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/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // FIXME: Sema shouldn't depend on Lex
32 #include "clang/Lex/ModuleLoader.h" // FIXME: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // FIXME: Sema shouldn't depend on Lex
34 #include "clang/Parse/ParseDiagnostic.h"
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 using namespace clang;
50 using namespace sema;
51 
52 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
53   if (OwnedType) {
54     Decl *Group[2] = { OwnedType, Ptr };
55     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
56   }
57 
58   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
59 }
60 
61 namespace {
62 
63 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
64  public:
65   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
66       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
67     WantExpressionKeywords = false;
68     WantCXXNamedCasts = false;
69     WantRemainingKeywords = false;
70   }
71 
72   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
73     if (NamedDecl *ND = candidate.getCorrectionDecl())
74       return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
75           (AllowInvalidDecl || !ND->isInvalidDecl());
76     else
77       return !WantClassName && candidate.isKeyword();
78   }
79 
80  private:
81   bool AllowInvalidDecl;
82   bool WantClassName;
83 };
84 
85 }
86 
87 /// \brief Determine whether the token kind starts a simple-type-specifier.
88 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
89   switch (Kind) {
90   // FIXME: Take into account the current language when deciding whether a
91   // token kind is a valid type specifier
92   case tok::kw_short:
93   case tok::kw_long:
94   case tok::kw___int64:
95   case tok::kw___int128:
96   case tok::kw_signed:
97   case tok::kw_unsigned:
98   case tok::kw_void:
99   case tok::kw_char:
100   case tok::kw_int:
101   case tok::kw_half:
102   case tok::kw_float:
103   case tok::kw_double:
104   case tok::kw_wchar_t:
105   case tok::kw_bool:
106   case tok::kw___underlying_type:
107     return true;
108 
109   case tok::annot_typename:
110   case tok::kw_char16_t:
111   case tok::kw_char32_t:
112   case tok::kw_typeof:
113   case tok::annot_decltype:
114   case tok::kw_decltype:
115     return getLangOpts().CPlusPlus;
116 
117   default:
118     break;
119   }
120 
121   return false;
122 }
123 
124 /// \brief If the identifier refers to a type name within this scope,
125 /// return the declaration of that type.
126 ///
127 /// This routine performs ordinary name lookup of the identifier II
128 /// within the given scope, with optional C++ scope specifier SS, to
129 /// determine whether the name refers to a type. If so, returns an
130 /// opaque pointer (actually a QualType) corresponding to that
131 /// type. Otherwise, returns NULL.
132 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
133                              Scope *S, CXXScopeSpec *SS,
134                              bool isClassName, bool HasTrailingDot,
135                              ParsedType ObjectTypePtr,
136                              bool IsCtorOrDtorName,
137                              bool WantNontrivialTypeSourceInfo,
138                              IdentifierInfo **CorrectedII) {
139   // Determine where we will perform name lookup.
140   DeclContext *LookupCtx = 0;
141   if (ObjectTypePtr) {
142     QualType ObjectType = ObjectTypePtr.get();
143     if (ObjectType->isRecordType())
144       LookupCtx = computeDeclContext(ObjectType);
145   } else if (SS && SS->isNotEmpty()) {
146     LookupCtx = computeDeclContext(*SS, false);
147 
148     if (!LookupCtx) {
149       if (isDependentScopeSpecifier(*SS)) {
150         // C++ [temp.res]p3:
151         //   A qualified-id that refers to a type and in which the
152         //   nested-name-specifier depends on a template-parameter (14.6.2)
153         //   shall be prefixed by the keyword typename to indicate that the
154         //   qualified-id denotes a type, forming an
155         //   elaborated-type-specifier (7.1.5.3).
156         //
157         // We therefore do not perform any name lookup if the result would
158         // refer to a member of an unknown specialization.
159         if (!isClassName && !IsCtorOrDtorName)
160           return ParsedType();
161 
162         // We know from the grammar that this name refers to a type,
163         // so build a dependent node to describe the type.
164         if (WantNontrivialTypeSourceInfo)
165           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
166 
167         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
168         QualType T =
169           CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
170                             II, NameLoc);
171 
172           return ParsedType::make(T);
173       }
174 
175       return ParsedType();
176     }
177 
178     if (!LookupCtx->isDependentContext() &&
179         RequireCompleteDeclContext(*SS, LookupCtx))
180       return ParsedType();
181   }
182 
183   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
184   // lookup for class-names.
185   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
186                                       LookupOrdinaryName;
187   LookupResult Result(*this, &II, NameLoc, Kind);
188   if (LookupCtx) {
189     // Perform "qualified" name lookup into the declaration context we
190     // computed, which is either the type of the base of a member access
191     // expression or the declaration context associated with a prior
192     // nested-name-specifier.
193     LookupQualifiedName(Result, LookupCtx);
194 
195     if (ObjectTypePtr && Result.empty()) {
196       // C++ [basic.lookup.classref]p3:
197       //   If the unqualified-id is ~type-name, the type-name is looked up
198       //   in the context of the entire postfix-expression. If the type T of
199       //   the object expression is of a class type C, the type-name is also
200       //   looked up in the scope of class C. At least one of the lookups shall
201       //   find a name that refers to (possibly cv-qualified) T.
202       LookupName(Result, S);
203     }
204   } else {
205     // Perform unqualified name lookup.
206     LookupName(Result, S);
207   }
208 
209   NamedDecl *IIDecl = 0;
210   switch (Result.getResultKind()) {
211   case LookupResult::NotFound:
212   case LookupResult::NotFoundInCurrentInstantiation:
213     if (CorrectedII) {
214       TypeNameValidatorCCC Validator(true, isClassName);
215       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
216                                               Kind, S, SS, Validator);
217       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
218       TemplateTy Template;
219       bool MemberOfUnknownSpecialization;
220       UnqualifiedId TemplateName;
221       TemplateName.setIdentifier(NewII, NameLoc);
222       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
223       CXXScopeSpec NewSS, *NewSSPtr = SS;
224       if (SS && NNS) {
225         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226         NewSSPtr = &NewSS;
227       }
228       if (Correction && (NNS || NewII != &II) &&
229           // Ignore a correction to a template type as the to-be-corrected
230           // identifier is not a template (typo correction for template names
231           // is handled elsewhere).
232           !(getLangOpts().CPlusPlus && NewSSPtr &&
233             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
234                            false, Template, MemberOfUnknownSpecialization))) {
235         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
236                                     isClassName, HasTrailingDot, ObjectTypePtr,
237                                     IsCtorOrDtorName,
238                                     WantNontrivialTypeSourceInfo);
239         if (Ty) {
240           diagnoseTypo(Correction,
241                        PDiag(diag::err_unknown_type_or_class_name_suggest)
242                          << Result.getLookupName() << isClassName);
243           if (SS && NNS)
244             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
245           *CorrectedII = NewII;
246           return Ty;
247         }
248       }
249     }
250     // If typo correction failed or was not performed, fall through
251   case LookupResult::FoundOverloaded:
252   case LookupResult::FoundUnresolvedValue:
253     Result.suppressDiagnostics();
254     return ParsedType();
255 
256   case LookupResult::Ambiguous:
257     // Recover from type-hiding ambiguities by hiding the type.  We'll
258     // do the lookup again when looking for an object, and we can
259     // diagnose the error then.  If we don't do this, then the error
260     // about hiding the type will be immediately followed by an error
261     // that only makes sense if the identifier was treated like a type.
262     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
263       Result.suppressDiagnostics();
264       return ParsedType();
265     }
266 
267     // Look to see if we have a type anywhere in the list of results.
268     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
269          Res != ResEnd; ++Res) {
270       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
271         if (!IIDecl ||
272             (*Res)->getLocation().getRawEncoding() <
273               IIDecl->getLocation().getRawEncoding())
274           IIDecl = *Res;
275       }
276     }
277 
278     if (!IIDecl) {
279       // None of the entities we found is a type, so there is no way
280       // to even assume that the result is a type. In this case, don't
281       // complain about the ambiguity. The parser will either try to
282       // perform this lookup again (e.g., as an object name), which
283       // will produce the ambiguity, or will complain that it expected
284       // a type name.
285       Result.suppressDiagnostics();
286       return ParsedType();
287     }
288 
289     // We found a type within the ambiguous lookup; diagnose the
290     // ambiguity and then return that type. This might be the right
291     // answer, or it might not be, but it suppresses any attempt to
292     // perform the name lookup again.
293     break;
294 
295   case LookupResult::Found:
296     IIDecl = Result.getFoundDecl();
297     break;
298   }
299 
300   assert(IIDecl && "Didn't find decl");
301 
302   QualType T;
303   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
304     DiagnoseUseOfDecl(IIDecl, NameLoc);
305 
306     if (T.isNull())
307       T = Context.getTypeDeclType(TD);
308 
309     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
310     // constructor or destructor name (in such a case, the scope specifier
311     // will be attached to the enclosing Expr or Decl node).
312     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
313       if (WantNontrivialTypeSourceInfo) {
314         // Construct a type with type-source information.
315         TypeLocBuilder Builder;
316         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
317 
318         T = getElaboratedType(ETK_None, *SS, T);
319         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
320         ElabTL.setElaboratedKeywordLoc(SourceLocation());
321         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
322         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
323       } else {
324         T = getElaboratedType(ETK_None, *SS, T);
325       }
326     }
327   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
328     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
329     if (!HasTrailingDot)
330       T = Context.getObjCInterfaceType(IDecl);
331   }
332 
333   if (T.isNull()) {
334     // If it's not plausibly a type, suppress diagnostics.
335     Result.suppressDiagnostics();
336     return ParsedType();
337   }
338   return ParsedType::make(T);
339 }
340 
341 /// isTagName() - This method is called *for error recovery purposes only*
342 /// to determine if the specified name is a valid tag name ("struct foo").  If
343 /// so, this returns the TST for the tag corresponding to it (TST_enum,
344 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
345 /// cases in C where the user forgot to specify the tag.
346 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
347   // Do a tag name lookup in this scope.
348   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
349   LookupName(R, S, false);
350   R.suppressDiagnostics();
351   if (R.getResultKind() == LookupResult::Found)
352     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
353       switch (TD->getTagKind()) {
354       case TTK_Struct: return DeclSpec::TST_struct;
355       case TTK_Interface: return DeclSpec::TST_interface;
356       case TTK_Union:  return DeclSpec::TST_union;
357       case TTK_Class:  return DeclSpec::TST_class;
358       case TTK_Enum:   return DeclSpec::TST_enum;
359       }
360     }
361 
362   return DeclSpec::TST_unspecified;
363 }
364 
365 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
366 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
367 /// then downgrade the missing typename error to a warning.
368 /// This is needed for MSVC compatibility; Example:
369 /// @code
370 /// template<class T> class A {
371 /// public:
372 ///   typedef int TYPE;
373 /// };
374 /// template<class T> class B : public A<T> {
375 /// public:
376 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
377 /// };
378 /// @endcode
379 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
380   if (CurContext->isRecord()) {
381     const Type *Ty = SS->getScopeRep()->getAsType();
382 
383     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
384     for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
385           BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
386       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
387         return true;
388     return S->isFunctionPrototypeScope();
389   }
390   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
391 }
392 
393 bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
394                                    SourceLocation IILoc,
395                                    Scope *S,
396                                    CXXScopeSpec *SS,
397                                    ParsedType &SuggestedType) {
398   // We don't have anything to suggest (yet).
399   SuggestedType = ParsedType();
400 
401   // There may have been a typo in the name of the type. Look up typo
402   // results, in case we have something that we can suggest.
403   TypeNameValidatorCCC Validator(false);
404   if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
405                                              LookupOrdinaryName, S, SS,
406                                              Validator)) {
407     if (Corrected.isKeyword()) {
408       // We corrected to a keyword.
409       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
410       II = Corrected.getCorrectionAsIdentifierInfo();
411     } else {
412       // We found a similarly-named type or interface; suggest that.
413       if (!SS || !SS->isSet()) {
414         diagnoseTypo(Corrected,
415                      PDiag(diag::err_unknown_typename_suggest) << II);
416       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
417         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
418         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
419                                 II->getName().equals(CorrectedStr);
420         diagnoseTypo(Corrected,
421                      PDiag(diag::err_unknown_nested_typename_suggest)
422                        << II << DC << DroppedSpecifier << SS->getRange());
423       } else {
424         llvm_unreachable("could not have corrected a typo here");
425       }
426 
427       CXXScopeSpec tmpSS;
428       if (Corrected.getCorrectionSpecifier())
429         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
430                           SourceRange(IILoc));
431       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
432                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
433                                   false, ParsedType(),
434                                   /*IsCtorOrDtorName=*/false,
435                                   /*NonTrivialTypeSourceInfo=*/true);
436     }
437     return true;
438   }
439 
440   if (getLangOpts().CPlusPlus) {
441     // See if II is a class template that the user forgot to pass arguments to.
442     UnqualifiedId Name;
443     Name.setIdentifier(II, IILoc);
444     CXXScopeSpec EmptySS;
445     TemplateTy TemplateResult;
446     bool MemberOfUnknownSpecialization;
447     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
448                        Name, ParsedType(), true, TemplateResult,
449                        MemberOfUnknownSpecialization) == TNK_Type_template) {
450       TemplateName TplName = TemplateResult.get();
451       Diag(IILoc, diag::err_template_missing_args) << TplName;
452       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
453         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
454           << TplDecl->getTemplateParameters()->getSourceRange();
455       }
456       return true;
457     }
458   }
459 
460   // FIXME: Should we move the logic that tries to recover from a missing tag
461   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
462 
463   if (!SS || (!SS->isSet() && !SS->isInvalid()))
464     Diag(IILoc, diag::err_unknown_typename) << II;
465   else if (DeclContext *DC = computeDeclContext(*SS, false))
466     Diag(IILoc, diag::err_typename_nested_not_found)
467       << II << DC << SS->getRange();
468   else if (isDependentScopeSpecifier(*SS)) {
469     unsigned DiagID = diag::err_typename_missing;
470     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
471       DiagID = diag::warn_typename_missing;
472 
473     Diag(SS->getRange().getBegin(), DiagID)
474       << SS->getScopeRep() << II->getName()
475       << SourceRange(SS->getRange().getBegin(), IILoc)
476       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
477     SuggestedType = ActOnTypenameType(S, SourceLocation(),
478                                       *SS, *II, IILoc).get();
479   } else {
480     assert(SS && SS->isInvalid() &&
481            "Invalid scope specifier has already been diagnosed");
482   }
483 
484   return true;
485 }
486 
487 /// \brief Determine whether the given result set contains either a type name
488 /// or
489 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
490   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
491                        NextToken.is(tok::less);
492 
493   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
494     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
495       return true;
496 
497     if (CheckTemplate && isa<TemplateDecl>(*I))
498       return true;
499   }
500 
501   return false;
502 }
503 
504 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
505                                     Scope *S, CXXScopeSpec &SS,
506                                     IdentifierInfo *&Name,
507                                     SourceLocation NameLoc) {
508   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
509   SemaRef.LookupParsedName(R, S, &SS);
510   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
511     const char *TagName = 0;
512     const char *FixItTagName = 0;
513     switch (Tag->getTagKind()) {
514       case TTK_Class:
515         TagName = "class";
516         FixItTagName = "class ";
517         break;
518 
519       case TTK_Enum:
520         TagName = "enum";
521         FixItTagName = "enum ";
522         break;
523 
524       case TTK_Struct:
525         TagName = "struct";
526         FixItTagName = "struct ";
527         break;
528 
529       case TTK_Interface:
530         TagName = "__interface";
531         FixItTagName = "__interface ";
532         break;
533 
534       case TTK_Union:
535         TagName = "union";
536         FixItTagName = "union ";
537         break;
538     }
539 
540     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
541       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
542       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
543 
544     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
545          I != IEnd; ++I)
546       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
547         << Name << TagName;
548 
549     // Replace lookup results with just the tag decl.
550     Result.clear(Sema::LookupTagName);
551     SemaRef.LookupParsedName(Result, S, &SS);
552     return true;
553   }
554 
555   return false;
556 }
557 
558 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
559 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
560                                   QualType T, SourceLocation NameLoc) {
561   ASTContext &Context = S.Context;
562 
563   TypeLocBuilder Builder;
564   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
565 
566   T = S.getElaboratedType(ETK_None, SS, T);
567   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
568   ElabTL.setElaboratedKeywordLoc(SourceLocation());
569   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
570   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
571 }
572 
573 Sema::NameClassification Sema::ClassifyName(Scope *S,
574                                             CXXScopeSpec &SS,
575                                             IdentifierInfo *&Name,
576                                             SourceLocation NameLoc,
577                                             const Token &NextToken,
578                                             bool IsAddressOfOperand,
579                                             CorrectionCandidateCallback *CCC) {
580   DeclarationNameInfo NameInfo(Name, NameLoc);
581   ObjCMethodDecl *CurMethod = getCurMethodDecl();
582 
583   if (NextToken.is(tok::coloncolon)) {
584     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
585                                 QualType(), false, SS, 0, false);
586 
587   }
588 
589   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
590   LookupParsedName(Result, S, &SS, !CurMethod);
591 
592   // Perform lookup for Objective-C instance variables (including automatically
593   // synthesized instance variables), if we're in an Objective-C method.
594   // FIXME: This lookup really, really needs to be folded in to the normal
595   // unqualified lookup mechanism.
596   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
597     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
598     if (E.get() || E.isInvalid())
599       return E;
600   }
601 
602   bool SecondTry = false;
603   bool IsFilteredTemplateName = false;
604 
605 Corrected:
606   switch (Result.getResultKind()) {
607   case LookupResult::NotFound:
608     // If an unqualified-id is followed by a '(', then we have a function
609     // call.
610     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
611       // In C++, this is an ADL-only call.
612       // FIXME: Reference?
613       if (getLangOpts().CPlusPlus)
614         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
615 
616       // C90 6.3.2.2:
617       //   If the expression that precedes the parenthesized argument list in a
618       //   function call consists solely of an identifier, and if no
619       //   declaration is visible for this identifier, the identifier is
620       //   implicitly declared exactly as if, in the innermost block containing
621       //   the function call, the declaration
622       //
623       //     extern int identifier ();
624       //
625       //   appeared.
626       //
627       // We also allow this in C99 as an extension.
628       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
629         Result.addDecl(D);
630         Result.resolveKind();
631         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
632       }
633     }
634 
635     // In C, we first see whether there is a tag type by the same name, in
636     // which case it's likely that the user just forget to write "enum",
637     // "struct", or "union".
638     if (!getLangOpts().CPlusPlus && !SecondTry &&
639         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
640       break;
641     }
642 
643     // Perform typo correction to determine if there is another name that is
644     // close to this name.
645     if (!SecondTry && CCC) {
646       SecondTry = true;
647       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
648                                                  Result.getLookupKind(), S,
649                                                  &SS, *CCC)) {
650         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
651         unsigned QualifiedDiag = diag::err_no_member_suggest;
652 
653         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
654         NamedDecl *UnderlyingFirstDecl
655           = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
656         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
657             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
658           UnqualifiedDiag = diag::err_no_template_suggest;
659           QualifiedDiag = diag::err_no_member_template_suggest;
660         } else if (UnderlyingFirstDecl &&
661                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
662                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
663                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
664           UnqualifiedDiag = diag::err_unknown_typename_suggest;
665           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
666         }
667 
668         if (SS.isEmpty()) {
669           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
670         } else {// FIXME: is this even reachable? Test it.
671           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
672           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
673                                   Name->getName().equals(CorrectedStr);
674           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
675                                     << Name << computeDeclContext(SS, false)
676                                     << DroppedSpecifier << SS.getRange());
677         }
678 
679         // Update the name, so that the caller has the new name.
680         Name = Corrected.getCorrectionAsIdentifierInfo();
681 
682         // Typo correction corrected to a keyword.
683         if (Corrected.isKeyword())
684           return Name;
685 
686         // Also update the LookupResult...
687         // FIXME: This should probably go away at some point
688         Result.clear();
689         Result.setLookupName(Corrected.getCorrection());
690         if (FirstDecl)
691           Result.addDecl(FirstDecl);
692 
693         // If we found an Objective-C instance variable, let
694         // LookupInObjCMethod build the appropriate expression to
695         // reference the ivar.
696         // FIXME: This is a gross hack.
697         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
698           Result.clear();
699           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
700           return E;
701         }
702 
703         goto Corrected;
704       }
705     }
706 
707     // We failed to correct; just fall through and let the parser deal with it.
708     Result.suppressDiagnostics();
709     return NameClassification::Unknown();
710 
711   case LookupResult::NotFoundInCurrentInstantiation: {
712     // We performed name lookup into the current instantiation, and there were
713     // dependent bases, so we treat this result the same way as any other
714     // dependent nested-name-specifier.
715 
716     // C++ [temp.res]p2:
717     //   A name used in a template declaration or definition and that is
718     //   dependent on a template-parameter is assumed not to name a type
719     //   unless the applicable name lookup finds a type name or the name is
720     //   qualified by the keyword typename.
721     //
722     // FIXME: If the next token is '<', we might want to ask the parser to
723     // perform some heroics to see if we actually have a
724     // template-argument-list, which would indicate a missing 'template'
725     // keyword here.
726     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
727                                       NameInfo, IsAddressOfOperand,
728                                       /*TemplateArgs=*/0);
729   }
730 
731   case LookupResult::Found:
732   case LookupResult::FoundOverloaded:
733   case LookupResult::FoundUnresolvedValue:
734     break;
735 
736   case LookupResult::Ambiguous:
737     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
738         hasAnyAcceptableTemplateNames(Result)) {
739       // C++ [temp.local]p3:
740       //   A lookup that finds an injected-class-name (10.2) can result in an
741       //   ambiguity in certain cases (for example, if it is found in more than
742       //   one base class). If all of the injected-class-names that are found
743       //   refer to specializations of the same class template, and if the name
744       //   is followed by a template-argument-list, the reference refers to the
745       //   class template itself and not a specialization thereof, and is not
746       //   ambiguous.
747       //
748       // This filtering can make an ambiguous result into an unambiguous one,
749       // so try again after filtering out template names.
750       FilterAcceptableTemplateNames(Result);
751       if (!Result.isAmbiguous()) {
752         IsFilteredTemplateName = true;
753         break;
754       }
755     }
756 
757     // Diagnose the ambiguity and return an error.
758     return NameClassification::Error();
759   }
760 
761   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
762       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
763     // C++ [temp.names]p3:
764     //   After name lookup (3.4) finds that a name is a template-name or that
765     //   an operator-function-id or a literal- operator-id refers to a set of
766     //   overloaded functions any member of which is a function template if
767     //   this is followed by a <, the < is always taken as the delimiter of a
768     //   template-argument-list and never as the less-than operator.
769     if (!IsFilteredTemplateName)
770       FilterAcceptableTemplateNames(Result);
771 
772     if (!Result.empty()) {
773       bool IsFunctionTemplate;
774       bool IsVarTemplate;
775       TemplateName Template;
776       if (Result.end() - Result.begin() > 1) {
777         IsFunctionTemplate = true;
778         Template = Context.getOverloadedTemplateName(Result.begin(),
779                                                      Result.end());
780       } else {
781         TemplateDecl *TD
782           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
783         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
784         IsVarTemplate = isa<VarTemplateDecl>(TD);
785 
786         if (SS.isSet() && !SS.isInvalid())
787           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
788                                                     /*TemplateKeyword=*/false,
789                                                       TD);
790         else
791           Template = TemplateName(TD);
792       }
793 
794       if (IsFunctionTemplate) {
795         // Function templates always go through overload resolution, at which
796         // point we'll perform the various checks (e.g., accessibility) we need
797         // to based on which function we selected.
798         Result.suppressDiagnostics();
799 
800         return NameClassification::FunctionTemplate(Template);
801       }
802 
803       return IsVarTemplate ? NameClassification::VarTemplate(Template)
804                            : NameClassification::TypeTemplate(Template);
805     }
806   }
807 
808   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
809   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
810     DiagnoseUseOfDecl(Type, NameLoc);
811     QualType T = Context.getTypeDeclType(Type);
812     if (SS.isNotEmpty())
813       return buildNestedType(*this, SS, T, NameLoc);
814     return ParsedType::make(T);
815   }
816 
817   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
818   if (!Class) {
819     // FIXME: It's unfortunate that we don't have a Type node for handling this.
820     if (ObjCCompatibleAliasDecl *Alias
821                                 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
822       Class = Alias->getClassInterface();
823   }
824 
825   if (Class) {
826     DiagnoseUseOfDecl(Class, NameLoc);
827 
828     if (NextToken.is(tok::period)) {
829       // Interface. <something> is parsed as a property reference expression.
830       // Just return "unknown" as a fall-through for now.
831       Result.suppressDiagnostics();
832       return NameClassification::Unknown();
833     }
834 
835     QualType T = Context.getObjCInterfaceType(Class);
836     return ParsedType::make(T);
837   }
838 
839   // We can have a type template here if we're classifying a template argument.
840   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
841     return NameClassification::TypeTemplate(
842         TemplateName(cast<TemplateDecl>(FirstDecl)));
843 
844   // Check for a tag type hidden by a non-type decl in a few cases where it
845   // seems likely a type is wanted instead of the non-type that was found.
846   bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
847   if ((NextToken.is(tok::identifier) ||
848        (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
849       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
850     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
851     DiagnoseUseOfDecl(Type, NameLoc);
852     QualType T = Context.getTypeDeclType(Type);
853     if (SS.isNotEmpty())
854       return buildNestedType(*this, SS, T, NameLoc);
855     return ParsedType::make(T);
856   }
857 
858   if (FirstDecl->isCXXClassMember())
859     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
860 
861   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
862   return BuildDeclarationNameExpr(SS, Result, ADL);
863 }
864 
865 // Determines the context to return to after temporarily entering a
866 // context.  This depends in an unnecessarily complicated way on the
867 // exact ordering of callbacks from the parser.
868 DeclContext *Sema::getContainingDC(DeclContext *DC) {
869 
870   // Functions defined inline within classes aren't parsed until we've
871   // finished parsing the top-level class, so the top-level class is
872   // the context we'll need to return to.
873   // A Lambda call operator whose parent is a class must not be treated
874   // as an inline member function.  A Lambda can be used legally
875   // either as an in-class member initializer or a default argument.  These
876   // are parsed once the class has been marked complete and so the containing
877   // context would be the nested class (when the lambda is defined in one);
878   // If the class is not complete, then the lambda is being used in an
879   // ill-formed fashion (such as to specify the width of a bit-field, or
880   // in an array-bound) - in which case we still want to return the
881   // lexically containing DC (which could be a nested class).
882   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
883     DC = DC->getLexicalParent();
884 
885     // A function not defined within a class will always return to its
886     // lexical context.
887     if (!isa<CXXRecordDecl>(DC))
888       return DC;
889 
890     // A C++ inline method/friend is parsed *after* the topmost class
891     // it was declared in is fully parsed ("complete");  the topmost
892     // class is the context we need to return to.
893     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
894       DC = RD;
895 
896     // Return the declaration context of the topmost class the inline method is
897     // declared in.
898     return DC;
899   }
900 
901   return DC->getLexicalParent();
902 }
903 
904 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
905   assert(getContainingDC(DC) == CurContext &&
906       "The next DeclContext should be lexically contained in the current one.");
907   CurContext = DC;
908   S->setEntity(DC);
909 }
910 
911 void Sema::PopDeclContext() {
912   assert(CurContext && "DeclContext imbalance!");
913 
914   CurContext = getContainingDC(CurContext);
915   assert(CurContext && "Popped translation unit!");
916 }
917 
918 /// EnterDeclaratorContext - Used when we must lookup names in the context
919 /// of a declarator's nested name specifier.
920 ///
921 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
922   // C++0x [basic.lookup.unqual]p13:
923   //   A name used in the definition of a static data member of class
924   //   X (after the qualified-id of the static member) is looked up as
925   //   if the name was used in a member function of X.
926   // C++0x [basic.lookup.unqual]p14:
927   //   If a variable member of a namespace is defined outside of the
928   //   scope of its namespace then any name used in the definition of
929   //   the variable member (after the declarator-id) is looked up as
930   //   if the definition of the variable member occurred in its
931   //   namespace.
932   // Both of these imply that we should push a scope whose context
933   // is the semantic context of the declaration.  We can't use
934   // PushDeclContext here because that context is not necessarily
935   // lexically contained in the current context.  Fortunately,
936   // the containing scope should have the appropriate information.
937 
938   assert(!S->getEntity() && "scope already has entity");
939 
940 #ifndef NDEBUG
941   Scope *Ancestor = S->getParent();
942   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
943   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
944 #endif
945 
946   CurContext = DC;
947   S->setEntity(DC);
948 }
949 
950 void Sema::ExitDeclaratorContext(Scope *S) {
951   assert(S->getEntity() == CurContext && "Context imbalance!");
952 
953   // Switch back to the lexical context.  The safety of this is
954   // enforced by an assert in EnterDeclaratorContext.
955   Scope *Ancestor = S->getParent();
956   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
957   CurContext = Ancestor->getEntity();
958 
959   // We don't need to do anything with the scope, which is going to
960   // disappear.
961 }
962 
963 
964 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
965   FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
966   if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
967     // We assume that the caller has already called
968     // ActOnReenterTemplateScope
969     FD = TFD->getTemplatedDecl();
970   }
971   if (!FD)
972     return;
973 
974   // Same implementation as PushDeclContext, but enters the context
975   // from the lexical parent, rather than the top-level class.
976   assert(CurContext == FD->getLexicalParent() &&
977     "The next DeclContext should be lexically contained in the current one.");
978   CurContext = FD;
979   S->setEntity(CurContext);
980 
981   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
982     ParmVarDecl *Param = FD->getParamDecl(P);
983     // If the parameter has an identifier, then add it to the scope
984     if (Param->getIdentifier()) {
985       S->AddDecl(Param);
986       IdResolver.AddDecl(Param);
987     }
988   }
989 }
990 
991 
992 void Sema::ActOnExitFunctionContext() {
993   // Same implementation as PopDeclContext, but returns to the lexical parent,
994   // rather than the top-level class.
995   assert(CurContext && "DeclContext imbalance!");
996   CurContext = CurContext->getLexicalParent();
997   assert(CurContext && "Popped translation unit!");
998 }
999 
1000 
1001 /// \brief Determine whether we allow overloading of the function
1002 /// PrevDecl with another declaration.
1003 ///
1004 /// This routine determines whether overloading is possible, not
1005 /// whether some new function is actually an overload. It will return
1006 /// true in C++ (where we can always provide overloads) or, as an
1007 /// extension, in C when the previous function is already an
1008 /// overloaded function declaration or has the "overloadable"
1009 /// attribute.
1010 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1011                                        ASTContext &Context) {
1012   if (Context.getLangOpts().CPlusPlus)
1013     return true;
1014 
1015   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1016     return true;
1017 
1018   return (Previous.getResultKind() == LookupResult::Found
1019           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1020 }
1021 
1022 /// Add this decl to the scope shadowed decl chains.
1023 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1024   // Move up the scope chain until we find the nearest enclosing
1025   // non-transparent context. The declaration will be introduced into this
1026   // scope.
1027   while (S->getEntity() && S->getEntity()->isTransparentContext())
1028     S = S->getParent();
1029 
1030   // Add scoped declarations into their context, so that they can be
1031   // found later. Declarations without a context won't be inserted
1032   // into any context.
1033   if (AddToContext)
1034     CurContext->addDecl(D);
1035 
1036   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1037   // are function-local declarations.
1038   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1039       !D->getDeclContext()->getRedeclContext()->Equals(
1040         D->getLexicalDeclContext()->getRedeclContext()) &&
1041       !D->getLexicalDeclContext()->isFunctionOrMethod())
1042     return;
1043 
1044   // Template instantiations should also not be pushed into scope.
1045   if (isa<FunctionDecl>(D) &&
1046       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1047     return;
1048 
1049   // If this replaces anything in the current scope,
1050   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1051                                IEnd = IdResolver.end();
1052   for (; I != IEnd; ++I) {
1053     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1054       S->RemoveDecl(*I);
1055       IdResolver.RemoveDecl(*I);
1056 
1057       // Should only need to replace one decl.
1058       break;
1059     }
1060   }
1061 
1062   S->AddDecl(D);
1063 
1064   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1065     // Implicitly-generated labels may end up getting generated in an order that
1066     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1067     // the label at the appropriate place in the identifier chain.
1068     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1069       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1070       if (IDC == CurContext) {
1071         if (!S->isDeclScope(*I))
1072           continue;
1073       } else if (IDC->Encloses(CurContext))
1074         break;
1075     }
1076 
1077     IdResolver.InsertDeclAfter(I, D);
1078   } else {
1079     IdResolver.AddDecl(D);
1080   }
1081 }
1082 
1083 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1084   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1085     TUScope->AddDecl(D);
1086 }
1087 
1088 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1089                          bool AllowInlineNamespace) {
1090   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1091 }
1092 
1093 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1094   DeclContext *TargetDC = DC->getPrimaryContext();
1095   do {
1096     if (DeclContext *ScopeDC = S->getEntity())
1097       if (ScopeDC->getPrimaryContext() == TargetDC)
1098         return S;
1099   } while ((S = S->getParent()));
1100 
1101   return 0;
1102 }
1103 
1104 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1105                                             DeclContext*,
1106                                             ASTContext&);
1107 
1108 /// Filters out lookup results that don't fall within the given scope
1109 /// as determined by isDeclInScope.
1110 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1111                                 bool ConsiderLinkage,
1112                                 bool AllowInlineNamespace) {
1113   LookupResult::Filter F = R.makeFilter();
1114   while (F.hasNext()) {
1115     NamedDecl *D = F.next();
1116 
1117     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1118       continue;
1119 
1120     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1121       continue;
1122 
1123     F.erase();
1124   }
1125 
1126   F.done();
1127 }
1128 
1129 static bool isUsingDecl(NamedDecl *D) {
1130   return isa<UsingShadowDecl>(D) ||
1131          isa<UnresolvedUsingTypenameDecl>(D) ||
1132          isa<UnresolvedUsingValueDecl>(D);
1133 }
1134 
1135 /// Removes using shadow declarations from the lookup results.
1136 static void RemoveUsingDecls(LookupResult &R) {
1137   LookupResult::Filter F = R.makeFilter();
1138   while (F.hasNext())
1139     if (isUsingDecl(F.next()))
1140       F.erase();
1141 
1142   F.done();
1143 }
1144 
1145 /// \brief Check for this common pattern:
1146 /// @code
1147 /// class S {
1148 ///   S(const S&); // DO NOT IMPLEMENT
1149 ///   void operator=(const S&); // DO NOT IMPLEMENT
1150 /// };
1151 /// @endcode
1152 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1153   // FIXME: Should check for private access too but access is set after we get
1154   // the decl here.
1155   if (D->doesThisDeclarationHaveABody())
1156     return false;
1157 
1158   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1159     return CD->isCopyConstructor();
1160   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1161     return Method->isCopyAssignmentOperator();
1162   return false;
1163 }
1164 
1165 // We need this to handle
1166 //
1167 // typedef struct {
1168 //   void *foo() { return 0; }
1169 // } A;
1170 //
1171 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1172 // for example. If 'A', foo will have external linkage. If we have '*A',
1173 // foo will have no linkage. Since we can't know until we get to the end
1174 // of the typedef, this function finds out if D might have non-external linkage.
1175 // Callers should verify at the end of the TU if it D has external linkage or
1176 // not.
1177 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1178   const DeclContext *DC = D->getDeclContext();
1179   while (!DC->isTranslationUnit()) {
1180     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1181       if (!RD->hasNameForLinkage())
1182         return true;
1183     }
1184     DC = DC->getParent();
1185   }
1186 
1187   return !D->isExternallyVisible();
1188 }
1189 
1190 // FIXME: This needs to be refactored; some other isInMainFile users want
1191 // these semantics.
1192 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1193   if (S.TUKind != TU_Complete)
1194     return false;
1195   return S.SourceMgr.isInMainFile(Loc);
1196 }
1197 
1198 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1199   assert(D);
1200 
1201   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1202     return false;
1203 
1204   // Ignore class templates.
1205   if (D->getDeclContext()->isDependentContext() ||
1206       D->getLexicalDeclContext()->isDependentContext())
1207     return false;
1208 
1209   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1210     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1211       return false;
1212 
1213     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1214       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1215         return false;
1216     } else {
1217       // 'static inline' functions are defined in headers; don't warn.
1218       if (FD->isInlineSpecified() &&
1219           !isMainFileLoc(*this, FD->getLocation()))
1220         return false;
1221     }
1222 
1223     if (FD->doesThisDeclarationHaveABody() &&
1224         Context.DeclMustBeEmitted(FD))
1225       return false;
1226   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1227     // Constants and utility variables are defined in headers with internal
1228     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1229     // like "inline".)
1230     if (!isMainFileLoc(*this, VD->getLocation()))
1231       return false;
1232 
1233     if (Context.DeclMustBeEmitted(VD))
1234       return false;
1235 
1236     if (VD->isStaticDataMember() &&
1237         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1238       return false;
1239   } else {
1240     return false;
1241   }
1242 
1243   // Only warn for unused decls internal to the translation unit.
1244   return mightHaveNonExternalLinkage(D);
1245 }
1246 
1247 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1248   if (!D)
1249     return;
1250 
1251   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1252     const FunctionDecl *First = FD->getFirstDecl();
1253     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1254       return; // First should already be in the vector.
1255   }
1256 
1257   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1258     const VarDecl *First = VD->getFirstDecl();
1259     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1260       return; // First should already be in the vector.
1261   }
1262 
1263   if (ShouldWarnIfUnusedFileScopedDecl(D))
1264     UnusedFileScopedDecls.push_back(D);
1265 }
1266 
1267 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1268   if (D->isInvalidDecl())
1269     return false;
1270 
1271   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1272       D->hasAttr<ObjCPreciseLifetimeAttr>())
1273     return false;
1274 
1275   if (isa<LabelDecl>(D))
1276     return true;
1277 
1278   // White-list anything that isn't a local variable.
1279   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1280       !D->getDeclContext()->isFunctionOrMethod())
1281     return false;
1282 
1283   // Types of valid local variables should be complete, so this should succeed.
1284   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1285 
1286     // White-list anything with an __attribute__((unused)) type.
1287     QualType Ty = VD->getType();
1288 
1289     // Only look at the outermost level of typedef.
1290     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1291       if (TT->getDecl()->hasAttr<UnusedAttr>())
1292         return false;
1293     }
1294 
1295     // If we failed to complete the type for some reason, or if the type is
1296     // dependent, don't diagnose the variable.
1297     if (Ty->isIncompleteType() || Ty->isDependentType())
1298       return false;
1299 
1300     if (const TagType *TT = Ty->getAs<TagType>()) {
1301       const TagDecl *Tag = TT->getDecl();
1302       if (Tag->hasAttr<UnusedAttr>())
1303         return false;
1304 
1305       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1306         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1307           return false;
1308 
1309         if (const Expr *Init = VD->getInit()) {
1310           if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1311             Init = Cleanups->getSubExpr();
1312           const CXXConstructExpr *Construct =
1313             dyn_cast<CXXConstructExpr>(Init);
1314           if (Construct && !Construct->isElidable()) {
1315             CXXConstructorDecl *CD = Construct->getConstructor();
1316             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1317               return false;
1318           }
1319         }
1320       }
1321     }
1322 
1323     // TODO: __attribute__((unused)) templates?
1324   }
1325 
1326   return true;
1327 }
1328 
1329 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1330                                      FixItHint &Hint) {
1331   if (isa<LabelDecl>(D)) {
1332     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1333                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1334     if (AfterColon.isInvalid())
1335       return;
1336     Hint = FixItHint::CreateRemoval(CharSourceRange::
1337                                     getCharRange(D->getLocStart(), AfterColon));
1338   }
1339   return;
1340 }
1341 
1342 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1343 /// unless they are marked attr(unused).
1344 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1345   FixItHint Hint;
1346   if (!ShouldDiagnoseUnusedDecl(D))
1347     return;
1348 
1349   GenerateFixForUnusedDecl(D, Context, Hint);
1350 
1351   unsigned DiagID;
1352   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1353     DiagID = diag::warn_unused_exception_param;
1354   else if (isa<LabelDecl>(D))
1355     DiagID = diag::warn_unused_label;
1356   else
1357     DiagID = diag::warn_unused_variable;
1358 
1359   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1360 }
1361 
1362 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1363   // Verify that we have no forward references left.  If so, there was a goto
1364   // or address of a label taken, but no definition of it.  Label fwd
1365   // definitions are indicated with a null substmt.
1366   if (L->getStmt() == 0)
1367     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1368 }
1369 
1370 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1371   if (S->decl_empty()) return;
1372   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1373          "Scope shouldn't contain decls!");
1374 
1375   for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1376        I != E; ++I) {
1377     Decl *TmpD = (*I);
1378     assert(TmpD && "This decl didn't get pushed??");
1379 
1380     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1381     NamedDecl *D = cast<NamedDecl>(TmpD);
1382 
1383     if (!D->getDeclName()) continue;
1384 
1385     // Diagnose unused variables in this scope.
1386     if (!S->hasUnrecoverableErrorOccurred())
1387       DiagnoseUnusedDecl(D);
1388 
1389     // If this was a forward reference to a label, verify it was defined.
1390     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1391       CheckPoppedLabel(LD, *this);
1392 
1393     // Remove this name from our lexical scope.
1394     IdResolver.RemoveDecl(D);
1395   }
1396 }
1397 
1398 void Sema::ActOnStartFunctionDeclarator() {
1399   ++InFunctionDeclarator;
1400 }
1401 
1402 void Sema::ActOnEndFunctionDeclarator() {
1403   assert(InFunctionDeclarator);
1404   --InFunctionDeclarator;
1405 }
1406 
1407 /// \brief Look for an Objective-C class in the translation unit.
1408 ///
1409 /// \param Id The name of the Objective-C class we're looking for. If
1410 /// typo-correction fixes this name, the Id will be updated
1411 /// to the fixed name.
1412 ///
1413 /// \param IdLoc The location of the name in the translation unit.
1414 ///
1415 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1416 /// if there is no class with the given name.
1417 ///
1418 /// \returns The declaration of the named Objective-C class, or NULL if the
1419 /// class could not be found.
1420 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1421                                               SourceLocation IdLoc,
1422                                               bool DoTypoCorrection) {
1423   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1424   // creation from this context.
1425   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1426 
1427   if (!IDecl && DoTypoCorrection) {
1428     // Perform typo correction at the given location, but only if we
1429     // find an Objective-C class name.
1430     DeclFilterCCC<ObjCInterfaceDecl> Validator;
1431     if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1432                                        LookupOrdinaryName, TUScope, NULL,
1433                                        Validator)) {
1434       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1435       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1436       Id = IDecl->getIdentifier();
1437     }
1438   }
1439   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1440   // This routine must always return a class definition, if any.
1441   if (Def && Def->getDefinition())
1442       Def = Def->getDefinition();
1443   return Def;
1444 }
1445 
1446 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1447 /// from S, where a non-field would be declared. This routine copes
1448 /// with the difference between C and C++ scoping rules in structs and
1449 /// unions. For example, the following code is well-formed in C but
1450 /// ill-formed in C++:
1451 /// @code
1452 /// struct S6 {
1453 ///   enum { BAR } e;
1454 /// };
1455 ///
1456 /// void test_S6() {
1457 ///   struct S6 a;
1458 ///   a.e = BAR;
1459 /// }
1460 /// @endcode
1461 /// For the declaration of BAR, this routine will return a different
1462 /// scope. The scope S will be the scope of the unnamed enumeration
1463 /// within S6. In C++, this routine will return the scope associated
1464 /// with S6, because the enumeration's scope is a transparent
1465 /// context but structures can contain non-field names. In C, this
1466 /// routine will return the translation unit scope, since the
1467 /// enumeration's scope is a transparent context and structures cannot
1468 /// contain non-field names.
1469 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1470   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1471          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1472          (S->isClassScope() && !getLangOpts().CPlusPlus))
1473     S = S->getParent();
1474   return S;
1475 }
1476 
1477 /// \brief Looks up the declaration of "struct objc_super" and
1478 /// saves it for later use in building builtin declaration of
1479 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1480 /// pre-existing declaration exists no action takes place.
1481 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1482                                         IdentifierInfo *II) {
1483   if (!II->isStr("objc_msgSendSuper"))
1484     return;
1485   ASTContext &Context = ThisSema.Context;
1486 
1487   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1488                       SourceLocation(), Sema::LookupTagName);
1489   ThisSema.LookupName(Result, S);
1490   if (Result.getResultKind() == LookupResult::Found)
1491     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1492       Context.setObjCSuperType(Context.getTagDeclType(TD));
1493 }
1494 
1495 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1496 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1497 /// if we're creating this built-in in anticipation of redeclaring the
1498 /// built-in.
1499 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1500                                      Scope *S, bool ForRedeclaration,
1501                                      SourceLocation Loc) {
1502   LookupPredefedObjCSuperType(*this, S, II);
1503 
1504   Builtin::ID BID = (Builtin::ID)bid;
1505 
1506   ASTContext::GetBuiltinTypeError Error;
1507   QualType R = Context.GetBuiltinType(BID, Error);
1508   switch (Error) {
1509   case ASTContext::GE_None:
1510     // Okay
1511     break;
1512 
1513   case ASTContext::GE_Missing_stdio:
1514     if (ForRedeclaration)
1515       Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1516         << Context.BuiltinInfo.GetName(BID);
1517     return 0;
1518 
1519   case ASTContext::GE_Missing_setjmp:
1520     if (ForRedeclaration)
1521       Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1522         << Context.BuiltinInfo.GetName(BID);
1523     return 0;
1524 
1525   case ASTContext::GE_Missing_ucontext:
1526     if (ForRedeclaration)
1527       Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1528         << Context.BuiltinInfo.GetName(BID);
1529     return 0;
1530   }
1531 
1532   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1533     Diag(Loc, diag::ext_implicit_lib_function_decl)
1534       << Context.BuiltinInfo.GetName(BID)
1535       << R;
1536     if (Context.BuiltinInfo.getHeaderName(BID) &&
1537         Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1538           != DiagnosticsEngine::Ignored)
1539       Diag(Loc, diag::note_please_include_header)
1540         << Context.BuiltinInfo.getHeaderName(BID)
1541         << Context.BuiltinInfo.GetName(BID);
1542   }
1543 
1544   DeclContext *Parent = Context.getTranslationUnitDecl();
1545   if (getLangOpts().CPlusPlus) {
1546     LinkageSpecDecl *CLinkageDecl =
1547         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1548                                 LinkageSpecDecl::lang_c, false);
1549     CLinkageDecl->setImplicit();
1550     Parent->addDecl(CLinkageDecl);
1551     Parent = CLinkageDecl;
1552   }
1553 
1554   FunctionDecl *New = FunctionDecl::Create(Context,
1555                                            Parent,
1556                                            Loc, Loc, II, R, /*TInfo=*/0,
1557                                            SC_Extern,
1558                                            false,
1559                                            /*hasPrototype=*/true);
1560   New->setImplicit();
1561 
1562   // Create Decl objects for each parameter, adding them to the
1563   // FunctionDecl.
1564   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1565     SmallVector<ParmVarDecl*, 16> Params;
1566     for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1567       ParmVarDecl *parm =
1568         ParmVarDecl::Create(Context, New, SourceLocation(),
1569                             SourceLocation(), 0,
1570                             FT->getArgType(i), /*TInfo=*/0,
1571                             SC_None, 0);
1572       parm->setScopeInfo(0, i);
1573       Params.push_back(parm);
1574     }
1575     New->setParams(Params);
1576   }
1577 
1578   AddKnownFunctionAttributes(New);
1579   RegisterLocallyScopedExternCDecl(New, S);
1580 
1581   // TUScope is the translation-unit scope to insert this function into.
1582   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1583   // relate Scopes to DeclContexts, and probably eliminate CurContext
1584   // entirely, but we're not there yet.
1585   DeclContext *SavedContext = CurContext;
1586   CurContext = Parent;
1587   PushOnScopeChains(New, TUScope);
1588   CurContext = SavedContext;
1589   return New;
1590 }
1591 
1592 /// \brief Filter out any previous declarations that the given declaration
1593 /// should not consider because they are not permitted to conflict, e.g.,
1594 /// because they come from hidden sub-modules and do not refer to the same
1595 /// entity.
1596 static void filterNonConflictingPreviousDecls(ASTContext &context,
1597                                               NamedDecl *decl,
1598                                               LookupResult &previous){
1599   // This is only interesting when modules are enabled.
1600   if (!context.getLangOpts().Modules)
1601     return;
1602 
1603   // Empty sets are uninteresting.
1604   if (previous.empty())
1605     return;
1606 
1607   LookupResult::Filter filter = previous.makeFilter();
1608   while (filter.hasNext()) {
1609     NamedDecl *old = filter.next();
1610 
1611     // Non-hidden declarations are never ignored.
1612     if (!old->isHidden())
1613       continue;
1614 
1615     if (!old->isExternallyVisible())
1616       filter.erase();
1617   }
1618 
1619   filter.done();
1620 }
1621 
1622 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1623   QualType OldType;
1624   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1625     OldType = OldTypedef->getUnderlyingType();
1626   else
1627     OldType = Context.getTypeDeclType(Old);
1628   QualType NewType = New->getUnderlyingType();
1629 
1630   if (NewType->isVariablyModifiedType()) {
1631     // Must not redefine a typedef with a variably-modified type.
1632     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1633     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1634       << Kind << NewType;
1635     if (Old->getLocation().isValid())
1636       Diag(Old->getLocation(), diag::note_previous_definition);
1637     New->setInvalidDecl();
1638     return true;
1639   }
1640 
1641   if (OldType != NewType &&
1642       !OldType->isDependentType() &&
1643       !NewType->isDependentType() &&
1644       !Context.hasSameType(OldType, NewType)) {
1645     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1646     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1647       << Kind << NewType << OldType;
1648     if (Old->getLocation().isValid())
1649       Diag(Old->getLocation(), diag::note_previous_definition);
1650     New->setInvalidDecl();
1651     return true;
1652   }
1653   return false;
1654 }
1655 
1656 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1657 /// same name and scope as a previous declaration 'Old'.  Figure out
1658 /// how to resolve this situation, merging decls or emitting
1659 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1660 ///
1661 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1662   // If the new decl is known invalid already, don't bother doing any
1663   // merging checks.
1664   if (New->isInvalidDecl()) return;
1665 
1666   // Allow multiple definitions for ObjC built-in typedefs.
1667   // FIXME: Verify the underlying types are equivalent!
1668   if (getLangOpts().ObjC1) {
1669     const IdentifierInfo *TypeID = New->getIdentifier();
1670     switch (TypeID->getLength()) {
1671     default: break;
1672     case 2:
1673       {
1674         if (!TypeID->isStr("id"))
1675           break;
1676         QualType T = New->getUnderlyingType();
1677         if (!T->isPointerType())
1678           break;
1679         if (!T->isVoidPointerType()) {
1680           QualType PT = T->getAs<PointerType>()->getPointeeType();
1681           if (!PT->isStructureType())
1682             break;
1683         }
1684         Context.setObjCIdRedefinitionType(T);
1685         // Install the built-in type for 'id', ignoring the current definition.
1686         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1687         return;
1688       }
1689     case 5:
1690       if (!TypeID->isStr("Class"))
1691         break;
1692       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1693       // Install the built-in type for 'Class', ignoring the current definition.
1694       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1695       return;
1696     case 3:
1697       if (!TypeID->isStr("SEL"))
1698         break;
1699       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1700       // Install the built-in type for 'SEL', ignoring the current definition.
1701       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1702       return;
1703     }
1704     // Fall through - the typedef name was not a builtin type.
1705   }
1706 
1707   // Verify the old decl was also a type.
1708   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1709   if (!Old) {
1710     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1711       << New->getDeclName();
1712 
1713     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1714     if (OldD->getLocation().isValid())
1715       Diag(OldD->getLocation(), diag::note_previous_definition);
1716 
1717     return New->setInvalidDecl();
1718   }
1719 
1720   // If the old declaration is invalid, just give up here.
1721   if (Old->isInvalidDecl())
1722     return New->setInvalidDecl();
1723 
1724   // If the typedef types are not identical, reject them in all languages and
1725   // with any extensions enabled.
1726   if (isIncompatibleTypedef(Old, New))
1727     return;
1728 
1729   // The types match.  Link up the redeclaration chain and merge attributes if
1730   // the old declaration was a typedef.
1731   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1732     New->setPreviousDecl(Typedef);
1733     mergeDeclAttributes(New, Old);
1734   }
1735 
1736   if (getLangOpts().MicrosoftExt)
1737     return;
1738 
1739   if (getLangOpts().CPlusPlus) {
1740     // C++ [dcl.typedef]p2:
1741     //   In a given non-class scope, a typedef specifier can be used to
1742     //   redefine the name of any type declared in that scope to refer
1743     //   to the type to which it already refers.
1744     if (!isa<CXXRecordDecl>(CurContext))
1745       return;
1746 
1747     // C++0x [dcl.typedef]p4:
1748     //   In a given class scope, a typedef specifier can be used to redefine
1749     //   any class-name declared in that scope that is not also a typedef-name
1750     //   to refer to the type to which it already refers.
1751     //
1752     // This wording came in via DR424, which was a correction to the
1753     // wording in DR56, which accidentally banned code like:
1754     //
1755     //   struct S {
1756     //     typedef struct A { } A;
1757     //   };
1758     //
1759     // in the C++03 standard. We implement the C++0x semantics, which
1760     // allow the above but disallow
1761     //
1762     //   struct S {
1763     //     typedef int I;
1764     //     typedef int I;
1765     //   };
1766     //
1767     // since that was the intent of DR56.
1768     if (!isa<TypedefNameDecl>(Old))
1769       return;
1770 
1771     Diag(New->getLocation(), diag::err_redefinition)
1772       << New->getDeclName();
1773     Diag(Old->getLocation(), diag::note_previous_definition);
1774     return New->setInvalidDecl();
1775   }
1776 
1777   // Modules always permit redefinition of typedefs, as does C11.
1778   if (getLangOpts().Modules || getLangOpts().C11)
1779     return;
1780 
1781   // If we have a redefinition of a typedef in C, emit a warning.  This warning
1782   // is normally mapped to an error, but can be controlled with
1783   // -Wtypedef-redefinition.  If either the original or the redefinition is
1784   // in a system header, don't emit this for compatibility with GCC.
1785   if (getDiagnostics().getSuppressSystemWarnings() &&
1786       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1787        Context.getSourceManager().isInSystemHeader(New->getLocation())))
1788     return;
1789 
1790   Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1791     << New->getDeclName();
1792   Diag(Old->getLocation(), diag::note_previous_definition);
1793   return;
1794 }
1795 
1796 /// DeclhasAttr - returns true if decl Declaration already has the target
1797 /// attribute.
1798 static bool
1799 DeclHasAttr(const Decl *D, const Attr *A) {
1800   // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1801   // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1802   // responsible for making sure they are consistent.
1803   const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1804   if (AA)
1805     return false;
1806 
1807   // The following thread safety attributes can also be duplicated.
1808   switch (A->getKind()) {
1809     case attr::ExclusiveLocksRequired:
1810     case attr::SharedLocksRequired:
1811     case attr::LocksExcluded:
1812     case attr::ExclusiveLockFunction:
1813     case attr::SharedLockFunction:
1814     case attr::UnlockFunction:
1815     case attr::ExclusiveTrylockFunction:
1816     case attr::SharedTrylockFunction:
1817     case attr::GuardedBy:
1818     case attr::PtGuardedBy:
1819     case attr::AcquiredBefore:
1820     case attr::AcquiredAfter:
1821       return false;
1822     default:
1823       ;
1824   }
1825 
1826   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1827   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1828   for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1829     if ((*i)->getKind() == A->getKind()) {
1830       if (Ann) {
1831         if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1832           return true;
1833         continue;
1834       }
1835       // FIXME: Don't hardcode this check
1836       if (OA && isa<OwnershipAttr>(*i))
1837         return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1838       return true;
1839     }
1840 
1841   return false;
1842 }
1843 
1844 static bool isAttributeTargetADefinition(Decl *D) {
1845   if (VarDecl *VD = dyn_cast<VarDecl>(D))
1846     return VD->isThisDeclarationADefinition();
1847   if (TagDecl *TD = dyn_cast<TagDecl>(D))
1848     return TD->isCompleteDefinition() || TD->isBeingDefined();
1849   return true;
1850 }
1851 
1852 /// Merge alignment attributes from \p Old to \p New, taking into account the
1853 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1854 ///
1855 /// \return \c true if any attributes were added to \p New.
1856 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1857   // Look for alignas attributes on Old, and pick out whichever attribute
1858   // specifies the strictest alignment requirement.
1859   AlignedAttr *OldAlignasAttr = 0;
1860   AlignedAttr *OldStrictestAlignAttr = 0;
1861   unsigned OldAlign = 0;
1862   for (specific_attr_iterator<AlignedAttr>
1863          I = Old->specific_attr_begin<AlignedAttr>(),
1864          E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1865     // FIXME: We have no way of representing inherited dependent alignments
1866     // in a case like:
1867     //   template<int A, int B> struct alignas(A) X;
1868     //   template<int A, int B> struct alignas(B) X {};
1869     // For now, we just ignore any alignas attributes which are not on the
1870     // definition in such a case.
1871     if (I->isAlignmentDependent())
1872       return false;
1873 
1874     if (I->isAlignas())
1875       OldAlignasAttr = *I;
1876 
1877     unsigned Align = I->getAlignment(S.Context);
1878     if (Align > OldAlign) {
1879       OldAlign = Align;
1880       OldStrictestAlignAttr = *I;
1881     }
1882   }
1883 
1884   // Look for alignas attributes on New.
1885   AlignedAttr *NewAlignasAttr = 0;
1886   unsigned NewAlign = 0;
1887   for (specific_attr_iterator<AlignedAttr>
1888          I = New->specific_attr_begin<AlignedAttr>(),
1889          E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1890     if (I->isAlignmentDependent())
1891       return false;
1892 
1893     if (I->isAlignas())
1894       NewAlignasAttr = *I;
1895 
1896     unsigned Align = I->getAlignment(S.Context);
1897     if (Align > NewAlign)
1898       NewAlign = Align;
1899   }
1900 
1901   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1902     // Both declarations have 'alignas' attributes. We require them to match.
1903     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1904     // fall short. (If two declarations both have alignas, they must both match
1905     // every definition, and so must match each other if there is a definition.)
1906 
1907     // If either declaration only contains 'alignas(0)' specifiers, then it
1908     // specifies the natural alignment for the type.
1909     if (OldAlign == 0 || NewAlign == 0) {
1910       QualType Ty;
1911       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1912         Ty = VD->getType();
1913       else
1914         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1915 
1916       if (OldAlign == 0)
1917         OldAlign = S.Context.getTypeAlign(Ty);
1918       if (NewAlign == 0)
1919         NewAlign = S.Context.getTypeAlign(Ty);
1920     }
1921 
1922     if (OldAlign != NewAlign) {
1923       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1924         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1925         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1926       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1927     }
1928   }
1929 
1930   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1931     // C++11 [dcl.align]p6:
1932     //   if any declaration of an entity has an alignment-specifier,
1933     //   every defining declaration of that entity shall specify an
1934     //   equivalent alignment.
1935     // C11 6.7.5/7:
1936     //   If the definition of an object does not have an alignment
1937     //   specifier, any other declaration of that object shall also
1938     //   have no alignment specifier.
1939     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1940       << OldAlignasAttr;
1941     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1942       << OldAlignasAttr;
1943   }
1944 
1945   bool AnyAdded = false;
1946 
1947   // Ensure we have an attribute representing the strictest alignment.
1948   if (OldAlign > NewAlign) {
1949     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1950     Clone->setInherited(true);
1951     New->addAttr(Clone);
1952     AnyAdded = true;
1953   }
1954 
1955   // Ensure we have an alignas attribute if the old declaration had one.
1956   if (OldAlignasAttr && !NewAlignasAttr &&
1957       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1958     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1959     Clone->setInherited(true);
1960     New->addAttr(Clone);
1961     AnyAdded = true;
1962   }
1963 
1964   return AnyAdded;
1965 }
1966 
1967 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1968                                bool Override) {
1969   InheritableAttr *NewAttr = NULL;
1970   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1971   if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1972     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1973                                       AA->getIntroduced(), AA->getDeprecated(),
1974                                       AA->getObsoleted(), AA->getUnavailable(),
1975                                       AA->getMessage(), Override,
1976                                       AttrSpellingListIndex);
1977   else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1978     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1979                                     AttrSpellingListIndex);
1980   else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1981     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1982                                         AttrSpellingListIndex);
1983   else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1984     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1985                                    AttrSpellingListIndex);
1986   else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1987     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1988                                    AttrSpellingListIndex);
1989   else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1990     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1991                                 FA->getFormatIdx(), FA->getFirstArg(),
1992                                 AttrSpellingListIndex);
1993   else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1994     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1995                                  AttrSpellingListIndex);
1996   else if (isa<AlignedAttr>(Attr))
1997     // AlignedAttrs are handled separately, because we need to handle all
1998     // such attributes on a declaration at the same time.
1999     NewAttr = 0;
2000   else if (!DeclHasAttr(D, Attr))
2001     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2002 
2003   if (NewAttr) {
2004     NewAttr->setInherited(true);
2005     D->addAttr(NewAttr);
2006     return true;
2007   }
2008 
2009   return false;
2010 }
2011 
2012 static const Decl *getDefinition(const Decl *D) {
2013   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2014     return TD->getDefinition();
2015   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2016     const VarDecl *Def = VD->getDefinition();
2017     if (Def)
2018       return Def;
2019     return VD->getActingDefinition();
2020   }
2021   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2022     const FunctionDecl* Def;
2023     if (FD->isDefined(Def))
2024       return Def;
2025   }
2026   return NULL;
2027 }
2028 
2029 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2030   for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2031        I != E; ++I) {
2032     Attr *Attribute = *I;
2033     if (Attribute->getKind() == Kind)
2034       return true;
2035   }
2036   return false;
2037 }
2038 
2039 /// checkNewAttributesAfterDef - If we already have a definition, check that
2040 /// there are no new attributes in this declaration.
2041 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2042   if (!New->hasAttrs())
2043     return;
2044 
2045   const Decl *Def = getDefinition(Old);
2046   if (!Def || Def == New)
2047     return;
2048 
2049   AttrVec &NewAttributes = New->getAttrs();
2050   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2051     const Attr *NewAttribute = NewAttributes[I];
2052 
2053     if (isa<AliasAttr>(NewAttribute)) {
2054       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2055         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2056       else {
2057         VarDecl *VD = cast<VarDecl>(New);
2058         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2059                                 VarDecl::TentativeDefinition
2060                             ? diag::err_alias_after_tentative
2061                             : diag::err_redefinition;
2062         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2063         S.Diag(Def->getLocation(), diag::note_previous_definition);
2064         VD->setInvalidDecl();
2065       }
2066       ++I;
2067       continue;
2068     }
2069 
2070     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2071       // Tentative definitions are only interesting for the alias check above.
2072       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2073         ++I;
2074         continue;
2075       }
2076     }
2077 
2078     if (hasAttribute(Def, NewAttribute->getKind())) {
2079       ++I;
2080       continue; // regular attr merging will take care of validating this.
2081     }
2082 
2083     if (isa<C11NoReturnAttr>(NewAttribute)) {
2084       // C's _Noreturn is allowed to be added to a function after it is defined.
2085       ++I;
2086       continue;
2087     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2088       if (AA->isAlignas()) {
2089         // C++11 [dcl.align]p6:
2090         //   if any declaration of an entity has an alignment-specifier,
2091         //   every defining declaration of that entity shall specify an
2092         //   equivalent alignment.
2093         // C11 6.7.5/7:
2094         //   If the definition of an object does not have an alignment
2095         //   specifier, any other declaration of that object shall also
2096         //   have no alignment specifier.
2097         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2098           << AA;
2099         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2100           << AA;
2101         NewAttributes.erase(NewAttributes.begin() + I);
2102         --E;
2103         continue;
2104       }
2105     }
2106 
2107     S.Diag(NewAttribute->getLocation(),
2108            diag::warn_attribute_precede_definition);
2109     S.Diag(Def->getLocation(), diag::note_previous_definition);
2110     NewAttributes.erase(NewAttributes.begin() + I);
2111     --E;
2112   }
2113 }
2114 
2115 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2116 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2117                                AvailabilityMergeKind AMK) {
2118   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2119     UsedAttr *NewAttr = OldAttr->clone(Context);
2120     NewAttr->setInherited(true);
2121     New->addAttr(NewAttr);
2122   }
2123 
2124   if (!Old->hasAttrs() && !New->hasAttrs())
2125     return;
2126 
2127   // attributes declared post-definition are currently ignored
2128   checkNewAttributesAfterDef(*this, New, Old);
2129 
2130   if (!Old->hasAttrs())
2131     return;
2132 
2133   bool foundAny = New->hasAttrs();
2134 
2135   // Ensure that any moving of objects within the allocated map is done before
2136   // we process them.
2137   if (!foundAny) New->setAttrs(AttrVec());
2138 
2139   for (specific_attr_iterator<InheritableAttr>
2140          i = Old->specific_attr_begin<InheritableAttr>(),
2141          e = Old->specific_attr_end<InheritableAttr>();
2142        i != e; ++i) {
2143     bool Override = false;
2144     // Ignore deprecated/unavailable/availability attributes if requested.
2145     if (isa<DeprecatedAttr>(*i) ||
2146         isa<UnavailableAttr>(*i) ||
2147         isa<AvailabilityAttr>(*i)) {
2148       switch (AMK) {
2149       case AMK_None:
2150         continue;
2151 
2152       case AMK_Redeclaration:
2153         break;
2154 
2155       case AMK_Override:
2156         Override = true;
2157         break;
2158       }
2159     }
2160 
2161     // Already handled.
2162     if (isa<UsedAttr>(*i))
2163       continue;
2164 
2165     if (mergeDeclAttribute(*this, New, *i, Override))
2166       foundAny = true;
2167   }
2168 
2169   if (mergeAlignedAttrs(*this, New, Old))
2170     foundAny = true;
2171 
2172   if (!foundAny) New->dropAttrs();
2173 }
2174 
2175 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2176 /// to the new one.
2177 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2178                                      const ParmVarDecl *oldDecl,
2179                                      Sema &S) {
2180   // C++11 [dcl.attr.depend]p2:
2181   //   The first declaration of a function shall specify the
2182   //   carries_dependency attribute for its declarator-id if any declaration
2183   //   of the function specifies the carries_dependency attribute.
2184   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2185   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2186     S.Diag(CDA->getLocation(),
2187            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2188     // Find the first declaration of the parameter.
2189     // FIXME: Should we build redeclaration chains for function parameters?
2190     const FunctionDecl *FirstFD =
2191       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2192     const ParmVarDecl *FirstVD =
2193       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2194     S.Diag(FirstVD->getLocation(),
2195            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2196   }
2197 
2198   if (!oldDecl->hasAttrs())
2199     return;
2200 
2201   bool foundAny = newDecl->hasAttrs();
2202 
2203   // Ensure that any moving of objects within the allocated map is
2204   // done before we process them.
2205   if (!foundAny) newDecl->setAttrs(AttrVec());
2206 
2207   for (specific_attr_iterator<InheritableParamAttr>
2208        i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2209        e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2210     if (!DeclHasAttr(newDecl, *i)) {
2211       InheritableAttr *newAttr =
2212         cast<InheritableParamAttr>((*i)->clone(S.Context));
2213       newAttr->setInherited(true);
2214       newDecl->addAttr(newAttr);
2215       foundAny = true;
2216     }
2217   }
2218 
2219   if (!foundAny) newDecl->dropAttrs();
2220 }
2221 
2222 namespace {
2223 
2224 /// Used in MergeFunctionDecl to keep track of function parameters in
2225 /// C.
2226 struct GNUCompatibleParamWarning {
2227   ParmVarDecl *OldParm;
2228   ParmVarDecl *NewParm;
2229   QualType PromotedType;
2230 };
2231 
2232 }
2233 
2234 /// getSpecialMember - get the special member enum for a method.
2235 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2236   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2237     if (Ctor->isDefaultConstructor())
2238       return Sema::CXXDefaultConstructor;
2239 
2240     if (Ctor->isCopyConstructor())
2241       return Sema::CXXCopyConstructor;
2242 
2243     if (Ctor->isMoveConstructor())
2244       return Sema::CXXMoveConstructor;
2245   } else if (isa<CXXDestructorDecl>(MD)) {
2246     return Sema::CXXDestructor;
2247   } else if (MD->isCopyAssignmentOperator()) {
2248     return Sema::CXXCopyAssignment;
2249   } else if (MD->isMoveAssignmentOperator()) {
2250     return Sema::CXXMoveAssignment;
2251   }
2252 
2253   return Sema::CXXInvalid;
2254 }
2255 
2256 /// canRedefineFunction - checks if a function can be redefined. Currently,
2257 /// only extern inline functions can be redefined, and even then only in
2258 /// GNU89 mode.
2259 static bool canRedefineFunction(const FunctionDecl *FD,
2260                                 const LangOptions& LangOpts) {
2261   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2262           !LangOpts.CPlusPlus &&
2263           FD->isInlineSpecified() &&
2264           FD->getStorageClass() == SC_Extern);
2265 }
2266 
2267 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2268   const AttributedType *AT = T->getAs<AttributedType>();
2269   while (AT && !AT->isCallingConv())
2270     AT = AT->getModifiedType()->getAs<AttributedType>();
2271   return AT;
2272 }
2273 
2274 template <typename T>
2275 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2276   const DeclContext *DC = Old->getDeclContext();
2277   if (DC->isRecord())
2278     return false;
2279 
2280   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2281   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2282     return true;
2283   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2284     return true;
2285   return false;
2286 }
2287 
2288 /// MergeFunctionDecl - We just parsed a function 'New' from
2289 /// declarator D which has the same name and scope as a previous
2290 /// declaration 'Old'.  Figure out how to resolve this situation,
2291 /// merging decls or emitting diagnostics as appropriate.
2292 ///
2293 /// In C++, New and Old must be declarations that are not
2294 /// overloaded. Use IsOverload to determine whether New and Old are
2295 /// overloaded, and to select the Old declaration that New should be
2296 /// merged with.
2297 ///
2298 /// Returns true if there was an error, false otherwise.
2299 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2300                              bool MergeTypeWithOld) {
2301   // Verify the old decl was also a function.
2302   FunctionDecl *Old = 0;
2303   if (FunctionTemplateDecl *OldFunctionTemplate
2304         = dyn_cast<FunctionTemplateDecl>(OldD))
2305     Old = OldFunctionTemplate->getTemplatedDecl();
2306   else
2307     Old = dyn_cast<FunctionDecl>(OldD);
2308   if (!Old) {
2309     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2310       if (New->getFriendObjectKind()) {
2311         Diag(New->getLocation(), diag::err_using_decl_friend);
2312         Diag(Shadow->getTargetDecl()->getLocation(),
2313              diag::note_using_decl_target);
2314         Diag(Shadow->getUsingDecl()->getLocation(),
2315              diag::note_using_decl) << 0;
2316         return true;
2317       }
2318 
2319       Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2320       Diag(Shadow->getTargetDecl()->getLocation(),
2321            diag::note_using_decl_target);
2322       Diag(Shadow->getUsingDecl()->getLocation(),
2323            diag::note_using_decl) << 0;
2324       return true;
2325     }
2326 
2327     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2328       << New->getDeclName();
2329     Diag(OldD->getLocation(), diag::note_previous_definition);
2330     return true;
2331   }
2332 
2333   // If the old declaration is invalid, just give up here.
2334   if (Old->isInvalidDecl())
2335     return true;
2336 
2337   // Determine whether the previous declaration was a definition,
2338   // implicit declaration, or a declaration.
2339   diag::kind PrevDiag;
2340   if (Old->isThisDeclarationADefinition())
2341     PrevDiag = diag::note_previous_definition;
2342   else if (Old->isImplicit())
2343     PrevDiag = diag::note_previous_implicit_declaration;
2344   else
2345     PrevDiag = diag::note_previous_declaration;
2346 
2347   // Don't complain about this if we're in GNU89 mode and the old function
2348   // is an extern inline function.
2349   // Don't complain about specializations. They are not supposed to have
2350   // storage classes.
2351   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2352       New->getStorageClass() == SC_Static &&
2353       Old->hasExternalFormalLinkage() &&
2354       !New->getTemplateSpecializationInfo() &&
2355       !canRedefineFunction(Old, getLangOpts())) {
2356     if (getLangOpts().MicrosoftExt) {
2357       Diag(New->getLocation(), diag::warn_static_non_static) << New;
2358       Diag(Old->getLocation(), PrevDiag);
2359     } else {
2360       Diag(New->getLocation(), diag::err_static_non_static) << New;
2361       Diag(Old->getLocation(), PrevDiag);
2362       return true;
2363     }
2364   }
2365 
2366 
2367   // If a function is first declared with a calling convention, but is later
2368   // declared or defined without one, all following decls assume the calling
2369   // convention of the first.
2370   //
2371   // It's OK if a function is first declared without a calling convention,
2372   // but is later declared or defined with the default calling convention.
2373   //
2374   // To test if either decl has an explicit calling convention, we look for
2375   // AttributedType sugar nodes on the type as written.  If they are missing or
2376   // were canonicalized away, we assume the calling convention was implicit.
2377   //
2378   // Note also that we DO NOT return at this point, because we still have
2379   // other tests to run.
2380   QualType OldQType = Context.getCanonicalType(Old->getType());
2381   QualType NewQType = Context.getCanonicalType(New->getType());
2382   const FunctionType *OldType = cast<FunctionType>(OldQType);
2383   const FunctionType *NewType = cast<FunctionType>(NewQType);
2384   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2385   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2386   bool RequiresAdjustment = false;
2387 
2388   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2389     FunctionDecl *First = Old->getFirstDecl();
2390     const FunctionType *FT =
2391         First->getType().getCanonicalType()->castAs<FunctionType>();
2392     FunctionType::ExtInfo FI = FT->getExtInfo();
2393     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2394     if (!NewCCExplicit) {
2395       // Inherit the CC from the previous declaration if it was specified
2396       // there but not here.
2397       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2398       RequiresAdjustment = true;
2399     } else {
2400       // Calling conventions aren't compatible, so complain.
2401       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2402       Diag(New->getLocation(), diag::err_cconv_change)
2403         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2404         << !FirstCCExplicit
2405         << (!FirstCCExplicit ? "" :
2406             FunctionType::getNameForCallConv(FI.getCC()));
2407 
2408       // Put the note on the first decl, since it is the one that matters.
2409       Diag(First->getLocation(), diag::note_previous_declaration);
2410       return true;
2411     }
2412   }
2413 
2414   // FIXME: diagnose the other way around?
2415   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2416     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2417     RequiresAdjustment = true;
2418   }
2419 
2420   // Merge regparm attribute.
2421   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2422       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2423     if (NewTypeInfo.getHasRegParm()) {
2424       Diag(New->getLocation(), diag::err_regparm_mismatch)
2425         << NewType->getRegParmType()
2426         << OldType->getRegParmType();
2427       Diag(Old->getLocation(), diag::note_previous_declaration);
2428       return true;
2429     }
2430 
2431     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2432     RequiresAdjustment = true;
2433   }
2434 
2435   // Merge ns_returns_retained attribute.
2436   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2437     if (NewTypeInfo.getProducesResult()) {
2438       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2439       Diag(Old->getLocation(), diag::note_previous_declaration);
2440       return true;
2441     }
2442 
2443     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2444     RequiresAdjustment = true;
2445   }
2446 
2447   if (RequiresAdjustment) {
2448     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2449     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2450     New->setType(QualType(AdjustedType, 0));
2451     NewQType = Context.getCanonicalType(New->getType());
2452     NewType = cast<FunctionType>(NewQType);
2453   }
2454 
2455   // If this redeclaration makes the function inline, we may need to add it to
2456   // UndefinedButUsed.
2457   if (!Old->isInlined() && New->isInlined() &&
2458       !New->hasAttr<GNUInlineAttr>() &&
2459       (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2460       Old->isUsed(false) &&
2461       !Old->isDefined() && !New->isThisDeclarationADefinition())
2462     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2463                                            SourceLocation()));
2464 
2465   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2466   // about it.
2467   if (New->hasAttr<GNUInlineAttr>() &&
2468       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2469     UndefinedButUsed.erase(Old->getCanonicalDecl());
2470   }
2471 
2472   if (getLangOpts().CPlusPlus) {
2473     // (C++98 13.1p2):
2474     //   Certain function declarations cannot be overloaded:
2475     //     -- Function declarations that differ only in the return type
2476     //        cannot be overloaded.
2477 
2478     // Go back to the type source info to compare the declared return types,
2479     // per C++1y [dcl.type.auto]p13:
2480     //   Redeclarations or specializations of a function or function template
2481     //   with a declared return type that uses a placeholder type shall also
2482     //   use that placeholder, not a deduced type.
2483     QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2484       ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2485       : OldType)->getResultType();
2486     QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2487       ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2488       : NewType)->getResultType();
2489     QualType ResQT;
2490     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2491         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2492           New->isLocalExternDecl())) {
2493       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2494           OldDeclaredReturnType->isObjCObjectPointerType())
2495         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2496       if (ResQT.isNull()) {
2497         if (New->isCXXClassMember() && New->isOutOfLine())
2498           Diag(New->getLocation(),
2499                diag::err_member_def_does_not_match_ret_type) << New;
2500         else
2501           Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2502         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2503         return true;
2504       }
2505       else
2506         NewQType = ResQT;
2507     }
2508 
2509     QualType OldReturnType = OldType->getResultType();
2510     QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2511     if (OldReturnType != NewReturnType) {
2512       // If this function has a deduced return type and has already been
2513       // defined, copy the deduced value from the old declaration.
2514       AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2515       if (OldAT && OldAT->isDeduced()) {
2516         New->setType(
2517             SubstAutoType(New->getType(),
2518                           OldAT->isDependentType() ? Context.DependentTy
2519                                                    : OldAT->getDeducedType()));
2520         NewQType = Context.getCanonicalType(
2521             SubstAutoType(NewQType,
2522                           OldAT->isDependentType() ? Context.DependentTy
2523                                                    : OldAT->getDeducedType()));
2524       }
2525     }
2526 
2527     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2528     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2529     if (OldMethod && NewMethod) {
2530       // Preserve triviality.
2531       NewMethod->setTrivial(OldMethod->isTrivial());
2532 
2533       // MSVC allows explicit template specialization at class scope:
2534       // 2 CXXMethodDecls referring to the same function will be injected.
2535       // We don't want a redeclaration error.
2536       bool IsClassScopeExplicitSpecialization =
2537                               OldMethod->isFunctionTemplateSpecialization() &&
2538                               NewMethod->isFunctionTemplateSpecialization();
2539       bool isFriend = NewMethod->getFriendObjectKind();
2540 
2541       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2542           !IsClassScopeExplicitSpecialization) {
2543         //    -- Member function declarations with the same name and the
2544         //       same parameter types cannot be overloaded if any of them
2545         //       is a static member function declaration.
2546         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2547           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2548           Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2549           return true;
2550         }
2551 
2552         // C++ [class.mem]p1:
2553         //   [...] A member shall not be declared twice in the
2554         //   member-specification, except that a nested class or member
2555         //   class template can be declared and then later defined.
2556         if (ActiveTemplateInstantiations.empty()) {
2557           unsigned NewDiag;
2558           if (isa<CXXConstructorDecl>(OldMethod))
2559             NewDiag = diag::err_constructor_redeclared;
2560           else if (isa<CXXDestructorDecl>(NewMethod))
2561             NewDiag = diag::err_destructor_redeclared;
2562           else if (isa<CXXConversionDecl>(NewMethod))
2563             NewDiag = diag::err_conv_function_redeclared;
2564           else
2565             NewDiag = diag::err_member_redeclared;
2566 
2567           Diag(New->getLocation(), NewDiag);
2568         } else {
2569           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2570             << New << New->getType();
2571         }
2572         Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2573 
2574       // Complain if this is an explicit declaration of a special
2575       // member that was initially declared implicitly.
2576       //
2577       // As an exception, it's okay to befriend such methods in order
2578       // to permit the implicit constructor/destructor/operator calls.
2579       } else if (OldMethod->isImplicit()) {
2580         if (isFriend) {
2581           NewMethod->setImplicit();
2582         } else {
2583           Diag(NewMethod->getLocation(),
2584                diag::err_definition_of_implicitly_declared_member)
2585             << New << getSpecialMember(OldMethod);
2586           return true;
2587         }
2588       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2589         Diag(NewMethod->getLocation(),
2590              diag::err_definition_of_explicitly_defaulted_member)
2591           << getSpecialMember(OldMethod);
2592         return true;
2593       }
2594     }
2595 
2596     // C++11 [dcl.attr.noreturn]p1:
2597     //   The first declaration of a function shall specify the noreturn
2598     //   attribute if any declaration of that function specifies the noreturn
2599     //   attribute.
2600     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2601     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2602       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2603       Diag(Old->getFirstDecl()->getLocation(),
2604            diag::note_noreturn_missing_first_decl);
2605     }
2606 
2607     // C++11 [dcl.attr.depend]p2:
2608     //   The first declaration of a function shall specify the
2609     //   carries_dependency attribute for its declarator-id if any declaration
2610     //   of the function specifies the carries_dependency attribute.
2611     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2612     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2613       Diag(CDA->getLocation(),
2614            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2615       Diag(Old->getFirstDecl()->getLocation(),
2616            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2617     }
2618 
2619     // (C++98 8.3.5p3):
2620     //   All declarations for a function shall agree exactly in both the
2621     //   return type and the parameter-type-list.
2622     // We also want to respect all the extended bits except noreturn.
2623 
2624     // noreturn should now match unless the old type info didn't have it.
2625     QualType OldQTypeForComparison = OldQType;
2626     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2627       assert(OldQType == QualType(OldType, 0));
2628       const FunctionType *OldTypeForComparison
2629         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2630       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2631       assert(OldQTypeForComparison.isCanonical());
2632     }
2633 
2634     if (haveIncompatibleLanguageLinkages(Old, New)) {
2635       // As a special case, retain the language linkage from previous
2636       // declarations of a friend function as an extension.
2637       //
2638       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2639       // and is useful because there's otherwise no way to specify language
2640       // linkage within class scope.
2641       //
2642       // Check cautiously as the friend object kind isn't yet complete.
2643       if (New->getFriendObjectKind() != Decl::FOK_None) {
2644         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2645         Diag(Old->getLocation(), PrevDiag);
2646       } else {
2647         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2648         Diag(Old->getLocation(), PrevDiag);
2649         return true;
2650       }
2651     }
2652 
2653     if (OldQTypeForComparison == NewQType)
2654       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2655 
2656     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2657         New->isLocalExternDecl()) {
2658       // It's OK if we couldn't merge types for a local function declaraton
2659       // if either the old or new type is dependent. We'll merge the types
2660       // when we instantiate the function.
2661       return false;
2662     }
2663 
2664     // Fall through for conflicting redeclarations and redefinitions.
2665   }
2666 
2667   // C: Function types need to be compatible, not identical. This handles
2668   // duplicate function decls like "void f(int); void f(enum X);" properly.
2669   if (!getLangOpts().CPlusPlus &&
2670       Context.typesAreCompatible(OldQType, NewQType)) {
2671     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2672     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2673     const FunctionProtoType *OldProto = 0;
2674     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2675         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2676       // The old declaration provided a function prototype, but the
2677       // new declaration does not. Merge in the prototype.
2678       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2679       SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2680                                                  OldProto->arg_type_end());
2681       NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2682                                          ParamTypes,
2683                                          OldProto->getExtProtoInfo());
2684       New->setType(NewQType);
2685       New->setHasInheritedPrototype();
2686 
2687       // Synthesize a parameter for each argument type.
2688       SmallVector<ParmVarDecl*, 16> Params;
2689       for (FunctionProtoType::arg_type_iterator
2690              ParamType = OldProto->arg_type_begin(),
2691              ParamEnd = OldProto->arg_type_end();
2692            ParamType != ParamEnd; ++ParamType) {
2693         ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2694                                                  SourceLocation(),
2695                                                  SourceLocation(), 0,
2696                                                  *ParamType, /*TInfo=*/0,
2697                                                  SC_None,
2698                                                  0);
2699         Param->setScopeInfo(0, Params.size());
2700         Param->setImplicit();
2701         Params.push_back(Param);
2702       }
2703 
2704       New->setParams(Params);
2705     }
2706 
2707     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2708   }
2709 
2710   // GNU C permits a K&R definition to follow a prototype declaration
2711   // if the declared types of the parameters in the K&R definition
2712   // match the types in the prototype declaration, even when the
2713   // promoted types of the parameters from the K&R definition differ
2714   // from the types in the prototype. GCC then keeps the types from
2715   // the prototype.
2716   //
2717   // If a variadic prototype is followed by a non-variadic K&R definition,
2718   // the K&R definition becomes variadic.  This is sort of an edge case, but
2719   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2720   // C99 6.9.1p8.
2721   if (!getLangOpts().CPlusPlus &&
2722       Old->hasPrototype() && !New->hasPrototype() &&
2723       New->getType()->getAs<FunctionProtoType>() &&
2724       Old->getNumParams() == New->getNumParams()) {
2725     SmallVector<QualType, 16> ArgTypes;
2726     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2727     const FunctionProtoType *OldProto
2728       = Old->getType()->getAs<FunctionProtoType>();
2729     const FunctionProtoType *NewProto
2730       = New->getType()->getAs<FunctionProtoType>();
2731 
2732     // Determine whether this is the GNU C extension.
2733     QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2734                                                NewProto->getResultType());
2735     bool LooseCompatible = !MergedReturn.isNull();
2736     for (unsigned Idx = 0, End = Old->getNumParams();
2737          LooseCompatible && Idx != End; ++Idx) {
2738       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2739       ParmVarDecl *NewParm = New->getParamDecl(Idx);
2740       if (Context.typesAreCompatible(OldParm->getType(),
2741                                      NewProto->getArgType(Idx))) {
2742         ArgTypes.push_back(NewParm->getType());
2743       } else if (Context.typesAreCompatible(OldParm->getType(),
2744                                             NewParm->getType(),
2745                                             /*CompareUnqualified=*/true)) {
2746         GNUCompatibleParamWarning Warn
2747           = { OldParm, NewParm, NewProto->getArgType(Idx) };
2748         Warnings.push_back(Warn);
2749         ArgTypes.push_back(NewParm->getType());
2750       } else
2751         LooseCompatible = false;
2752     }
2753 
2754     if (LooseCompatible) {
2755       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2756         Diag(Warnings[Warn].NewParm->getLocation(),
2757              diag::ext_param_promoted_not_compatible_with_prototype)
2758           << Warnings[Warn].PromotedType
2759           << Warnings[Warn].OldParm->getType();
2760         if (Warnings[Warn].OldParm->getLocation().isValid())
2761           Diag(Warnings[Warn].OldParm->getLocation(),
2762                diag::note_previous_declaration);
2763       }
2764 
2765       if (MergeTypeWithOld)
2766         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2767                                              OldProto->getExtProtoInfo()));
2768       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2769     }
2770 
2771     // Fall through to diagnose conflicting types.
2772   }
2773 
2774   // A function that has already been declared has been redeclared or
2775   // defined with a different type; show an appropriate diagnostic.
2776 
2777   // If the previous declaration was an implicitly-generated builtin
2778   // declaration, then at the very least we should use a specialized note.
2779   unsigned BuiltinID;
2780   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2781     // If it's actually a library-defined builtin function like 'malloc'
2782     // or 'printf', just warn about the incompatible redeclaration.
2783     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2784       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2785       Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2786         << Old << Old->getType();
2787 
2788       // If this is a global redeclaration, just forget hereafter
2789       // about the "builtin-ness" of the function.
2790       //
2791       // Doing this for local extern declarations is problematic.  If
2792       // the builtin declaration remains visible, a second invalid
2793       // local declaration will produce a hard error; if it doesn't
2794       // remain visible, a single bogus local redeclaration (which is
2795       // actually only a warning) could break all the downstream code.
2796       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2797         New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2798 
2799       return false;
2800     }
2801 
2802     PrevDiag = diag::note_previous_builtin_declaration;
2803   }
2804 
2805   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2806   Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2807   return true;
2808 }
2809 
2810 /// \brief Completes the merge of two function declarations that are
2811 /// known to be compatible.
2812 ///
2813 /// This routine handles the merging of attributes and other
2814 /// properties of function declarations from the old declaration to
2815 /// the new declaration, once we know that New is in fact a
2816 /// redeclaration of Old.
2817 ///
2818 /// \returns false
2819 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2820                                         Scope *S, bool MergeTypeWithOld) {
2821   // Merge the attributes
2822   mergeDeclAttributes(New, Old);
2823 
2824   // Merge "pure" flag.
2825   if (Old->isPure())
2826     New->setPure();
2827 
2828   // Merge "used" flag.
2829   if (Old->getMostRecentDecl()->isUsed(false))
2830     New->setIsUsed();
2831 
2832   // Merge attributes from the parameters.  These can mismatch with K&R
2833   // declarations.
2834   if (New->getNumParams() == Old->getNumParams())
2835     for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2836       mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2837                                *this);
2838 
2839   if (getLangOpts().CPlusPlus)
2840     return MergeCXXFunctionDecl(New, Old, S);
2841 
2842   // Merge the function types so the we get the composite types for the return
2843   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2844   // was visible.
2845   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2846   if (!Merged.isNull() && MergeTypeWithOld)
2847     New->setType(Merged);
2848 
2849   return false;
2850 }
2851 
2852 
2853 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2854                                 ObjCMethodDecl *oldMethod) {
2855 
2856   // Merge the attributes, including deprecated/unavailable
2857   AvailabilityMergeKind MergeKind =
2858     isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2859                                                    : AMK_Override;
2860   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2861 
2862   // Merge attributes from the parameters.
2863   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2864                                        oe = oldMethod->param_end();
2865   for (ObjCMethodDecl::param_iterator
2866          ni = newMethod->param_begin(), ne = newMethod->param_end();
2867        ni != ne && oi != oe; ++ni, ++oi)
2868     mergeParamDeclAttributes(*ni, *oi, *this);
2869 
2870   CheckObjCMethodOverride(newMethod, oldMethod);
2871 }
2872 
2873 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2874 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2875 /// emitting diagnostics as appropriate.
2876 ///
2877 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2878 /// to here in AddInitializerToDecl. We can't check them before the initializer
2879 /// is attached.
2880 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2881                              bool MergeTypeWithOld) {
2882   if (New->isInvalidDecl() || Old->isInvalidDecl())
2883     return;
2884 
2885   QualType MergedT;
2886   if (getLangOpts().CPlusPlus) {
2887     if (New->getType()->isUndeducedType()) {
2888       // We don't know what the new type is until the initializer is attached.
2889       return;
2890     } else if (Context.hasSameType(New->getType(), Old->getType())) {
2891       // These could still be something that needs exception specs checked.
2892       return MergeVarDeclExceptionSpecs(New, Old);
2893     }
2894     // C++ [basic.link]p10:
2895     //   [...] the types specified by all declarations referring to a given
2896     //   object or function shall be identical, except that declarations for an
2897     //   array object can specify array types that differ by the presence or
2898     //   absence of a major array bound (8.3.4).
2899     else if (Old->getType()->isIncompleteArrayType() &&
2900              New->getType()->isArrayType()) {
2901       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2902       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2903       if (Context.hasSameType(OldArray->getElementType(),
2904                               NewArray->getElementType()))
2905         MergedT = New->getType();
2906     } else if (Old->getType()->isArrayType() &&
2907                New->getType()->isIncompleteArrayType()) {
2908       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2909       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2910       if (Context.hasSameType(OldArray->getElementType(),
2911                               NewArray->getElementType()))
2912         MergedT = Old->getType();
2913     } else if (New->getType()->isObjCObjectPointerType() &&
2914                Old->getType()->isObjCObjectPointerType()) {
2915       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2916                                               Old->getType());
2917     }
2918   } else {
2919     // C 6.2.7p2:
2920     //   All declarations that refer to the same object or function shall have
2921     //   compatible type.
2922     MergedT = Context.mergeTypes(New->getType(), Old->getType());
2923   }
2924   if (MergedT.isNull()) {
2925     // It's OK if we couldn't merge types if either type is dependent, for a
2926     // block-scope variable. In other cases (static data members of class
2927     // templates, variable templates, ...), we require the types to be
2928     // equivalent.
2929     // FIXME: The C++ standard doesn't say anything about this.
2930     if ((New->getType()->isDependentType() ||
2931          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2932       // If the old type was dependent, we can't merge with it, so the new type
2933       // becomes dependent for now. We'll reproduce the original type when we
2934       // instantiate the TypeSourceInfo for the variable.
2935       if (!New->getType()->isDependentType() && MergeTypeWithOld)
2936         New->setType(Context.DependentTy);
2937       return;
2938     }
2939 
2940     // FIXME: Even if this merging succeeds, some other non-visible declaration
2941     // of this variable might have an incompatible type. For instance:
2942     //
2943     //   extern int arr[];
2944     //   void f() { extern int arr[2]; }
2945     //   void g() { extern int arr[3]; }
2946     //
2947     // Neither C nor C++ requires a diagnostic for this, but we should still try
2948     // to diagnose it.
2949     Diag(New->getLocation(), diag::err_redefinition_different_type)
2950       << New->getDeclName() << New->getType() << Old->getType();
2951     Diag(Old->getLocation(), diag::note_previous_definition);
2952     return New->setInvalidDecl();
2953   }
2954 
2955   // Don't actually update the type on the new declaration if the old
2956   // declaration was an extern declaration in a different scope.
2957   if (MergeTypeWithOld)
2958     New->setType(MergedT);
2959 }
2960 
2961 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2962                                   LookupResult &Previous) {
2963   // C11 6.2.7p4:
2964   //   For an identifier with internal or external linkage declared
2965   //   in a scope in which a prior declaration of that identifier is
2966   //   visible, if the prior declaration specifies internal or
2967   //   external linkage, the type of the identifier at the later
2968   //   declaration becomes the composite type.
2969   //
2970   // If the variable isn't visible, we do not merge with its type.
2971   if (Previous.isShadowed())
2972     return false;
2973 
2974   if (S.getLangOpts().CPlusPlus) {
2975     // C++11 [dcl.array]p3:
2976     //   If there is a preceding declaration of the entity in the same
2977     //   scope in which the bound was specified, an omitted array bound
2978     //   is taken to be the same as in that earlier declaration.
2979     return NewVD->isPreviousDeclInSameBlockScope() ||
2980            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2981             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2982   } else {
2983     // If the old declaration was function-local, don't merge with its
2984     // type unless we're in the same function.
2985     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2986            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2987   }
2988 }
2989 
2990 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
2991 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2992 /// situation, merging decls or emitting diagnostics as appropriate.
2993 ///
2994 /// Tentative definition rules (C99 6.9.2p2) are checked by
2995 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2996 /// definitions here, since the initializer hasn't been attached.
2997 ///
2998 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2999   // If the new decl is already invalid, don't do any other checking.
3000   if (New->isInvalidDecl())
3001     return;
3002 
3003   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3004 
3005   // Verify the old decl was also a variable or variable template.
3006   VarDecl *Old = 0;
3007   VarTemplateDecl *OldTemplate = 0;
3008   if (Previous.isSingleResult()) {
3009     if (NewTemplate) {
3010       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3011       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : 0;
3012     } else
3013       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3014   }
3015   if (!Old) {
3016     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3017       << New->getDeclName();
3018     Diag(Previous.getRepresentativeDecl()->getLocation(),
3019          diag::note_previous_definition);
3020     return New->setInvalidDecl();
3021   }
3022 
3023   if (!shouldLinkPossiblyHiddenDecl(Old, New))
3024     return;
3025 
3026   // Ensure the template parameters are compatible.
3027   if (NewTemplate &&
3028       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3029                                       OldTemplate->getTemplateParameters(),
3030                                       /*Complain=*/true, TPL_TemplateMatch))
3031     return;
3032 
3033   // C++ [class.mem]p1:
3034   //   A member shall not be declared twice in the member-specification [...]
3035   //
3036   // Here, we need only consider static data members.
3037   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3038     Diag(New->getLocation(), diag::err_duplicate_member)
3039       << New->getIdentifier();
3040     Diag(Old->getLocation(), diag::note_previous_declaration);
3041     New->setInvalidDecl();
3042   }
3043 
3044   mergeDeclAttributes(New, Old);
3045   // Warn if an already-declared variable is made a weak_import in a subsequent
3046   // declaration
3047   if (New->hasAttr<WeakImportAttr>() &&
3048       Old->getStorageClass() == SC_None &&
3049       !Old->hasAttr<WeakImportAttr>()) {
3050     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3051     Diag(Old->getLocation(), diag::note_previous_definition);
3052     // Remove weak_import attribute on new declaration.
3053     New->dropAttr<WeakImportAttr>();
3054   }
3055 
3056   // Merge the types.
3057   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3058 
3059   if (New->isInvalidDecl())
3060     return;
3061 
3062   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3063   if (New->getStorageClass() == SC_Static &&
3064       !New->isStaticDataMember() &&
3065       Old->hasExternalFormalLinkage()) {
3066     Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
3067     Diag(Old->getLocation(), diag::note_previous_definition);
3068     return New->setInvalidDecl();
3069   }
3070   // C99 6.2.2p4:
3071   //   For an identifier declared with the storage-class specifier
3072   //   extern in a scope in which a prior declaration of that
3073   //   identifier is visible,23) if the prior declaration specifies
3074   //   internal or external linkage, the linkage of the identifier at
3075   //   the later declaration is the same as the linkage specified at
3076   //   the prior declaration. If no prior declaration is visible, or
3077   //   if the prior declaration specifies no linkage, then the
3078   //   identifier has external linkage.
3079   if (New->hasExternalStorage() && Old->hasLinkage())
3080     /* Okay */;
3081   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3082            !New->isStaticDataMember() &&
3083            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3084     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3085     Diag(Old->getLocation(), diag::note_previous_definition);
3086     return New->setInvalidDecl();
3087   }
3088 
3089   // Check if extern is followed by non-extern and vice-versa.
3090   if (New->hasExternalStorage() &&
3091       !Old->hasLinkage() && Old->isLocalVarDecl()) {
3092     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3093     Diag(Old->getLocation(), diag::note_previous_definition);
3094     return New->setInvalidDecl();
3095   }
3096   if (Old->hasLinkage() && New->isLocalVarDecl() &&
3097       !New->hasExternalStorage()) {
3098     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3099     Diag(Old->getLocation(), diag::note_previous_definition);
3100     return New->setInvalidDecl();
3101   }
3102 
3103   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3104 
3105   // FIXME: The test for external storage here seems wrong? We still
3106   // need to check for mismatches.
3107   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3108       // Don't complain about out-of-line definitions of static members.
3109       !(Old->getLexicalDeclContext()->isRecord() &&
3110         !New->getLexicalDeclContext()->isRecord())) {
3111     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3112     Diag(Old->getLocation(), diag::note_previous_definition);
3113     return New->setInvalidDecl();
3114   }
3115 
3116   if (New->getTLSKind() != Old->getTLSKind()) {
3117     if (!Old->getTLSKind()) {
3118       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3119       Diag(Old->getLocation(), diag::note_previous_declaration);
3120     } else if (!New->getTLSKind()) {
3121       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3122       Diag(Old->getLocation(), diag::note_previous_declaration);
3123     } else {
3124       // Do not allow redeclaration to change the variable between requiring
3125       // static and dynamic initialization.
3126       // FIXME: GCC allows this, but uses the TLS keyword on the first
3127       // declaration to determine the kind. Do we need to be compatible here?
3128       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3129         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3130       Diag(Old->getLocation(), diag::note_previous_declaration);
3131     }
3132   }
3133 
3134   // C++ doesn't have tentative definitions, so go right ahead and check here.
3135   const VarDecl *Def;
3136   if (getLangOpts().CPlusPlus &&
3137       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3138       (Def = Old->getDefinition())) {
3139     Diag(New->getLocation(), diag::err_redefinition) << New;
3140     Diag(Def->getLocation(), diag::note_previous_definition);
3141     New->setInvalidDecl();
3142     return;
3143   }
3144 
3145   if (haveIncompatibleLanguageLinkages(Old, New)) {
3146     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3147     Diag(Old->getLocation(), diag::note_previous_definition);
3148     New->setInvalidDecl();
3149     return;
3150   }
3151 
3152   // Merge "used" flag.
3153   if (Old->getMostRecentDecl()->isUsed(false))
3154     New->setIsUsed();
3155 
3156   // Keep a chain of previous declarations.
3157   New->setPreviousDecl(Old);
3158   if (NewTemplate)
3159     NewTemplate->setPreviousDecl(OldTemplate);
3160 
3161   // Inherit access appropriately.
3162   New->setAccess(Old->getAccess());
3163   if (NewTemplate)
3164     NewTemplate->setAccess(New->getAccess());
3165 }
3166 
3167 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3168 /// no declarator (e.g. "struct foo;") is parsed.
3169 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3170                                        DeclSpec &DS) {
3171   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3172 }
3173 
3174 static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
3175   if (!S.Context.getLangOpts().CPlusPlus)
3176     return;
3177 
3178   if (isa<CXXRecordDecl>(Tag->getParent())) {
3179     // If this tag is the direct child of a class, number it if
3180     // it is anonymous.
3181     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3182       return;
3183     MangleNumberingContext &MCtx =
3184         S.Context.getManglingNumberContext(Tag->getParent());
3185     S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3186     return;
3187   }
3188 
3189   // If this tag isn't a direct child of a class, number it if it is local.
3190   Decl *ManglingContextDecl;
3191   if (MangleNumberingContext *MCtx =
3192           S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3193                                           ManglingContextDecl)) {
3194     S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3195   }
3196 }
3197 
3198 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3199 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3200 /// parameters to cope with template friend declarations.
3201 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3202                                        DeclSpec &DS,
3203                                        MultiTemplateParamsArg TemplateParams,
3204                                        bool IsExplicitInstantiation) {
3205   Decl *TagD = 0;
3206   TagDecl *Tag = 0;
3207   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3208       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3209       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3210       DS.getTypeSpecType() == DeclSpec::TST_union ||
3211       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3212     TagD = DS.getRepAsDecl();
3213 
3214     if (!TagD) // We probably had an error
3215       return 0;
3216 
3217     // Note that the above type specs guarantee that the
3218     // type rep is a Decl, whereas in many of the others
3219     // it's a Type.
3220     if (isa<TagDecl>(TagD))
3221       Tag = cast<TagDecl>(TagD);
3222     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3223       Tag = CTD->getTemplatedDecl();
3224   }
3225 
3226   if (Tag) {
3227     HandleTagNumbering(*this, Tag);
3228     Tag->setFreeStanding();
3229     if (Tag->isInvalidDecl())
3230       return Tag;
3231   }
3232 
3233   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3234     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3235     // or incomplete types shall not be restrict-qualified."
3236     if (TypeQuals & DeclSpec::TQ_restrict)
3237       Diag(DS.getRestrictSpecLoc(),
3238            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3239            << DS.getSourceRange();
3240   }
3241 
3242   if (DS.isConstexprSpecified()) {
3243     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3244     // and definitions of functions and variables.
3245     if (Tag)
3246       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3247         << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3248             DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3249             DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3250             DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3251     else
3252       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3253     // Don't emit warnings after this error.
3254     return TagD;
3255   }
3256 
3257   DiagnoseFunctionSpecifiers(DS);
3258 
3259   if (DS.isFriendSpecified()) {
3260     // If we're dealing with a decl but not a TagDecl, assume that
3261     // whatever routines created it handled the friendship aspect.
3262     if (TagD && !Tag)
3263       return 0;
3264     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3265   }
3266 
3267   CXXScopeSpec &SS = DS.getTypeSpecScope();
3268   bool IsExplicitSpecialization =
3269     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3270   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3271       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3272     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3273     // nested-name-specifier unless it is an explicit instantiation
3274     // or an explicit specialization.
3275     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3276     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3277       << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3278           DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3279           DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3280           DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3281       << SS.getRange();
3282     return 0;
3283   }
3284 
3285   // Track whether this decl-specifier declares anything.
3286   bool DeclaresAnything = true;
3287 
3288   // Handle anonymous struct definitions.
3289   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3290     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3291         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3292       if (getLangOpts().CPlusPlus ||
3293           Record->getDeclContext()->isRecord())
3294         return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy());
3295 
3296       DeclaresAnything = false;
3297     }
3298   }
3299 
3300   // Check for Microsoft C extension: anonymous struct member.
3301   if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3302       CurContext->isRecord() &&
3303       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3304     // Handle 2 kinds of anonymous struct:
3305     //   struct STRUCT;
3306     // and
3307     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3308     RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3309     if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3310         (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3311          DS.getRepAsType().get()->isStructureType())) {
3312       Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3313         << DS.getSourceRange();
3314       return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3315     }
3316   }
3317 
3318   // Skip all the checks below if we have a type error.
3319   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3320       (TagD && TagD->isInvalidDecl()))
3321     return TagD;
3322 
3323   if (getLangOpts().CPlusPlus &&
3324       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3325     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3326       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3327           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3328         DeclaresAnything = false;
3329 
3330   if (!DS.isMissingDeclaratorOk()) {
3331     // Customize diagnostic for a typedef missing a name.
3332     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3333       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3334         << DS.getSourceRange();
3335     else
3336       DeclaresAnything = false;
3337   }
3338 
3339   if (DS.isModulePrivateSpecified() &&
3340       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3341     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3342       << Tag->getTagKind()
3343       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3344 
3345   ActOnDocumentableDecl(TagD);
3346 
3347   // C 6.7/2:
3348   //   A declaration [...] shall declare at least a declarator [...], a tag,
3349   //   or the members of an enumeration.
3350   // C++ [dcl.dcl]p3:
3351   //   [If there are no declarators], and except for the declaration of an
3352   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3353   //   names into the program, or shall redeclare a name introduced by a
3354   //   previous declaration.
3355   if (!DeclaresAnything) {
3356     // In C, we allow this as a (popular) extension / bug. Don't bother
3357     // producing further diagnostics for redundant qualifiers after this.
3358     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3359     return TagD;
3360   }
3361 
3362   // C++ [dcl.stc]p1:
3363   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3364   //   init-declarator-list of the declaration shall not be empty.
3365   // C++ [dcl.fct.spec]p1:
3366   //   If a cv-qualifier appears in a decl-specifier-seq, the
3367   //   init-declarator-list of the declaration shall not be empty.
3368   //
3369   // Spurious qualifiers here appear to be valid in C.
3370   unsigned DiagID = diag::warn_standalone_specifier;
3371   if (getLangOpts().CPlusPlus)
3372     DiagID = diag::ext_standalone_specifier;
3373 
3374   // Note that a linkage-specification sets a storage class, but
3375   // 'extern "C" struct foo;' is actually valid and not theoretically
3376   // useless.
3377   if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3378     if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3379       Diag(DS.getStorageClassSpecLoc(), DiagID)
3380         << DeclSpec::getSpecifierName(SCS);
3381 
3382   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3383     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3384       << DeclSpec::getSpecifierName(TSCS);
3385   if (DS.getTypeQualifiers()) {
3386     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3387       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3388     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3389       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3390     // Restrict is covered above.
3391     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3392       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3393   }
3394 
3395   // Warn about ignored type attributes, for example:
3396   // __attribute__((aligned)) struct A;
3397   // Attributes should be placed after tag to apply to type declaration.
3398   if (!DS.getAttributes().empty()) {
3399     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3400     if (TypeSpecType == DeclSpec::TST_class ||
3401         TypeSpecType == DeclSpec::TST_struct ||
3402         TypeSpecType == DeclSpec::TST_interface ||
3403         TypeSpecType == DeclSpec::TST_union ||
3404         TypeSpecType == DeclSpec::TST_enum) {
3405       AttributeList* attrs = DS.getAttributes().getList();
3406       while (attrs) {
3407         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3408         << attrs->getName()
3409         << (TypeSpecType == DeclSpec::TST_class ? 0 :
3410             TypeSpecType == DeclSpec::TST_struct ? 1 :
3411             TypeSpecType == DeclSpec::TST_union ? 2 :
3412             TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3413         attrs = attrs->getNext();
3414       }
3415     }
3416   }
3417 
3418   return TagD;
3419 }
3420 
3421 /// We are trying to inject an anonymous member into the given scope;
3422 /// check if there's an existing declaration that can't be overloaded.
3423 ///
3424 /// \return true if this is a forbidden redeclaration
3425 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3426                                          Scope *S,
3427                                          DeclContext *Owner,
3428                                          DeclarationName Name,
3429                                          SourceLocation NameLoc,
3430                                          unsigned diagnostic) {
3431   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3432                  Sema::ForRedeclaration);
3433   if (!SemaRef.LookupName(R, S)) return false;
3434 
3435   if (R.getAsSingle<TagDecl>())
3436     return false;
3437 
3438   // Pick a representative declaration.
3439   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3440   assert(PrevDecl && "Expected a non-null Decl");
3441 
3442   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3443     return false;
3444 
3445   SemaRef.Diag(NameLoc, diagnostic) << Name;
3446   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3447 
3448   return true;
3449 }
3450 
3451 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3452 /// anonymous struct or union AnonRecord into the owning context Owner
3453 /// and scope S. This routine will be invoked just after we realize
3454 /// that an unnamed union or struct is actually an anonymous union or
3455 /// struct, e.g.,
3456 ///
3457 /// @code
3458 /// union {
3459 ///   int i;
3460 ///   float f;
3461 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3462 ///    // f into the surrounding scope.x
3463 /// @endcode
3464 ///
3465 /// This routine is recursive, injecting the names of nested anonymous
3466 /// structs/unions into the owning context and scope as well.
3467 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3468                                          DeclContext *Owner,
3469                                          RecordDecl *AnonRecord,
3470                                          AccessSpecifier AS,
3471                                          SmallVectorImpl<NamedDecl *> &Chaining,
3472                                          bool MSAnonStruct) {
3473   unsigned diagKind
3474     = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3475                             : diag::err_anonymous_struct_member_redecl;
3476 
3477   bool Invalid = false;
3478 
3479   // Look every FieldDecl and IndirectFieldDecl with a name.
3480   for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3481                                DEnd = AnonRecord->decls_end();
3482        D != DEnd; ++D) {
3483     if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3484         cast<NamedDecl>(*D)->getDeclName()) {
3485       ValueDecl *VD = cast<ValueDecl>(*D);
3486       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3487                                        VD->getLocation(), diagKind)) {
3488         // C++ [class.union]p2:
3489         //   The names of the members of an anonymous union shall be
3490         //   distinct from the names of any other entity in the
3491         //   scope in which the anonymous union is declared.
3492         Invalid = true;
3493       } else {
3494         // C++ [class.union]p2:
3495         //   For the purpose of name lookup, after the anonymous union
3496         //   definition, the members of the anonymous union are
3497         //   considered to have been defined in the scope in which the
3498         //   anonymous union is declared.
3499         unsigned OldChainingSize = Chaining.size();
3500         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3501           for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3502                PE = IF->chain_end(); PI != PE; ++PI)
3503             Chaining.push_back(*PI);
3504         else
3505           Chaining.push_back(VD);
3506 
3507         assert(Chaining.size() >= 2);
3508         NamedDecl **NamedChain =
3509           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3510         for (unsigned i = 0; i < Chaining.size(); i++)
3511           NamedChain[i] = Chaining[i];
3512 
3513         IndirectFieldDecl* IndirectField =
3514           IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3515                                     VD->getIdentifier(), VD->getType(),
3516                                     NamedChain, Chaining.size());
3517 
3518         IndirectField->setAccess(AS);
3519         IndirectField->setImplicit();
3520         SemaRef.PushOnScopeChains(IndirectField, S);
3521 
3522         // That includes picking up the appropriate access specifier.
3523         if (AS != AS_none) IndirectField->setAccess(AS);
3524 
3525         Chaining.resize(OldChainingSize);
3526       }
3527     }
3528   }
3529 
3530   return Invalid;
3531 }
3532 
3533 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3534 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
3535 /// illegal input values are mapped to SC_None.
3536 static StorageClass
3537 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3538   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3539   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3540          "Parser allowed 'typedef' as storage class VarDecl.");
3541   switch (StorageClassSpec) {
3542   case DeclSpec::SCS_unspecified:    return SC_None;
3543   case DeclSpec::SCS_extern:
3544     if (DS.isExternInLinkageSpec())
3545       return SC_None;
3546     return SC_Extern;
3547   case DeclSpec::SCS_static:         return SC_Static;
3548   case DeclSpec::SCS_auto:           return SC_Auto;
3549   case DeclSpec::SCS_register:       return SC_Register;
3550   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3551     // Illegal SCSs map to None: error reporting is up to the caller.
3552   case DeclSpec::SCS_mutable:        // Fall through.
3553   case DeclSpec::SCS_typedef:        return SC_None;
3554   }
3555   llvm_unreachable("unknown storage class specifier");
3556 }
3557 
3558 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
3559   assert(Record->hasInClassInitializer());
3560 
3561   for (DeclContext::decl_iterator I = Record->decls_begin(),
3562                                   E = Record->decls_end();
3563        I != E; ++I) {
3564     FieldDecl *FD = dyn_cast<FieldDecl>(*I);
3565     if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*I))
3566       FD = IFD->getAnonField();
3567     if (FD && FD->hasInClassInitializer())
3568       return FD->getLocation();
3569   }
3570 
3571   llvm_unreachable("couldn't find in-class initializer");
3572 }
3573 
3574 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3575                                       SourceLocation DefaultInitLoc) {
3576   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3577     return;
3578 
3579   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
3580   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
3581 }
3582 
3583 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
3584                                       CXXRecordDecl *AnonUnion) {
3585   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
3586     return;
3587 
3588   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
3589 }
3590 
3591 /// BuildAnonymousStructOrUnion - Handle the declaration of an
3592 /// anonymous structure or union. Anonymous unions are a C++ feature
3593 /// (C++ [class.union]) and a C11 feature; anonymous structures
3594 /// are a C11 feature and GNU C++ extension.
3595 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3596                                         AccessSpecifier AS,
3597                                         RecordDecl *Record,
3598                                         const PrintingPolicy &Policy) {
3599   DeclContext *Owner = Record->getDeclContext();
3600 
3601   // Diagnose whether this anonymous struct/union is an extension.
3602   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3603     Diag(Record->getLocation(), diag::ext_anonymous_union);
3604   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3605     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3606   else if (!Record->isUnion() && !getLangOpts().C11)
3607     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3608 
3609   // C and C++ require different kinds of checks for anonymous
3610   // structs/unions.
3611   bool Invalid = false;
3612   if (getLangOpts().CPlusPlus) {
3613     const char* PrevSpec = 0;
3614     unsigned DiagID;
3615     if (Record->isUnion()) {
3616       // C++ [class.union]p6:
3617       //   Anonymous unions declared in a named namespace or in the
3618       //   global namespace shall be declared static.
3619       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3620           (isa<TranslationUnitDecl>(Owner) ||
3621            (isa<NamespaceDecl>(Owner) &&
3622             cast<NamespaceDecl>(Owner)->getDeclName()))) {
3623         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3624           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3625 
3626         // Recover by adding 'static'.
3627         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3628                                PrevSpec, DiagID, Policy);
3629       }
3630       // C++ [class.union]p6:
3631       //   A storage class is not allowed in a declaration of an
3632       //   anonymous union in a class scope.
3633       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3634                isa<RecordDecl>(Owner)) {
3635         Diag(DS.getStorageClassSpecLoc(),
3636              diag::err_anonymous_union_with_storage_spec)
3637           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3638 
3639         // Recover by removing the storage specifier.
3640         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3641                                SourceLocation(),
3642                                PrevSpec, DiagID, Context.getPrintingPolicy());
3643       }
3644     }
3645 
3646     // Ignore const/volatile/restrict qualifiers.
3647     if (DS.getTypeQualifiers()) {
3648       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3649         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3650           << Record->isUnion() << "const"
3651           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3652       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3653         Diag(DS.getVolatileSpecLoc(),
3654              diag::ext_anonymous_struct_union_qualified)
3655           << Record->isUnion() << "volatile"
3656           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3657       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3658         Diag(DS.getRestrictSpecLoc(),
3659              diag::ext_anonymous_struct_union_qualified)
3660           << Record->isUnion() << "restrict"
3661           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3662       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3663         Diag(DS.getAtomicSpecLoc(),
3664              diag::ext_anonymous_struct_union_qualified)
3665           << Record->isUnion() << "_Atomic"
3666           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3667 
3668       DS.ClearTypeQualifiers();
3669     }
3670 
3671     // C++ [class.union]p2:
3672     //   The member-specification of an anonymous union shall only
3673     //   define non-static data members. [Note: nested types and
3674     //   functions cannot be declared within an anonymous union. ]
3675     for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3676                                  MemEnd = Record->decls_end();
3677          Mem != MemEnd; ++Mem) {
3678       if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3679         // C++ [class.union]p3:
3680         //   An anonymous union shall not have private or protected
3681         //   members (clause 11).
3682         assert(FD->getAccess() != AS_none);
3683         if (FD->getAccess() != AS_public) {
3684           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3685             << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3686           Invalid = true;
3687         }
3688 
3689         // C++ [class.union]p1
3690         //   An object of a class with a non-trivial constructor, a non-trivial
3691         //   copy constructor, a non-trivial destructor, or a non-trivial copy
3692         //   assignment operator cannot be a member of a union, nor can an
3693         //   array of such objects.
3694         if (CheckNontrivialField(FD))
3695           Invalid = true;
3696       } else if ((*Mem)->isImplicit()) {
3697         // Any implicit members are fine.
3698       } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3699         // This is a type that showed up in an
3700         // elaborated-type-specifier inside the anonymous struct or
3701         // union, but which actually declares a type outside of the
3702         // anonymous struct or union. It's okay.
3703       } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3704         if (!MemRecord->isAnonymousStructOrUnion() &&
3705             MemRecord->getDeclName()) {
3706           // Visual C++ allows type definition in anonymous struct or union.
3707           if (getLangOpts().MicrosoftExt)
3708             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3709               << (int)Record->isUnion();
3710           else {
3711             // This is a nested type declaration.
3712             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3713               << (int)Record->isUnion();
3714             Invalid = true;
3715           }
3716         } else {
3717           // This is an anonymous type definition within another anonymous type.
3718           // This is a popular extension, provided by Plan9, MSVC and GCC, but
3719           // not part of standard C++.
3720           Diag(MemRecord->getLocation(),
3721                diag::ext_anonymous_record_with_anonymous_type)
3722             << (int)Record->isUnion();
3723         }
3724       } else if (isa<AccessSpecDecl>(*Mem)) {
3725         // Any access specifier is fine.
3726       } else {
3727         // We have something that isn't a non-static data
3728         // member. Complain about it.
3729         unsigned DK = diag::err_anonymous_record_bad_member;
3730         if (isa<TypeDecl>(*Mem))
3731           DK = diag::err_anonymous_record_with_type;
3732         else if (isa<FunctionDecl>(*Mem))
3733           DK = diag::err_anonymous_record_with_function;
3734         else if (isa<VarDecl>(*Mem))
3735           DK = diag::err_anonymous_record_with_static;
3736 
3737         // Visual C++ allows type definition in anonymous struct or union.
3738         if (getLangOpts().MicrosoftExt &&
3739             DK == diag::err_anonymous_record_with_type)
3740           Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3741             << (int)Record->isUnion();
3742         else {
3743           Diag((*Mem)->getLocation(), DK)
3744               << (int)Record->isUnion();
3745           Invalid = true;
3746         }
3747       }
3748     }
3749 
3750     // C++11 [class.union]p8 (DR1460):
3751     //   At most one variant member of a union may have a
3752     //   brace-or-equal-initializer.
3753     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
3754         Owner->isRecord())
3755       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
3756                                 cast<CXXRecordDecl>(Record));
3757   }
3758 
3759   if (!Record->isUnion() && !Owner->isRecord()) {
3760     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3761       << (int)getLangOpts().CPlusPlus;
3762     Invalid = true;
3763   }
3764 
3765   // Mock up a declarator.
3766   Declarator Dc(DS, Declarator::MemberContext);
3767   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3768   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3769 
3770   // Create a declaration for this anonymous struct/union.
3771   NamedDecl *Anon = 0;
3772   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3773     Anon = FieldDecl::Create(Context, OwningClass,
3774                              DS.getLocStart(),
3775                              Record->getLocation(),
3776                              /*IdentifierInfo=*/0,
3777                              Context.getTypeDeclType(Record),
3778                              TInfo,
3779                              /*BitWidth=*/0, /*Mutable=*/false,
3780                              /*InitStyle=*/ICIS_NoInit);
3781     Anon->setAccess(AS);
3782     if (getLangOpts().CPlusPlus)
3783       FieldCollector->Add(cast<FieldDecl>(Anon));
3784   } else {
3785     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3786     VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3787     if (SCSpec == DeclSpec::SCS_mutable) {
3788       // mutable can only appear on non-static class members, so it's always
3789       // an error here
3790       Diag(Record->getLocation(), diag::err_mutable_nonmember);
3791       Invalid = true;
3792       SC = SC_None;
3793     }
3794 
3795     Anon = VarDecl::Create(Context, Owner,
3796                            DS.getLocStart(),
3797                            Record->getLocation(), /*IdentifierInfo=*/0,
3798                            Context.getTypeDeclType(Record),
3799                            TInfo, SC);
3800 
3801     // Default-initialize the implicit variable. This initialization will be
3802     // trivial in almost all cases, except if a union member has an in-class
3803     // initializer:
3804     //   union { int n = 0; };
3805     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3806   }
3807   Anon->setImplicit();
3808 
3809   // Mark this as an anonymous struct/union type.
3810   Record->setAnonymousStructOrUnion(true);
3811 
3812   // Add the anonymous struct/union object to the current
3813   // context. We'll be referencing this object when we refer to one of
3814   // its members.
3815   Owner->addDecl(Anon);
3816 
3817   // Inject the members of the anonymous struct/union into the owning
3818   // context and into the identifier resolver chain for name lookup
3819   // purposes.
3820   SmallVector<NamedDecl*, 2> Chain;
3821   Chain.push_back(Anon);
3822 
3823   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3824                                           Chain, false))
3825     Invalid = true;
3826 
3827   if (Invalid)
3828     Anon->setInvalidDecl();
3829 
3830   return Anon;
3831 }
3832 
3833 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3834 /// Microsoft C anonymous structure.
3835 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3836 /// Example:
3837 ///
3838 /// struct A { int a; };
3839 /// struct B { struct A; int b; };
3840 ///
3841 /// void foo() {
3842 ///   B var;
3843 ///   var.a = 3;
3844 /// }
3845 ///
3846 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3847                                            RecordDecl *Record) {
3848 
3849   // If there is no Record, get the record via the typedef.
3850   if (!Record)
3851     Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3852 
3853   // Mock up a declarator.
3854   Declarator Dc(DS, Declarator::TypeNameContext);
3855   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3856   assert(TInfo && "couldn't build declarator info for anonymous struct");
3857 
3858   // Create a declaration for this anonymous struct.
3859   NamedDecl* Anon = FieldDecl::Create(Context,
3860                              cast<RecordDecl>(CurContext),
3861                              DS.getLocStart(),
3862                              DS.getLocStart(),
3863                              /*IdentifierInfo=*/0,
3864                              Context.getTypeDeclType(Record),
3865                              TInfo,
3866                              /*BitWidth=*/0, /*Mutable=*/false,
3867                              /*InitStyle=*/ICIS_NoInit);
3868   Anon->setImplicit();
3869 
3870   // Add the anonymous struct object to the current context.
3871   CurContext->addDecl(Anon);
3872 
3873   // Inject the members of the anonymous struct into the current
3874   // context and into the identifier resolver chain for name lookup
3875   // purposes.
3876   SmallVector<NamedDecl*, 2> Chain;
3877   Chain.push_back(Anon);
3878 
3879   RecordDecl *RecordDef = Record->getDefinition();
3880   if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3881                                                         RecordDef, AS_none,
3882                                                         Chain, true))
3883     Anon->setInvalidDecl();
3884 
3885   return Anon;
3886 }
3887 
3888 /// GetNameForDeclarator - Determine the full declaration name for the
3889 /// given Declarator.
3890 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3891   return GetNameFromUnqualifiedId(D.getName());
3892 }
3893 
3894 /// \brief Retrieves the declaration name from a parsed unqualified-id.
3895 DeclarationNameInfo
3896 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3897   DeclarationNameInfo NameInfo;
3898   NameInfo.setLoc(Name.StartLocation);
3899 
3900   switch (Name.getKind()) {
3901 
3902   case UnqualifiedId::IK_ImplicitSelfParam:
3903   case UnqualifiedId::IK_Identifier:
3904     NameInfo.setName(Name.Identifier);
3905     NameInfo.setLoc(Name.StartLocation);
3906     return NameInfo;
3907 
3908   case UnqualifiedId::IK_OperatorFunctionId:
3909     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3910                                            Name.OperatorFunctionId.Operator));
3911     NameInfo.setLoc(Name.StartLocation);
3912     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3913       = Name.OperatorFunctionId.SymbolLocations[0];
3914     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3915       = Name.EndLocation.getRawEncoding();
3916     return NameInfo;
3917 
3918   case UnqualifiedId::IK_LiteralOperatorId:
3919     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3920                                                            Name.Identifier));
3921     NameInfo.setLoc(Name.StartLocation);
3922     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3923     return NameInfo;
3924 
3925   case UnqualifiedId::IK_ConversionFunctionId: {
3926     TypeSourceInfo *TInfo;
3927     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3928     if (Ty.isNull())
3929       return DeclarationNameInfo();
3930     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3931                                                Context.getCanonicalType(Ty)));
3932     NameInfo.setLoc(Name.StartLocation);
3933     NameInfo.setNamedTypeInfo(TInfo);
3934     return NameInfo;
3935   }
3936 
3937   case UnqualifiedId::IK_ConstructorName: {
3938     TypeSourceInfo *TInfo;
3939     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3940     if (Ty.isNull())
3941       return DeclarationNameInfo();
3942     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3943                                               Context.getCanonicalType(Ty)));
3944     NameInfo.setLoc(Name.StartLocation);
3945     NameInfo.setNamedTypeInfo(TInfo);
3946     return NameInfo;
3947   }
3948 
3949   case UnqualifiedId::IK_ConstructorTemplateId: {
3950     // In well-formed code, we can only have a constructor
3951     // template-id that refers to the current context, so go there
3952     // to find the actual type being constructed.
3953     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3954     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3955       return DeclarationNameInfo();
3956 
3957     // Determine the type of the class being constructed.
3958     QualType CurClassType = Context.getTypeDeclType(CurClass);
3959 
3960     // FIXME: Check two things: that the template-id names the same type as
3961     // CurClassType, and that the template-id does not occur when the name
3962     // was qualified.
3963 
3964     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3965                                     Context.getCanonicalType(CurClassType)));
3966     NameInfo.setLoc(Name.StartLocation);
3967     // FIXME: should we retrieve TypeSourceInfo?
3968     NameInfo.setNamedTypeInfo(0);
3969     return NameInfo;
3970   }
3971 
3972   case UnqualifiedId::IK_DestructorName: {
3973     TypeSourceInfo *TInfo;
3974     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3975     if (Ty.isNull())
3976       return DeclarationNameInfo();
3977     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3978                                               Context.getCanonicalType(Ty)));
3979     NameInfo.setLoc(Name.StartLocation);
3980     NameInfo.setNamedTypeInfo(TInfo);
3981     return NameInfo;
3982   }
3983 
3984   case UnqualifiedId::IK_TemplateId: {
3985     TemplateName TName = Name.TemplateId->Template.get();
3986     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3987     return Context.getNameForTemplate(TName, TNameLoc);
3988   }
3989 
3990   } // switch (Name.getKind())
3991 
3992   llvm_unreachable("Unknown name kind");
3993 }
3994 
3995 static QualType getCoreType(QualType Ty) {
3996   do {
3997     if (Ty->isPointerType() || Ty->isReferenceType())
3998       Ty = Ty->getPointeeType();
3999     else if (Ty->isArrayType())
4000       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4001     else
4002       return Ty.withoutLocalFastQualifiers();
4003   } while (true);
4004 }
4005 
4006 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4007 /// and Definition have "nearly" matching parameters. This heuristic is
4008 /// used to improve diagnostics in the case where an out-of-line function
4009 /// definition doesn't match any declaration within the class or namespace.
4010 /// Also sets Params to the list of indices to the parameters that differ
4011 /// between the declaration and the definition. If hasSimilarParameters
4012 /// returns true and Params is empty, then all of the parameters match.
4013 static bool hasSimilarParameters(ASTContext &Context,
4014                                      FunctionDecl *Declaration,
4015                                      FunctionDecl *Definition,
4016                                      SmallVectorImpl<unsigned> &Params) {
4017   Params.clear();
4018   if (Declaration->param_size() != Definition->param_size())
4019     return false;
4020   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4021     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4022     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4023 
4024     // The parameter types are identical
4025     if (Context.hasSameType(DefParamTy, DeclParamTy))
4026       continue;
4027 
4028     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4029     QualType DefParamBaseTy = getCoreType(DefParamTy);
4030     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4031     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4032 
4033     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4034         (DeclTyName && DeclTyName == DefTyName))
4035       Params.push_back(Idx);
4036     else  // The two parameters aren't even close
4037       return false;
4038   }
4039 
4040   return true;
4041 }
4042 
4043 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4044 /// declarator needs to be rebuilt in the current instantiation.
4045 /// Any bits of declarator which appear before the name are valid for
4046 /// consideration here.  That's specifically the type in the decl spec
4047 /// and the base type in any member-pointer chunks.
4048 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4049                                                     DeclarationName Name) {
4050   // The types we specifically need to rebuild are:
4051   //   - typenames, typeofs, and decltypes
4052   //   - types which will become injected class names
4053   // Of course, we also need to rebuild any type referencing such a
4054   // type.  It's safest to just say "dependent", but we call out a
4055   // few cases here.
4056 
4057   DeclSpec &DS = D.getMutableDeclSpec();
4058   switch (DS.getTypeSpecType()) {
4059   case DeclSpec::TST_typename:
4060   case DeclSpec::TST_typeofType:
4061   case DeclSpec::TST_underlyingType:
4062   case DeclSpec::TST_atomic: {
4063     // Grab the type from the parser.
4064     TypeSourceInfo *TSI = 0;
4065     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4066     if (T.isNull() || !T->isDependentType()) break;
4067 
4068     // Make sure there's a type source info.  This isn't really much
4069     // of a waste; most dependent types should have type source info
4070     // attached already.
4071     if (!TSI)
4072       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4073 
4074     // Rebuild the type in the current instantiation.
4075     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4076     if (!TSI) return true;
4077 
4078     // Store the new type back in the decl spec.
4079     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4080     DS.UpdateTypeRep(LocType);
4081     break;
4082   }
4083 
4084   case DeclSpec::TST_decltype:
4085   case DeclSpec::TST_typeofExpr: {
4086     Expr *E = DS.getRepAsExpr();
4087     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4088     if (Result.isInvalid()) return true;
4089     DS.UpdateExprRep(Result.get());
4090     break;
4091   }
4092 
4093   default:
4094     // Nothing to do for these decl specs.
4095     break;
4096   }
4097 
4098   // It doesn't matter what order we do this in.
4099   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4100     DeclaratorChunk &Chunk = D.getTypeObject(I);
4101 
4102     // The only type information in the declarator which can come
4103     // before the declaration name is the base type of a member
4104     // pointer.
4105     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4106       continue;
4107 
4108     // Rebuild the scope specifier in-place.
4109     CXXScopeSpec &SS = Chunk.Mem.Scope();
4110     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4111       return true;
4112   }
4113 
4114   return false;
4115 }
4116 
4117 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4118   D.setFunctionDefinitionKind(FDK_Declaration);
4119   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4120 
4121   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4122       Dcl && Dcl->getDeclContext()->isFileContext())
4123     Dcl->setTopLevelDeclInObjCContainer();
4124 
4125   return Dcl;
4126 }
4127 
4128 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4129 ///   If T is the name of a class, then each of the following shall have a
4130 ///   name different from T:
4131 ///     - every static data member of class T;
4132 ///     - every member function of class T
4133 ///     - every member of class T that is itself a type;
4134 /// \returns true if the declaration name violates these rules.
4135 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4136                                    DeclarationNameInfo NameInfo) {
4137   DeclarationName Name = NameInfo.getName();
4138 
4139   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4140     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4141       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4142       return true;
4143     }
4144 
4145   return false;
4146 }
4147 
4148 /// \brief Diagnose a declaration whose declarator-id has the given
4149 /// nested-name-specifier.
4150 ///
4151 /// \param SS The nested-name-specifier of the declarator-id.
4152 ///
4153 /// \param DC The declaration context to which the nested-name-specifier
4154 /// resolves.
4155 ///
4156 /// \param Name The name of the entity being declared.
4157 ///
4158 /// \param Loc The location of the name of the entity being declared.
4159 ///
4160 /// \returns true if we cannot safely recover from this error, false otherwise.
4161 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4162                                         DeclarationName Name,
4163                                         SourceLocation Loc) {
4164   DeclContext *Cur = CurContext;
4165   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4166     Cur = Cur->getParent();
4167 
4168   // If the user provided a superfluous scope specifier that refers back to the
4169   // class in which the entity is already declared, diagnose and ignore it.
4170   //
4171   // class X {
4172   //   void X::f();
4173   // };
4174   //
4175   // Note, it was once ill-formed to give redundant qualification in all
4176   // contexts, but that rule was removed by DR482.
4177   if (Cur->Equals(DC)) {
4178     if (Cur->isRecord()) {
4179       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4180                                       : diag::err_member_extra_qualification)
4181         << Name << FixItHint::CreateRemoval(SS.getRange());
4182       SS.clear();
4183     } else {
4184       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4185     }
4186     return false;
4187   }
4188 
4189   // Check whether the qualifying scope encloses the scope of the original
4190   // declaration.
4191   if (!Cur->Encloses(DC)) {
4192     if (Cur->isRecord())
4193       Diag(Loc, diag::err_member_qualification)
4194         << Name << SS.getRange();
4195     else if (isa<TranslationUnitDecl>(DC))
4196       Diag(Loc, diag::err_invalid_declarator_global_scope)
4197         << Name << SS.getRange();
4198     else if (isa<FunctionDecl>(Cur))
4199       Diag(Loc, diag::err_invalid_declarator_in_function)
4200         << Name << SS.getRange();
4201     else if (isa<BlockDecl>(Cur))
4202       Diag(Loc, diag::err_invalid_declarator_in_block)
4203         << Name << SS.getRange();
4204     else
4205       Diag(Loc, diag::err_invalid_declarator_scope)
4206       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4207 
4208     return true;
4209   }
4210 
4211   if (Cur->isRecord()) {
4212     // Cannot qualify members within a class.
4213     Diag(Loc, diag::err_member_qualification)
4214       << Name << SS.getRange();
4215     SS.clear();
4216 
4217     // C++ constructors and destructors with incorrect scopes can break
4218     // our AST invariants by having the wrong underlying types. If
4219     // that's the case, then drop this declaration entirely.
4220     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4221          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4222         !Context.hasSameType(Name.getCXXNameType(),
4223                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4224       return true;
4225 
4226     return false;
4227   }
4228 
4229   // C++11 [dcl.meaning]p1:
4230   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4231   //   not begin with a decltype-specifer"
4232   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4233   while (SpecLoc.getPrefix())
4234     SpecLoc = SpecLoc.getPrefix();
4235   if (dyn_cast_or_null<DecltypeType>(
4236         SpecLoc.getNestedNameSpecifier()->getAsType()))
4237     Diag(Loc, diag::err_decltype_in_declarator)
4238       << SpecLoc.getTypeLoc().getSourceRange();
4239 
4240   return false;
4241 }
4242 
4243 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4244                                   MultiTemplateParamsArg TemplateParamLists) {
4245   // TODO: consider using NameInfo for diagnostic.
4246   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4247   DeclarationName Name = NameInfo.getName();
4248 
4249   // All of these full declarators require an identifier.  If it doesn't have
4250   // one, the ParsedFreeStandingDeclSpec action should be used.
4251   if (!Name) {
4252     if (!D.isInvalidType())  // Reject this if we think it is valid.
4253       Diag(D.getDeclSpec().getLocStart(),
4254            diag::err_declarator_need_ident)
4255         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4256     return 0;
4257   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4258     return 0;
4259 
4260   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4261   // we find one that is.
4262   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4263          (S->getFlags() & Scope::TemplateParamScope) != 0)
4264     S = S->getParent();
4265 
4266   DeclContext *DC = CurContext;
4267   if (D.getCXXScopeSpec().isInvalid())
4268     D.setInvalidType();
4269   else if (D.getCXXScopeSpec().isSet()) {
4270     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4271                                         UPPC_DeclarationQualifier))
4272       return 0;
4273 
4274     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4275     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4276     if (!DC || isa<EnumDecl>(DC)) {
4277       // If we could not compute the declaration context, it's because the
4278       // declaration context is dependent but does not refer to a class,
4279       // class template, or class template partial specialization. Complain
4280       // and return early, to avoid the coming semantic disaster.
4281       Diag(D.getIdentifierLoc(),
4282            diag::err_template_qualified_declarator_no_match)
4283         << D.getCXXScopeSpec().getScopeRep()
4284         << D.getCXXScopeSpec().getRange();
4285       return 0;
4286     }
4287     bool IsDependentContext = DC->isDependentContext();
4288 
4289     if (!IsDependentContext &&
4290         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4291       return 0;
4292 
4293     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4294       Diag(D.getIdentifierLoc(),
4295            diag::err_member_def_undefined_record)
4296         << Name << DC << D.getCXXScopeSpec().getRange();
4297       D.setInvalidType();
4298     } else if (!D.getDeclSpec().isFriendSpecified()) {
4299       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4300                                       Name, D.getIdentifierLoc())) {
4301         if (DC->isRecord())
4302           return 0;
4303 
4304         D.setInvalidType();
4305       }
4306     }
4307 
4308     // Check whether we need to rebuild the type of the given
4309     // declaration in the current instantiation.
4310     if (EnteringContext && IsDependentContext &&
4311         TemplateParamLists.size() != 0) {
4312       ContextRAII SavedContext(*this, DC);
4313       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4314         D.setInvalidType();
4315     }
4316   }
4317 
4318   if (DiagnoseClassNameShadow(DC, NameInfo))
4319     // If this is a typedef, we'll end up spewing multiple diagnostics.
4320     // Just return early; it's safer.
4321     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4322       return 0;
4323 
4324   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4325   QualType R = TInfo->getType();
4326 
4327   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4328                                       UPPC_DeclarationType))
4329     D.setInvalidType();
4330 
4331   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4332                         ForRedeclaration);
4333 
4334   // See if this is a redefinition of a variable in the same scope.
4335   if (!D.getCXXScopeSpec().isSet()) {
4336     bool IsLinkageLookup = false;
4337     bool CreateBuiltins = false;
4338 
4339     // If the declaration we're planning to build will be a function
4340     // or object with linkage, then look for another declaration with
4341     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4342     //
4343     // If the declaration we're planning to build will be declared with
4344     // external linkage in the translation unit, create any builtin with
4345     // the same name.
4346     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4347       /* Do nothing*/;
4348     else if (CurContext->isFunctionOrMethod() &&
4349              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4350               R->isFunctionType())) {
4351       IsLinkageLookup = true;
4352       CreateBuiltins =
4353           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4354     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4355                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4356       CreateBuiltins = true;
4357 
4358     if (IsLinkageLookup)
4359       Previous.clear(LookupRedeclarationWithLinkage);
4360 
4361     LookupName(Previous, S, CreateBuiltins);
4362   } else { // Something like "int foo::x;"
4363     LookupQualifiedName(Previous, DC);
4364 
4365     // C++ [dcl.meaning]p1:
4366     //   When the declarator-id is qualified, the declaration shall refer to a
4367     //  previously declared member of the class or namespace to which the
4368     //  qualifier refers (or, in the case of a namespace, of an element of the
4369     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4370     //  thereof; [...]
4371     //
4372     // Note that we already checked the context above, and that we do not have
4373     // enough information to make sure that Previous contains the declaration
4374     // we want to match. For example, given:
4375     //
4376     //   class X {
4377     //     void f();
4378     //     void f(float);
4379     //   };
4380     //
4381     //   void X::f(int) { } // ill-formed
4382     //
4383     // In this case, Previous will point to the overload set
4384     // containing the two f's declared in X, but neither of them
4385     // matches.
4386 
4387     // C++ [dcl.meaning]p1:
4388     //   [...] the member shall not merely have been introduced by a
4389     //   using-declaration in the scope of the class or namespace nominated by
4390     //   the nested-name-specifier of the declarator-id.
4391     RemoveUsingDecls(Previous);
4392   }
4393 
4394   if (Previous.isSingleResult() &&
4395       Previous.getFoundDecl()->isTemplateParameter()) {
4396     // Maybe we will complain about the shadowed template parameter.
4397     if (!D.isInvalidType())
4398       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4399                                       Previous.getFoundDecl());
4400 
4401     // Just pretend that we didn't see the previous declaration.
4402     Previous.clear();
4403   }
4404 
4405   // In C++, the previous declaration we find might be a tag type
4406   // (class or enum). In this case, the new declaration will hide the
4407   // tag type. Note that this does does not apply if we're declaring a
4408   // typedef (C++ [dcl.typedef]p4).
4409   if (Previous.isSingleTagDecl() &&
4410       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4411     Previous.clear();
4412 
4413   // Check that there are no default arguments other than in the parameters
4414   // of a function declaration (C++ only).
4415   if (getLangOpts().CPlusPlus)
4416     CheckExtraCXXDefaultArguments(D);
4417 
4418   NamedDecl *New;
4419 
4420   bool AddToScope = true;
4421   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4422     if (TemplateParamLists.size()) {
4423       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4424       return 0;
4425     }
4426 
4427     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4428   } else if (R->isFunctionType()) {
4429     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4430                                   TemplateParamLists,
4431                                   AddToScope);
4432   } else {
4433     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4434                                   AddToScope);
4435   }
4436 
4437   if (New == 0)
4438     return 0;
4439 
4440   // If this has an identifier and is not an invalid redeclaration or
4441   // function template specialization, add it to the scope stack.
4442   if (New->getDeclName() && AddToScope &&
4443        !(D.isRedeclaration() && New->isInvalidDecl())) {
4444     // Only make a locally-scoped extern declaration visible if it is the first
4445     // declaration of this entity. Qualified lookup for such an entity should
4446     // only find this declaration if there is no visible declaration of it.
4447     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4448     PushOnScopeChains(New, S, AddToContext);
4449     if (!AddToContext)
4450       CurContext->addHiddenDecl(New);
4451   }
4452 
4453   return New;
4454 }
4455 
4456 /// Helper method to turn variable array types into constant array
4457 /// types in certain situations which would otherwise be errors (for
4458 /// GCC compatibility).
4459 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4460                                                     ASTContext &Context,
4461                                                     bool &SizeIsNegative,
4462                                                     llvm::APSInt &Oversized) {
4463   // This method tries to turn a variable array into a constant
4464   // array even when the size isn't an ICE.  This is necessary
4465   // for compatibility with code that depends on gcc's buggy
4466   // constant expression folding, like struct {char x[(int)(char*)2];}
4467   SizeIsNegative = false;
4468   Oversized = 0;
4469 
4470   if (T->isDependentType())
4471     return QualType();
4472 
4473   QualifierCollector Qs;
4474   const Type *Ty = Qs.strip(T);
4475 
4476   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4477     QualType Pointee = PTy->getPointeeType();
4478     QualType FixedType =
4479         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4480                                             Oversized);
4481     if (FixedType.isNull()) return FixedType;
4482     FixedType = Context.getPointerType(FixedType);
4483     return Qs.apply(Context, FixedType);
4484   }
4485   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4486     QualType Inner = PTy->getInnerType();
4487     QualType FixedType =
4488         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4489                                             Oversized);
4490     if (FixedType.isNull()) return FixedType;
4491     FixedType = Context.getParenType(FixedType);
4492     return Qs.apply(Context, FixedType);
4493   }
4494 
4495   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4496   if (!VLATy)
4497     return QualType();
4498   // FIXME: We should probably handle this case
4499   if (VLATy->getElementType()->isVariablyModifiedType())
4500     return QualType();
4501 
4502   llvm::APSInt Res;
4503   if (!VLATy->getSizeExpr() ||
4504       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4505     return QualType();
4506 
4507   // Check whether the array size is negative.
4508   if (Res.isSigned() && Res.isNegative()) {
4509     SizeIsNegative = true;
4510     return QualType();
4511   }
4512 
4513   // Check whether the array is too large to be addressed.
4514   unsigned ActiveSizeBits
4515     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4516                                               Res);
4517   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4518     Oversized = Res;
4519     return QualType();
4520   }
4521 
4522   return Context.getConstantArrayType(VLATy->getElementType(),
4523                                       Res, ArrayType::Normal, 0);
4524 }
4525 
4526 static void
4527 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4528   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4529     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4530     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4531                                       DstPTL.getPointeeLoc());
4532     DstPTL.setStarLoc(SrcPTL.getStarLoc());
4533     return;
4534   }
4535   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4536     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4537     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4538                                       DstPTL.getInnerLoc());
4539     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4540     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4541     return;
4542   }
4543   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4544   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4545   TypeLoc SrcElemTL = SrcATL.getElementLoc();
4546   TypeLoc DstElemTL = DstATL.getElementLoc();
4547   DstElemTL.initializeFullCopy(SrcElemTL);
4548   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4549   DstATL.setSizeExpr(SrcATL.getSizeExpr());
4550   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4551 }
4552 
4553 /// Helper method to turn variable array types into constant array
4554 /// types in certain situations which would otherwise be errors (for
4555 /// GCC compatibility).
4556 static TypeSourceInfo*
4557 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4558                                               ASTContext &Context,
4559                                               bool &SizeIsNegative,
4560                                               llvm::APSInt &Oversized) {
4561   QualType FixedTy
4562     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4563                                           SizeIsNegative, Oversized);
4564   if (FixedTy.isNull())
4565     return 0;
4566   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4567   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4568                                     FixedTInfo->getTypeLoc());
4569   return FixedTInfo;
4570 }
4571 
4572 /// \brief Register the given locally-scoped extern "C" declaration so
4573 /// that it can be found later for redeclarations. We include any extern "C"
4574 /// declaration that is not visible in the translation unit here, not just
4575 /// function-scope declarations.
4576 void
4577 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4578   if (!getLangOpts().CPlusPlus &&
4579       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4580     // Don't need to track declarations in the TU in C.
4581     return;
4582 
4583   // Note that we have a locally-scoped external with this name.
4584   // FIXME: There can be multiple such declarations if they are functions marked
4585   // __attribute__((overloadable)) declared in function scope in C.
4586   LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4587 }
4588 
4589 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4590   if (ExternalSource) {
4591     // Load locally-scoped external decls from the external source.
4592     // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4593     SmallVector<NamedDecl *, 4> Decls;
4594     ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4595     for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4596       llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4597         = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4598       if (Pos == LocallyScopedExternCDecls.end())
4599         LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4600     }
4601   }
4602 
4603   NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4604   return D ? D->getMostRecentDecl() : 0;
4605 }
4606 
4607 /// \brief Diagnose function specifiers on a declaration of an identifier that
4608 /// does not identify a function.
4609 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4610   // FIXME: We should probably indicate the identifier in question to avoid
4611   // confusion for constructs like "inline int a(), b;"
4612   if (DS.isInlineSpecified())
4613     Diag(DS.getInlineSpecLoc(),
4614          diag::err_inline_non_function);
4615 
4616   if (DS.isVirtualSpecified())
4617     Diag(DS.getVirtualSpecLoc(),
4618          diag::err_virtual_non_function);
4619 
4620   if (DS.isExplicitSpecified())
4621     Diag(DS.getExplicitSpecLoc(),
4622          diag::err_explicit_non_function);
4623 
4624   if (DS.isNoreturnSpecified())
4625     Diag(DS.getNoreturnSpecLoc(),
4626          diag::err_noreturn_non_function);
4627 }
4628 
4629 NamedDecl*
4630 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4631                              TypeSourceInfo *TInfo, LookupResult &Previous) {
4632   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4633   if (D.getCXXScopeSpec().isSet()) {
4634     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4635       << D.getCXXScopeSpec().getRange();
4636     D.setInvalidType();
4637     // Pretend we didn't see the scope specifier.
4638     DC = CurContext;
4639     Previous.clear();
4640   }
4641 
4642   DiagnoseFunctionSpecifiers(D.getDeclSpec());
4643 
4644   if (D.getDeclSpec().isConstexprSpecified())
4645     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4646       << 1;
4647 
4648   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4649     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4650       << D.getName().getSourceRange();
4651     return 0;
4652   }
4653 
4654   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4655   if (!NewTD) return 0;
4656 
4657   // Handle attributes prior to checking for duplicates in MergeVarDecl
4658   ProcessDeclAttributes(S, NewTD, D);
4659 
4660   CheckTypedefForVariablyModifiedType(S, NewTD);
4661 
4662   bool Redeclaration = D.isRedeclaration();
4663   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4664   D.setRedeclaration(Redeclaration);
4665   return ND;
4666 }
4667 
4668 void
4669 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4670   // C99 6.7.7p2: If a typedef name specifies a variably modified type
4671   // then it shall have block scope.
4672   // Note that variably modified types must be fixed before merging the decl so
4673   // that redeclarations will match.
4674   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4675   QualType T = TInfo->getType();
4676   if (T->isVariablyModifiedType()) {
4677     getCurFunction()->setHasBranchProtectedScope();
4678 
4679     if (S->getFnParent() == 0) {
4680       bool SizeIsNegative;
4681       llvm::APSInt Oversized;
4682       TypeSourceInfo *FixedTInfo =
4683         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4684                                                       SizeIsNegative,
4685                                                       Oversized);
4686       if (FixedTInfo) {
4687         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4688         NewTD->setTypeSourceInfo(FixedTInfo);
4689       } else {
4690         if (SizeIsNegative)
4691           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4692         else if (T->isVariableArrayType())
4693           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4694         else if (Oversized.getBoolValue())
4695           Diag(NewTD->getLocation(), diag::err_array_too_large)
4696             << Oversized.toString(10);
4697         else
4698           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4699         NewTD->setInvalidDecl();
4700       }
4701     }
4702   }
4703 }
4704 
4705 
4706 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4707 /// declares a typedef-name, either using the 'typedef' type specifier or via
4708 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4709 NamedDecl*
4710 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4711                            LookupResult &Previous, bool &Redeclaration) {
4712   // Merge the decl with the existing one if appropriate. If the decl is
4713   // in an outer scope, it isn't the same thing.
4714   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
4715                        /*AllowInlineNamespace*/false);
4716   filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4717   if (!Previous.empty()) {
4718     Redeclaration = true;
4719     MergeTypedefNameDecl(NewTD, Previous);
4720   }
4721 
4722   // If this is the C FILE type, notify the AST context.
4723   if (IdentifierInfo *II = NewTD->getIdentifier())
4724     if (!NewTD->isInvalidDecl() &&
4725         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4726       if (II->isStr("FILE"))
4727         Context.setFILEDecl(NewTD);
4728       else if (II->isStr("jmp_buf"))
4729         Context.setjmp_bufDecl(NewTD);
4730       else if (II->isStr("sigjmp_buf"))
4731         Context.setsigjmp_bufDecl(NewTD);
4732       else if (II->isStr("ucontext_t"))
4733         Context.setucontext_tDecl(NewTD);
4734     }
4735 
4736   return NewTD;
4737 }
4738 
4739 /// \brief Determines whether the given declaration is an out-of-scope
4740 /// previous declaration.
4741 ///
4742 /// This routine should be invoked when name lookup has found a
4743 /// previous declaration (PrevDecl) that is not in the scope where a
4744 /// new declaration by the same name is being introduced. If the new
4745 /// declaration occurs in a local scope, previous declarations with
4746 /// linkage may still be considered previous declarations (C99
4747 /// 6.2.2p4-5, C++ [basic.link]p6).
4748 ///
4749 /// \param PrevDecl the previous declaration found by name
4750 /// lookup
4751 ///
4752 /// \param DC the context in which the new declaration is being
4753 /// declared.
4754 ///
4755 /// \returns true if PrevDecl is an out-of-scope previous declaration
4756 /// for a new delcaration with the same name.
4757 static bool
4758 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4759                                 ASTContext &Context) {
4760   if (!PrevDecl)
4761     return false;
4762 
4763   if (!PrevDecl->hasLinkage())
4764     return false;
4765 
4766   if (Context.getLangOpts().CPlusPlus) {
4767     // C++ [basic.link]p6:
4768     //   If there is a visible declaration of an entity with linkage
4769     //   having the same name and type, ignoring entities declared
4770     //   outside the innermost enclosing namespace scope, the block
4771     //   scope declaration declares that same entity and receives the
4772     //   linkage of the previous declaration.
4773     DeclContext *OuterContext = DC->getRedeclContext();
4774     if (!OuterContext->isFunctionOrMethod())
4775       // This rule only applies to block-scope declarations.
4776       return false;
4777 
4778     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4779     if (PrevOuterContext->isRecord())
4780       // We found a member function: ignore it.
4781       return false;
4782 
4783     // Find the innermost enclosing namespace for the new and
4784     // previous declarations.
4785     OuterContext = OuterContext->getEnclosingNamespaceContext();
4786     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4787 
4788     // The previous declaration is in a different namespace, so it
4789     // isn't the same function.
4790     if (!OuterContext->Equals(PrevOuterContext))
4791       return false;
4792   }
4793 
4794   return true;
4795 }
4796 
4797 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4798   CXXScopeSpec &SS = D.getCXXScopeSpec();
4799   if (!SS.isSet()) return;
4800   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4801 }
4802 
4803 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4804   QualType type = decl->getType();
4805   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4806   if (lifetime == Qualifiers::OCL_Autoreleasing) {
4807     // Various kinds of declaration aren't allowed to be __autoreleasing.
4808     unsigned kind = -1U;
4809     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4810       if (var->hasAttr<BlocksAttr>())
4811         kind = 0; // __block
4812       else if (!var->hasLocalStorage())
4813         kind = 1; // global
4814     } else if (isa<ObjCIvarDecl>(decl)) {
4815       kind = 3; // ivar
4816     } else if (isa<FieldDecl>(decl)) {
4817       kind = 2; // field
4818     }
4819 
4820     if (kind != -1U) {
4821       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4822         << kind;
4823     }
4824   } else if (lifetime == Qualifiers::OCL_None) {
4825     // Try to infer lifetime.
4826     if (!type->isObjCLifetimeType())
4827       return false;
4828 
4829     lifetime = type->getObjCARCImplicitLifetime();
4830     type = Context.getLifetimeQualifiedType(type, lifetime);
4831     decl->setType(type);
4832   }
4833 
4834   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4835     // Thread-local variables cannot have lifetime.
4836     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4837         var->getTLSKind()) {
4838       Diag(var->getLocation(), diag::err_arc_thread_ownership)
4839         << var->getType();
4840       return true;
4841     }
4842   }
4843 
4844   return false;
4845 }
4846 
4847 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4848   // 'weak' only applies to declarations with external linkage.
4849   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4850     if (!ND.isExternallyVisible()) {
4851       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4852       ND.dropAttr<WeakAttr>();
4853     }
4854   }
4855   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4856     if (ND.isExternallyVisible()) {
4857       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4858       ND.dropAttr<WeakRefAttr>();
4859     }
4860   }
4861 
4862   // 'selectany' only applies to externally visible varable declarations.
4863   // It does not apply to functions.
4864   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4865     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4866       S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4867       ND.dropAttr<SelectAnyAttr>();
4868     }
4869   }
4870 }
4871 
4872 /// Given that we are within the definition of the given function,
4873 /// will that definition behave like C99's 'inline', where the
4874 /// definition is discarded except for optimization purposes?
4875 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4876   // Try to avoid calling GetGVALinkageForFunction.
4877 
4878   // All cases of this require the 'inline' keyword.
4879   if (!FD->isInlined()) return false;
4880 
4881   // This is only possible in C++ with the gnu_inline attribute.
4882   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4883     return false;
4884 
4885   // Okay, go ahead and call the relatively-more-expensive function.
4886 
4887 #ifndef NDEBUG
4888   // AST quite reasonably asserts that it's working on a function
4889   // definition.  We don't really have a way to tell it that we're
4890   // currently defining the function, so just lie to it in +Asserts
4891   // builds.  This is an awful hack.
4892   FD->setLazyBody(1);
4893 #endif
4894 
4895   bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4896 
4897 #ifndef NDEBUG
4898   FD->setLazyBody(0);
4899 #endif
4900 
4901   return isC99Inline;
4902 }
4903 
4904 /// Determine whether a variable is extern "C" prior to attaching
4905 /// an initializer. We can't just call isExternC() here, because that
4906 /// will also compute and cache whether the declaration is externally
4907 /// visible, which might change when we attach the initializer.
4908 ///
4909 /// This can only be used if the declaration is known to not be a
4910 /// redeclaration of an internal linkage declaration.
4911 ///
4912 /// For instance:
4913 ///
4914 ///   auto x = []{};
4915 ///
4916 /// Attaching the initializer here makes this declaration not externally
4917 /// visible, because its type has internal linkage.
4918 ///
4919 /// FIXME: This is a hack.
4920 template<typename T>
4921 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4922   if (S.getLangOpts().CPlusPlus) {
4923     // In C++, the overloadable attribute negates the effects of extern "C".
4924     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4925       return false;
4926   }
4927   return D->isExternC();
4928 }
4929 
4930 static bool shouldConsiderLinkage(const VarDecl *VD) {
4931   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4932   if (DC->isFunctionOrMethod())
4933     return VD->hasExternalStorage();
4934   if (DC->isFileContext())
4935     return true;
4936   if (DC->isRecord())
4937     return false;
4938   llvm_unreachable("Unexpected context");
4939 }
4940 
4941 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4942   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4943   if (DC->isFileContext() || DC->isFunctionOrMethod())
4944     return true;
4945   if (DC->isRecord())
4946     return false;
4947   llvm_unreachable("Unexpected context");
4948 }
4949 
4950 /// Adjust the \c DeclContext for a function or variable that might be a
4951 /// function-local external declaration.
4952 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4953   if (!DC->isFunctionOrMethod())
4954     return false;
4955 
4956   // If this is a local extern function or variable declared within a function
4957   // template, don't add it into the enclosing namespace scope until it is
4958   // instantiated; it might have a dependent type right now.
4959   if (DC->isDependentContext())
4960     return true;
4961 
4962   // C++11 [basic.link]p7:
4963   //   When a block scope declaration of an entity with linkage is not found to
4964   //   refer to some other declaration, then that entity is a member of the
4965   //   innermost enclosing namespace.
4966   //
4967   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4968   // semantically-enclosing namespace, not a lexically-enclosing one.
4969   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4970     DC = DC->getParent();
4971   return true;
4972 }
4973 
4974 NamedDecl *
4975 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4976                               TypeSourceInfo *TInfo, LookupResult &Previous,
4977                               MultiTemplateParamsArg TemplateParamLists,
4978                               bool &AddToScope) {
4979   QualType R = TInfo->getType();
4980   DeclarationName Name = GetNameForDeclarator(D).getName();
4981 
4982   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4983   VarDecl::StorageClass SC =
4984     StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
4985 
4986   DeclContext *OriginalDC = DC;
4987   bool IsLocalExternDecl = SC == SC_Extern &&
4988                            adjustContextForLocalExternDecl(DC);
4989 
4990   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
4991     // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4992     // half array type (unless the cl_khr_fp16 extension is enabled).
4993     if (Context.getBaseElementType(R)->isHalfType()) {
4994       Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4995       D.setInvalidType();
4996     }
4997   }
4998 
4999   if (SCSpec == DeclSpec::SCS_mutable) {
5000     // mutable can only appear on non-static class members, so it's always
5001     // an error here
5002     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5003     D.setInvalidType();
5004     SC = SC_None;
5005   }
5006 
5007   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5008       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5009                               D.getDeclSpec().getStorageClassSpecLoc())) {
5010     // In C++11, the 'register' storage class specifier is deprecated.
5011     // Suppress the warning in system macros, it's used in macros in some
5012     // popular C system headers, such as in glibc's htonl() macro.
5013     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5014          diag::warn_deprecated_register)
5015       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5016   }
5017 
5018   IdentifierInfo *II = Name.getAsIdentifierInfo();
5019   if (!II) {
5020     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5021       << Name;
5022     return 0;
5023   }
5024 
5025   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5026 
5027   if (!DC->isRecord() && S->getFnParent() == 0) {
5028     // C99 6.9p2: The storage-class specifiers auto and register shall not
5029     // appear in the declaration specifiers in an external declaration.
5030     if (SC == SC_Auto || SC == SC_Register) {
5031       // If this is a register variable with an asm label specified, then this
5032       // is a GNU extension.
5033       if (SC == SC_Register && D.getAsmLabel())
5034         Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
5035       else
5036         Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5037       D.setInvalidType();
5038     }
5039   }
5040 
5041   if (getLangOpts().OpenCL) {
5042     // Set up the special work-group-local storage class for variables in the
5043     // OpenCL __local address space.
5044     if (R.getAddressSpace() == LangAS::opencl_local) {
5045       SC = SC_OpenCLWorkGroupLocal;
5046     }
5047 
5048     // OpenCL v1.2 s6.9.b p4:
5049     // The sampler type cannot be used with the __local and __global address
5050     // space qualifiers.
5051     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5052       R.getAddressSpace() == LangAS::opencl_global)) {
5053       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5054     }
5055 
5056     // OpenCL 1.2 spec, p6.9 r:
5057     // The event type cannot be used to declare a program scope variable.
5058     // The event type cannot be used with the __local, __constant and __global
5059     // address space qualifiers.
5060     if (R->isEventT()) {
5061       if (S->getParent() == 0) {
5062         Diag(D.getLocStart(), diag::err_event_t_global_var);
5063         D.setInvalidType();
5064       }
5065 
5066       if (R.getAddressSpace()) {
5067         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5068         D.setInvalidType();
5069       }
5070     }
5071   }
5072 
5073   bool IsExplicitSpecialization = false;
5074   bool IsVariableTemplateSpecialization = false;
5075   bool IsPartialSpecialization = false;
5076   bool IsVariableTemplate = false;
5077   VarDecl *NewVD = 0;
5078   VarTemplateDecl *NewTemplate = 0;
5079   TemplateParameterList *TemplateParams = 0;
5080   if (!getLangOpts().CPlusPlus) {
5081     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5082                             D.getIdentifierLoc(), II,
5083                             R, TInfo, SC);
5084 
5085     if (D.isInvalidType())
5086       NewVD->setInvalidDecl();
5087   } else {
5088     bool Invalid = false;
5089 
5090     if (DC->isRecord() && !CurContext->isRecord()) {
5091       // This is an out-of-line definition of a static data member.
5092       switch (SC) {
5093       case SC_None:
5094         break;
5095       case SC_Static:
5096         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5097              diag::err_static_out_of_line)
5098           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5099         break;
5100       case SC_Auto:
5101       case SC_Register:
5102       case SC_Extern:
5103         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5104         // to names of variables declared in a block or to function parameters.
5105         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5106         // of class members
5107 
5108         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5109              diag::err_storage_class_for_static_member)
5110           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5111         break;
5112       case SC_PrivateExtern:
5113         llvm_unreachable("C storage class in c++!");
5114       case SC_OpenCLWorkGroupLocal:
5115         llvm_unreachable("OpenCL storage class in c++!");
5116       }
5117     }
5118 
5119     if (SC == SC_Static && CurContext->isRecord()) {
5120       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5121         if (RD->isLocalClass())
5122           Diag(D.getIdentifierLoc(),
5123                diag::err_static_data_member_not_allowed_in_local_class)
5124             << Name << RD->getDeclName();
5125 
5126         // C++98 [class.union]p1: If a union contains a static data member,
5127         // the program is ill-formed. C++11 drops this restriction.
5128         if (RD->isUnion())
5129           Diag(D.getIdentifierLoc(),
5130                getLangOpts().CPlusPlus11
5131                  ? diag::warn_cxx98_compat_static_data_member_in_union
5132                  : diag::ext_static_data_member_in_union) << Name;
5133         // We conservatively disallow static data members in anonymous structs.
5134         else if (!RD->getDeclName())
5135           Diag(D.getIdentifierLoc(),
5136                diag::err_static_data_member_not_allowed_in_anon_struct)
5137             << Name << RD->isUnion();
5138       }
5139     }
5140 
5141     // Match up the template parameter lists with the scope specifier, then
5142     // determine whether we have a template or a template specialization.
5143     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5144         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5145         D.getCXXScopeSpec(), TemplateParamLists,
5146         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5147 
5148     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
5149         !TemplateParams) {
5150       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5151 
5152       // We have encountered something that the user meant to be a
5153       // specialization (because it has explicitly-specified template
5154       // arguments) but that was not introduced with a "template<>" (or had
5155       // too few of them).
5156       // FIXME: Differentiate between attempts for explicit instantiations
5157       // (starting with "template") and the rest.
5158       Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5159           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5160           << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5161                                         "template<> ");
5162       IsVariableTemplateSpecialization = true;
5163       TemplateParams = TemplateParameterList::Create(Context, SourceLocation(),
5164                                                      SourceLocation(), 0, 0,
5165                                                      SourceLocation());
5166     }
5167 
5168     if (TemplateParams) {
5169       if (!TemplateParams->size() &&
5170           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5171         // There is an extraneous 'template<>' for this variable. Complain
5172         // about it, but allow the declaration of the variable.
5173         Diag(TemplateParams->getTemplateLoc(),
5174              diag::err_template_variable_noparams)
5175           << II
5176           << SourceRange(TemplateParams->getTemplateLoc(),
5177                          TemplateParams->getRAngleLoc());
5178         TemplateParams = 0;
5179       } else {
5180         // Only C++1y supports variable templates (N3651).
5181         Diag(D.getIdentifierLoc(),
5182              getLangOpts().CPlusPlus1y
5183                  ? diag::warn_cxx11_compat_variable_template
5184                  : diag::ext_variable_template);
5185 
5186         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5187           // This is an explicit specialization or a partial specialization.
5188           // FIXME: Check that we can declare a specialization here.
5189           IsVariableTemplateSpecialization = true;
5190           IsPartialSpecialization = TemplateParams->size() > 0;
5191         } else { // if (TemplateParams->size() > 0)
5192           // This is a template declaration.
5193           IsVariableTemplate = true;
5194 
5195           // Check that we can declare a template here.
5196           if (CheckTemplateDeclScope(S, TemplateParams))
5197             return 0;
5198         }
5199       }
5200     }
5201 
5202     if (IsVariableTemplateSpecialization) {
5203       SourceLocation TemplateKWLoc =
5204           TemplateParamLists.size() > 0
5205               ? TemplateParamLists[0]->getTemplateLoc()
5206               : SourceLocation();
5207       DeclResult Res = ActOnVarTemplateSpecialization(
5208           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5209           IsPartialSpecialization);
5210       if (Res.isInvalid())
5211         return 0;
5212       NewVD = cast<VarDecl>(Res.get());
5213       AddToScope = false;
5214     } else
5215       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5216                               D.getIdentifierLoc(), II, R, TInfo, SC);
5217 
5218     // If this is supposed to be a variable template, create it as such.
5219     if (IsVariableTemplate) {
5220       NewTemplate =
5221           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5222                                   TemplateParams, NewVD);
5223       NewVD->setDescribedVarTemplate(NewTemplate);
5224     }
5225 
5226     // If this decl has an auto type in need of deduction, make a note of the
5227     // Decl so we can diagnose uses of it in its own initializer.
5228     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5229       ParsingInitForAutoVars.insert(NewVD);
5230 
5231     if (D.isInvalidType() || Invalid) {
5232       NewVD->setInvalidDecl();
5233       if (NewTemplate)
5234         NewTemplate->setInvalidDecl();
5235     }
5236 
5237     SetNestedNameSpecifier(NewVD, D);
5238 
5239     // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5240     if (TemplateParams && TemplateParamLists.size() > 1 &&
5241         (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5242       NewVD->setTemplateParameterListsInfo(
5243           Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5244     } else if (IsVariableTemplateSpecialization ||
5245                (!TemplateParams && TemplateParamLists.size() > 0 &&
5246                 (D.getCXXScopeSpec().isSet()))) {
5247       NewVD->setTemplateParameterListsInfo(Context,
5248                                            TemplateParamLists.size(),
5249                                            TemplateParamLists.data());
5250     }
5251 
5252     if (D.getDeclSpec().isConstexprSpecified())
5253       NewVD->setConstexpr(true);
5254   }
5255 
5256   // Set the lexical context. If the declarator has a C++ scope specifier, the
5257   // lexical context will be different from the semantic context.
5258   NewVD->setLexicalDeclContext(CurContext);
5259   if (NewTemplate)
5260     NewTemplate->setLexicalDeclContext(CurContext);
5261 
5262   if (IsLocalExternDecl)
5263     NewVD->setLocalExternDecl();
5264 
5265   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5266     if (NewVD->hasLocalStorage()) {
5267       // C++11 [dcl.stc]p4:
5268       //   When thread_local is applied to a variable of block scope the
5269       //   storage-class-specifier static is implied if it does not appear
5270       //   explicitly.
5271       // Core issue: 'static' is not implied if the variable is declared
5272       //   'extern'.
5273       if (SCSpec == DeclSpec::SCS_unspecified &&
5274           TSCS == DeclSpec::TSCS_thread_local &&
5275           DC->isFunctionOrMethod())
5276         NewVD->setTSCSpec(TSCS);
5277       else
5278         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5279              diag::err_thread_non_global)
5280           << DeclSpec::getSpecifierName(TSCS);
5281     } else if (!Context.getTargetInfo().isTLSSupported())
5282       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5283            diag::err_thread_unsupported);
5284     else
5285       NewVD->setTSCSpec(TSCS);
5286   }
5287 
5288   // C99 6.7.4p3
5289   //   An inline definition of a function with external linkage shall
5290   //   not contain a definition of a modifiable object with static or
5291   //   thread storage duration...
5292   // We only apply this when the function is required to be defined
5293   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5294   // that a local variable with thread storage duration still has to
5295   // be marked 'static'.  Also note that it's possible to get these
5296   // semantics in C++ using __attribute__((gnu_inline)).
5297   if (SC == SC_Static && S->getFnParent() != 0 &&
5298       !NewVD->getType().isConstQualified()) {
5299     FunctionDecl *CurFD = getCurFunctionDecl();
5300     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5301       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5302            diag::warn_static_local_in_extern_inline);
5303       MaybeSuggestAddingStaticToDecl(CurFD);
5304     }
5305   }
5306 
5307   if (D.getDeclSpec().isModulePrivateSpecified()) {
5308     if (IsVariableTemplateSpecialization)
5309       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5310           << (IsPartialSpecialization ? 1 : 0)
5311           << FixItHint::CreateRemoval(
5312                  D.getDeclSpec().getModulePrivateSpecLoc());
5313     else if (IsExplicitSpecialization)
5314       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5315         << 2
5316         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5317     else if (NewVD->hasLocalStorage())
5318       Diag(NewVD->getLocation(), diag::err_module_private_local)
5319         << 0 << NewVD->getDeclName()
5320         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5321         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5322     else {
5323       NewVD->setModulePrivate();
5324       if (NewTemplate)
5325         NewTemplate->setModulePrivate();
5326     }
5327   }
5328 
5329   // Handle attributes prior to checking for duplicates in MergeVarDecl
5330   ProcessDeclAttributes(S, NewVD, D);
5331 
5332   if (NewVD->hasAttrs())
5333     CheckAlignasUnderalignment(NewVD);
5334 
5335   if (getLangOpts().CUDA) {
5336     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5337     // storage [duration]."
5338     if (SC == SC_None && S->getFnParent() != 0 &&
5339         (NewVD->hasAttr<CUDASharedAttr>() ||
5340          NewVD->hasAttr<CUDAConstantAttr>())) {
5341       NewVD->setStorageClass(SC_Static);
5342     }
5343   }
5344 
5345   // In auto-retain/release, infer strong retension for variables of
5346   // retainable type.
5347   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5348     NewVD->setInvalidDecl();
5349 
5350   // Handle GNU asm-label extension (encoded as an attribute).
5351   if (Expr *E = (Expr*)D.getAsmLabel()) {
5352     // The parser guarantees this is a string.
5353     StringLiteral *SE = cast<StringLiteral>(E);
5354     StringRef Label = SE->getString();
5355     if (S->getFnParent() != 0) {
5356       switch (SC) {
5357       case SC_None:
5358       case SC_Auto:
5359         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5360         break;
5361       case SC_Register:
5362         if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5363           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5364         break;
5365       case SC_Static:
5366       case SC_Extern:
5367       case SC_PrivateExtern:
5368       case SC_OpenCLWorkGroupLocal:
5369         break;
5370       }
5371     }
5372 
5373     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5374                                                 Context, Label, 0));
5375   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5376     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5377       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5378     if (I != ExtnameUndeclaredIdentifiers.end()) {
5379       NewVD->addAttr(I->second);
5380       ExtnameUndeclaredIdentifiers.erase(I);
5381     }
5382   }
5383 
5384   // Diagnose shadowed variables before filtering for scope.
5385   if (D.getCXXScopeSpec().isEmpty())
5386     CheckShadow(S, NewVD, Previous);
5387 
5388   // Don't consider existing declarations that are in a different
5389   // scope and are out-of-semantic-context declarations (if the new
5390   // declaration has linkage).
5391   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5392                        D.getCXXScopeSpec().isNotEmpty() ||
5393                        IsExplicitSpecialization ||
5394                        IsVariableTemplateSpecialization);
5395 
5396   // Check whether the previous declaration is in the same block scope. This
5397   // affects whether we merge types with it, per C++11 [dcl.array]p3.
5398   if (getLangOpts().CPlusPlus &&
5399       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5400     NewVD->setPreviousDeclInSameBlockScope(
5401         Previous.isSingleResult() && !Previous.isShadowed() &&
5402         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5403 
5404   if (!getLangOpts().CPlusPlus) {
5405     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5406   } else {
5407     // If this is an explicit specialization of a static data member, check it.
5408     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5409         CheckMemberSpecialization(NewVD, Previous))
5410       NewVD->setInvalidDecl();
5411 
5412     // Merge the decl with the existing one if appropriate.
5413     if (!Previous.empty()) {
5414       if (Previous.isSingleResult() &&
5415           isa<FieldDecl>(Previous.getFoundDecl()) &&
5416           D.getCXXScopeSpec().isSet()) {
5417         // The user tried to define a non-static data member
5418         // out-of-line (C++ [dcl.meaning]p1).
5419         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5420           << D.getCXXScopeSpec().getRange();
5421         Previous.clear();
5422         NewVD->setInvalidDecl();
5423       }
5424     } else if (D.getCXXScopeSpec().isSet()) {
5425       // No previous declaration in the qualifying scope.
5426       Diag(D.getIdentifierLoc(), diag::err_no_member)
5427         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5428         << D.getCXXScopeSpec().getRange();
5429       NewVD->setInvalidDecl();
5430     }
5431 
5432     if (!IsVariableTemplateSpecialization)
5433       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5434 
5435     if (NewTemplate) {
5436       VarTemplateDecl *PrevVarTemplate =
5437           NewVD->getPreviousDecl()
5438               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
5439               : 0;
5440 
5441       // Check the template parameter list of this declaration, possibly
5442       // merging in the template parameter list from the previous variable
5443       // template declaration.
5444       if (CheckTemplateParameterList(
5445               TemplateParams,
5446               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5447                               : 0,
5448               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5449                DC->isDependentContext())
5450                   ? TPC_ClassTemplateMember
5451                   : TPC_VarTemplate))
5452         NewVD->setInvalidDecl();
5453 
5454       // If we are providing an explicit specialization of a static variable
5455       // template, make a note of that.
5456       if (PrevVarTemplate &&
5457           PrevVarTemplate->getInstantiatedFromMemberTemplate())
5458         PrevVarTemplate->setMemberSpecialization();
5459     }
5460   }
5461 
5462   ProcessPragmaWeak(S, NewVD);
5463   checkAttributesAfterMerging(*this, *NewVD);
5464 
5465   // If this is the first declaration of an extern C variable, update
5466   // the map of such variables.
5467   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5468       isIncompleteDeclExternC(*this, NewVD))
5469     RegisterLocallyScopedExternCDecl(NewVD, S);
5470 
5471   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5472     Decl *ManglingContextDecl;
5473     if (MangleNumberingContext *MCtx =
5474             getCurrentMangleNumberContext(NewVD->getDeclContext(),
5475                                           ManglingContextDecl)) {
5476       Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5477     }
5478   }
5479 
5480   if (NewTemplate) {
5481     if (NewVD->isInvalidDecl())
5482       NewTemplate->setInvalidDecl();
5483     ActOnDocumentableDecl(NewTemplate);
5484     return NewTemplate;
5485   }
5486 
5487   return NewVD;
5488 }
5489 
5490 /// \brief Diagnose variable or built-in function shadowing.  Implements
5491 /// -Wshadow.
5492 ///
5493 /// This method is called whenever a VarDecl is added to a "useful"
5494 /// scope.
5495 ///
5496 /// \param S the scope in which the shadowing name is being declared
5497 /// \param R the lookup of the name
5498 ///
5499 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5500   // Return if warning is ignored.
5501   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
5502         DiagnosticsEngine::Ignored)
5503     return;
5504 
5505   // Don't diagnose declarations at file scope.
5506   if (D->hasGlobalStorage())
5507     return;
5508 
5509   DeclContext *NewDC = D->getDeclContext();
5510 
5511   // Only diagnose if we're shadowing an unambiguous field or variable.
5512   if (R.getResultKind() != LookupResult::Found)
5513     return;
5514 
5515   NamedDecl* ShadowedDecl = R.getFoundDecl();
5516   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5517     return;
5518 
5519   // Fields are not shadowed by variables in C++ static methods.
5520   if (isa<FieldDecl>(ShadowedDecl))
5521     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5522       if (MD->isStatic())
5523         return;
5524 
5525   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5526     if (shadowedVar->isExternC()) {
5527       // For shadowing external vars, make sure that we point to the global
5528       // declaration, not a locally scoped extern declaration.
5529       for (VarDecl::redecl_iterator
5530              I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5531            I != E; ++I)
5532         if (I->isFileVarDecl()) {
5533           ShadowedDecl = *I;
5534           break;
5535         }
5536     }
5537 
5538   DeclContext *OldDC = ShadowedDecl->getDeclContext();
5539 
5540   // Only warn about certain kinds of shadowing for class members.
5541   if (NewDC && NewDC->isRecord()) {
5542     // In particular, don't warn about shadowing non-class members.
5543     if (!OldDC->isRecord())
5544       return;
5545 
5546     // TODO: should we warn about static data members shadowing
5547     // static data members from base classes?
5548 
5549     // TODO: don't diagnose for inaccessible shadowed members.
5550     // This is hard to do perfectly because we might friend the
5551     // shadowing context, but that's just a false negative.
5552   }
5553 
5554   // Determine what kind of declaration we're shadowing.
5555   unsigned Kind;
5556   if (isa<RecordDecl>(OldDC)) {
5557     if (isa<FieldDecl>(ShadowedDecl))
5558       Kind = 3; // field
5559     else
5560       Kind = 2; // static data member
5561   } else if (OldDC->isFileContext())
5562     Kind = 1; // global
5563   else
5564     Kind = 0; // local
5565 
5566   DeclarationName Name = R.getLookupName();
5567 
5568   // Emit warning and note.
5569   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
5570     return;
5571   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5572   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5573 }
5574 
5575 /// \brief Check -Wshadow without the advantage of a previous lookup.
5576 void Sema::CheckShadow(Scope *S, VarDecl *D) {
5577   if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5578         DiagnosticsEngine::Ignored)
5579     return;
5580 
5581   LookupResult R(*this, D->getDeclName(), D->getLocation(),
5582                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5583   LookupName(R, S);
5584   CheckShadow(S, D, R);
5585 }
5586 
5587 /// Check for conflict between this global or extern "C" declaration and
5588 /// previous global or extern "C" declarations. This is only used in C++.
5589 template<typename T>
5590 static bool checkGlobalOrExternCConflict(
5591     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5592   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5593   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5594 
5595   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5596     // The common case: this global doesn't conflict with any extern "C"
5597     // declaration.
5598     return false;
5599   }
5600 
5601   if (Prev) {
5602     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5603       // Both the old and new declarations have C language linkage. This is a
5604       // redeclaration.
5605       Previous.clear();
5606       Previous.addDecl(Prev);
5607       return true;
5608     }
5609 
5610     // This is a global, non-extern "C" declaration, and there is a previous
5611     // non-global extern "C" declaration. Diagnose if this is a variable
5612     // declaration.
5613     if (!isa<VarDecl>(ND))
5614       return false;
5615   } else {
5616     // The declaration is extern "C". Check for any declaration in the
5617     // translation unit which might conflict.
5618     if (IsGlobal) {
5619       // We have already performed the lookup into the translation unit.
5620       IsGlobal = false;
5621       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5622            I != E; ++I) {
5623         if (isa<VarDecl>(*I)) {
5624           Prev = *I;
5625           break;
5626         }
5627       }
5628     } else {
5629       DeclContext::lookup_result R =
5630           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5631       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5632            I != E; ++I) {
5633         if (isa<VarDecl>(*I)) {
5634           Prev = *I;
5635           break;
5636         }
5637         // FIXME: If we have any other entity with this name in global scope,
5638         // the declaration is ill-formed, but that is a defect: it breaks the
5639         // 'stat' hack, for instance. Only variables can have mangled name
5640         // clashes with extern "C" declarations, so only they deserve a
5641         // diagnostic.
5642       }
5643     }
5644 
5645     if (!Prev)
5646       return false;
5647   }
5648 
5649   // Use the first declaration's location to ensure we point at something which
5650   // is lexically inside an extern "C" linkage-spec.
5651   assert(Prev && "should have found a previous declaration to diagnose");
5652   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5653     Prev = FD->getFirstDecl();
5654   else
5655     Prev = cast<VarDecl>(Prev)->getFirstDecl();
5656 
5657   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5658     << IsGlobal << ND;
5659   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5660     << IsGlobal;
5661   return false;
5662 }
5663 
5664 /// Apply special rules for handling extern "C" declarations. Returns \c true
5665 /// if we have found that this is a redeclaration of some prior entity.
5666 ///
5667 /// Per C++ [dcl.link]p6:
5668 ///   Two declarations [for a function or variable] with C language linkage
5669 ///   with the same name that appear in different scopes refer to the same
5670 ///   [entity]. An entity with C language linkage shall not be declared with
5671 ///   the same name as an entity in global scope.
5672 template<typename T>
5673 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5674                                                   LookupResult &Previous) {
5675   if (!S.getLangOpts().CPlusPlus) {
5676     // In C, when declaring a global variable, look for a corresponding 'extern'
5677     // variable declared in function scope. We don't need this in C++, because
5678     // we find local extern decls in the surrounding file-scope DeclContext.
5679     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5680       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5681         Previous.clear();
5682         Previous.addDecl(Prev);
5683         return true;
5684       }
5685     }
5686     return false;
5687   }
5688 
5689   // A declaration in the translation unit can conflict with an extern "C"
5690   // declaration.
5691   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5692     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5693 
5694   // An extern "C" declaration can conflict with a declaration in the
5695   // translation unit or can be a redeclaration of an extern "C" declaration
5696   // in another scope.
5697   if (isIncompleteDeclExternC(S,ND))
5698     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5699 
5700   // Neither global nor extern "C": nothing to do.
5701   return false;
5702 }
5703 
5704 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5705   // If the decl is already known invalid, don't check it.
5706   if (NewVD->isInvalidDecl())
5707     return;
5708 
5709   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5710   QualType T = TInfo->getType();
5711 
5712   // Defer checking an 'auto' type until its initializer is attached.
5713   if (T->isUndeducedType())
5714     return;
5715 
5716   if (T->isObjCObjectType()) {
5717     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5718       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5719     T = Context.getObjCObjectPointerType(T);
5720     NewVD->setType(T);
5721   }
5722 
5723   // Emit an error if an address space was applied to decl with local storage.
5724   // This includes arrays of objects with address space qualifiers, but not
5725   // automatic variables that point to other address spaces.
5726   // ISO/IEC TR 18037 S5.1.2
5727   if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5728     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5729     NewVD->setInvalidDecl();
5730     return;
5731   }
5732 
5733   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5734   // __constant address space.
5735   if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5736       && T.getAddressSpace() != LangAS::opencl_constant
5737       && !T->isSamplerT()){
5738     Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5739     NewVD->setInvalidDecl();
5740     return;
5741   }
5742 
5743   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5744   // scope.
5745   if ((getLangOpts().OpenCLVersion >= 120)
5746       && NewVD->isStaticLocal()) {
5747     Diag(NewVD->getLocation(), diag::err_static_function_scope);
5748     NewVD->setInvalidDecl();
5749     return;
5750   }
5751 
5752   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5753       && !NewVD->hasAttr<BlocksAttr>()) {
5754     if (getLangOpts().getGC() != LangOptions::NonGC)
5755       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5756     else {
5757       assert(!getLangOpts().ObjCAutoRefCount);
5758       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5759     }
5760   }
5761 
5762   bool isVM = T->isVariablyModifiedType();
5763   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5764       NewVD->hasAttr<BlocksAttr>())
5765     getCurFunction()->setHasBranchProtectedScope();
5766 
5767   if ((isVM && NewVD->hasLinkage()) ||
5768       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5769     bool SizeIsNegative;
5770     llvm::APSInt Oversized;
5771     TypeSourceInfo *FixedTInfo =
5772       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5773                                                     SizeIsNegative, Oversized);
5774     if (FixedTInfo == 0 && T->isVariableArrayType()) {
5775       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5776       // FIXME: This won't give the correct result for
5777       // int a[10][n];
5778       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5779 
5780       if (NewVD->isFileVarDecl())
5781         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5782         << SizeRange;
5783       else if (NewVD->isStaticLocal())
5784         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5785         << SizeRange;
5786       else
5787         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5788         << SizeRange;
5789       NewVD->setInvalidDecl();
5790       return;
5791     }
5792 
5793     if (FixedTInfo == 0) {
5794       if (NewVD->isFileVarDecl())
5795         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5796       else
5797         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5798       NewVD->setInvalidDecl();
5799       return;
5800     }
5801 
5802     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5803     NewVD->setType(FixedTInfo->getType());
5804     NewVD->setTypeSourceInfo(FixedTInfo);
5805   }
5806 
5807   if (T->isVoidType()) {
5808     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5809     //                    of objects and functions.
5810     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5811       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5812         << T;
5813       NewVD->setInvalidDecl();
5814       return;
5815     }
5816   }
5817 
5818   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5819     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5820     NewVD->setInvalidDecl();
5821     return;
5822   }
5823 
5824   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5825     Diag(NewVD->getLocation(), diag::err_block_on_vm);
5826     NewVD->setInvalidDecl();
5827     return;
5828   }
5829 
5830   if (NewVD->isConstexpr() && !T->isDependentType() &&
5831       RequireLiteralType(NewVD->getLocation(), T,
5832                          diag::err_constexpr_var_non_literal)) {
5833     // Can't perform this check until the type is deduced.
5834     NewVD->setInvalidDecl();
5835     return;
5836   }
5837 }
5838 
5839 /// \brief Perform semantic checking on a newly-created variable
5840 /// declaration.
5841 ///
5842 /// This routine performs all of the type-checking required for a
5843 /// variable declaration once it has been built. It is used both to
5844 /// check variables after they have been parsed and their declarators
5845 /// have been translated into a declaration, and to check variables
5846 /// that have been instantiated from a template.
5847 ///
5848 /// Sets NewVD->isInvalidDecl() if an error was encountered.
5849 ///
5850 /// Returns true if the variable declaration is a redeclaration.
5851 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
5852   CheckVariableDeclarationType(NewVD);
5853 
5854   // If the decl is already known invalid, don't check it.
5855   if (NewVD->isInvalidDecl())
5856     return false;
5857 
5858   // If we did not find anything by this name, look for a non-visible
5859   // extern "C" declaration with the same name.
5860   if (Previous.empty() &&
5861       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
5862     Previous.setShadowed();
5863 
5864   // Filter out any non-conflicting previous declarations.
5865   filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5866 
5867   if (!Previous.empty()) {
5868     MergeVarDecl(NewVD, Previous);
5869     return true;
5870   }
5871   return false;
5872 }
5873 
5874 /// \brief Data used with FindOverriddenMethod
5875 struct FindOverriddenMethodData {
5876   Sema *S;
5877   CXXMethodDecl *Method;
5878 };
5879 
5880 /// \brief Member lookup function that determines whether a given C++
5881 /// method overrides a method in a base class, to be used with
5882 /// CXXRecordDecl::lookupInBases().
5883 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5884                                  CXXBasePath &Path,
5885                                  void *UserData) {
5886   RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5887 
5888   FindOverriddenMethodData *Data
5889     = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5890 
5891   DeclarationName Name = Data->Method->getDeclName();
5892 
5893   // FIXME: Do we care about other names here too?
5894   if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5895     // We really want to find the base class destructor here.
5896     QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5897     CanQualType CT = Data->S->Context.getCanonicalType(T);
5898 
5899     Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5900   }
5901 
5902   for (Path.Decls = BaseRecord->lookup(Name);
5903        !Path.Decls.empty();
5904        Path.Decls = Path.Decls.slice(1)) {
5905     NamedDecl *D = Path.Decls.front();
5906     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5907       if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
5908         return true;
5909     }
5910   }
5911 
5912   return false;
5913 }
5914 
5915 namespace {
5916   enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5917 }
5918 /// \brief Report an error regarding overriding, along with any relevant
5919 /// overriden methods.
5920 ///
5921 /// \param DiagID the primary error to report.
5922 /// \param MD the overriding method.
5923 /// \param OEK which overrides to include as notes.
5924 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5925                             OverrideErrorKind OEK = OEK_All) {
5926   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5927   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5928                                       E = MD->end_overridden_methods();
5929        I != E; ++I) {
5930     // This check (& the OEK parameter) could be replaced by a predicate, but
5931     // without lambdas that would be overkill. This is still nicer than writing
5932     // out the diag loop 3 times.
5933     if ((OEK == OEK_All) ||
5934         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5935         (OEK == OEK_Deleted && (*I)->isDeleted()))
5936       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5937   }
5938 }
5939 
5940 /// AddOverriddenMethods - See if a method overrides any in the base classes,
5941 /// and if so, check that it's a valid override and remember it.
5942 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5943   // Look for virtual methods in base classes that this method might override.
5944   CXXBasePaths Paths;
5945   FindOverriddenMethodData Data;
5946   Data.Method = MD;
5947   Data.S = this;
5948   bool hasDeletedOverridenMethods = false;
5949   bool hasNonDeletedOverridenMethods = false;
5950   bool AddedAny = false;
5951   if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5952     for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5953          E = Paths.found_decls_end(); I != E; ++I) {
5954       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
5955         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
5956         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
5957             !CheckOverridingFunctionAttributes(MD, OldMD) &&
5958             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
5959             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
5960           hasDeletedOverridenMethods |= OldMD->isDeleted();
5961           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
5962           AddedAny = true;
5963         }
5964       }
5965     }
5966   }
5967 
5968   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5969     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5970   }
5971   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5972     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5973   }
5974 
5975   return AddedAny;
5976 }
5977 
5978 namespace {
5979   // Struct for holding all of the extra arguments needed by
5980   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5981   struct ActOnFDArgs {
5982     Scope *S;
5983     Declarator &D;
5984     MultiTemplateParamsArg TemplateParamLists;
5985     bool AddToScope;
5986   };
5987 }
5988 
5989 namespace {
5990 
5991 // Callback to only accept typo corrections that have a non-zero edit distance.
5992 // Also only accept corrections that have the same parent decl.
5993 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5994  public:
5995   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5996                             CXXRecordDecl *Parent)
5997       : Context(Context), OriginalFD(TypoFD),
5998         ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
5999 
6000   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
6001     if (candidate.getEditDistance() == 0)
6002       return false;
6003 
6004     SmallVector<unsigned, 1> MismatchedParams;
6005     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6006                                           CDeclEnd = candidate.end();
6007          CDecl != CDeclEnd; ++CDecl) {
6008       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6009 
6010       if (FD && !FD->hasBody() &&
6011           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6012         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6013           CXXRecordDecl *Parent = MD->getParent();
6014           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6015             return true;
6016         } else if (!ExpectedParent) {
6017           return true;
6018         }
6019       }
6020     }
6021 
6022     return false;
6023   }
6024 
6025  private:
6026   ASTContext &Context;
6027   FunctionDecl *OriginalFD;
6028   CXXRecordDecl *ExpectedParent;
6029 };
6030 
6031 }
6032 
6033 /// \brief Generate diagnostics for an invalid function redeclaration.
6034 ///
6035 /// This routine handles generating the diagnostic messages for an invalid
6036 /// function redeclaration, including finding possible similar declarations
6037 /// or performing typo correction if there are no previous declarations with
6038 /// the same name.
6039 ///
6040 /// Returns a NamedDecl iff typo correction was performed and substituting in
6041 /// the new declaration name does not cause new errors.
6042 static NamedDecl *DiagnoseInvalidRedeclaration(
6043     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6044     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6045   DeclarationName Name = NewFD->getDeclName();
6046   DeclContext *NewDC = NewFD->getDeclContext();
6047   SmallVector<unsigned, 1> MismatchedParams;
6048   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6049   TypoCorrection Correction;
6050   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6051   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6052                                    : diag::err_member_decl_does_not_match;
6053   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6054                     IsLocalFriend ? Sema::LookupLocalFriendName
6055                                   : Sema::LookupOrdinaryName,
6056                     Sema::ForRedeclaration);
6057 
6058   NewFD->setInvalidDecl();
6059   if (IsLocalFriend)
6060     SemaRef.LookupName(Prev, S);
6061   else
6062     SemaRef.LookupQualifiedName(Prev, NewDC);
6063   assert(!Prev.isAmbiguous() &&
6064          "Cannot have an ambiguity in previous-declaration lookup");
6065   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6066   DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6067                                       MD ? MD->getParent() : 0);
6068   if (!Prev.empty()) {
6069     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6070          Func != FuncEnd; ++Func) {
6071       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6072       if (FD &&
6073           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6074         // Add 1 to the index so that 0 can mean the mismatch didn't
6075         // involve a parameter
6076         unsigned ParamNum =
6077             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6078         NearMatches.push_back(std::make_pair(FD, ParamNum));
6079       }
6080     }
6081   // If the qualified name lookup yielded nothing, try typo correction
6082   } else if ((Correction = SemaRef.CorrectTypo(
6083                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6084                  &ExtraArgs.D.getCXXScopeSpec(), Validator,
6085                  IsLocalFriend ? 0 : NewDC))) {
6086     // Set up everything for the call to ActOnFunctionDeclarator
6087     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6088                               ExtraArgs.D.getIdentifierLoc());
6089     Previous.clear();
6090     Previous.setLookupName(Correction.getCorrection());
6091     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6092                                     CDeclEnd = Correction.end();
6093          CDecl != CDeclEnd; ++CDecl) {
6094       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6095       if (FD && !FD->hasBody() &&
6096           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6097         Previous.addDecl(FD);
6098       }
6099     }
6100     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6101 
6102     NamedDecl *Result;
6103     // Retry building the function declaration with the new previous
6104     // declarations, and with errors suppressed.
6105     {
6106       // Trap errors.
6107       Sema::SFINAETrap Trap(SemaRef);
6108 
6109       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6110       // pieces need to verify the typo-corrected C++ declaration and hopefully
6111       // eliminate the need for the parameter pack ExtraArgs.
6112       Result = SemaRef.ActOnFunctionDeclarator(
6113           ExtraArgs.S, ExtraArgs.D,
6114           Correction.getCorrectionDecl()->getDeclContext(),
6115           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6116           ExtraArgs.AddToScope);
6117 
6118       if (Trap.hasErrorOccurred())
6119         Result = 0;
6120     }
6121 
6122     if (Result) {
6123       // Determine which correction we picked.
6124       Decl *Canonical = Result->getCanonicalDecl();
6125       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6126            I != E; ++I)
6127         if ((*I)->getCanonicalDecl() == Canonical)
6128           Correction.setCorrectionDecl(*I);
6129 
6130       SemaRef.diagnoseTypo(
6131           Correction,
6132           SemaRef.PDiag(IsLocalFriend
6133                           ? diag::err_no_matching_local_friend_suggest
6134                           : diag::err_member_decl_does_not_match_suggest)
6135             << Name << NewDC << IsDefinition);
6136       return Result;
6137     }
6138 
6139     // Pretend the typo correction never occurred
6140     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6141                               ExtraArgs.D.getIdentifierLoc());
6142     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6143     Previous.clear();
6144     Previous.setLookupName(Name);
6145   }
6146 
6147   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6148       << Name << NewDC << IsDefinition << NewFD->getLocation();
6149 
6150   bool NewFDisConst = false;
6151   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6152     NewFDisConst = NewMD->isConst();
6153 
6154   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6155        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6156        NearMatch != NearMatchEnd; ++NearMatch) {
6157     FunctionDecl *FD = NearMatch->first;
6158     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6159     bool FDisConst = MD && MD->isConst();
6160     bool IsMember = MD || !IsLocalFriend;
6161 
6162     // FIXME: These notes are poorly worded for the local friend case.
6163     if (unsigned Idx = NearMatch->second) {
6164       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6165       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6166       if (Loc.isInvalid()) Loc = FD->getLocation();
6167       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6168                                  : diag::note_local_decl_close_param_match)
6169         << Idx << FDParam->getType()
6170         << NewFD->getParamDecl(Idx - 1)->getType();
6171     } else if (FDisConst != NewFDisConst) {
6172       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6173           << NewFDisConst << FD->getSourceRange().getEnd();
6174     } else
6175       SemaRef.Diag(FD->getLocation(),
6176                    IsMember ? diag::note_member_def_close_match
6177                             : diag::note_local_decl_close_match);
6178   }
6179   return 0;
6180 }
6181 
6182 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6183                                                           Declarator &D) {
6184   switch (D.getDeclSpec().getStorageClassSpec()) {
6185   default: llvm_unreachable("Unknown storage class!");
6186   case DeclSpec::SCS_auto:
6187   case DeclSpec::SCS_register:
6188   case DeclSpec::SCS_mutable:
6189     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6190                  diag::err_typecheck_sclass_func);
6191     D.setInvalidType();
6192     break;
6193   case DeclSpec::SCS_unspecified: break;
6194   case DeclSpec::SCS_extern:
6195     if (D.getDeclSpec().isExternInLinkageSpec())
6196       return SC_None;
6197     return SC_Extern;
6198   case DeclSpec::SCS_static: {
6199     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6200       // C99 6.7.1p5:
6201       //   The declaration of an identifier for a function that has
6202       //   block scope shall have no explicit storage-class specifier
6203       //   other than extern
6204       // See also (C++ [dcl.stc]p4).
6205       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6206                    diag::err_static_block_func);
6207       break;
6208     } else
6209       return SC_Static;
6210   }
6211   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6212   }
6213 
6214   // No explicit storage class has already been returned
6215   return SC_None;
6216 }
6217 
6218 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6219                                            DeclContext *DC, QualType &R,
6220                                            TypeSourceInfo *TInfo,
6221                                            FunctionDecl::StorageClass SC,
6222                                            bool &IsVirtualOkay) {
6223   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6224   DeclarationName Name = NameInfo.getName();
6225 
6226   FunctionDecl *NewFD = 0;
6227   bool isInline = D.getDeclSpec().isInlineSpecified();
6228 
6229   if (!SemaRef.getLangOpts().CPlusPlus) {
6230     // Determine whether the function was written with a
6231     // prototype. This true when:
6232     //   - there is a prototype in the declarator, or
6233     //   - the type R of the function is some kind of typedef or other reference
6234     //     to a type name (which eventually refers to a function type).
6235     bool HasPrototype =
6236       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6237       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6238 
6239     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6240                                  D.getLocStart(), NameInfo, R,
6241                                  TInfo, SC, isInline,
6242                                  HasPrototype, false);
6243     if (D.isInvalidType())
6244       NewFD->setInvalidDecl();
6245 
6246     // Set the lexical context.
6247     NewFD->setLexicalDeclContext(SemaRef.CurContext);
6248 
6249     return NewFD;
6250   }
6251 
6252   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6253   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6254 
6255   // Check that the return type is not an abstract class type.
6256   // For record types, this is done by the AbstractClassUsageDiagnoser once
6257   // the class has been completely parsed.
6258   if (!DC->isRecord() &&
6259       SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6260                                      R->getAs<FunctionType>()->getResultType(),
6261                                      diag::err_abstract_type_in_decl,
6262                                      SemaRef.AbstractReturnType))
6263     D.setInvalidType();
6264 
6265   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6266     // This is a C++ constructor declaration.
6267     assert(DC->isRecord() &&
6268            "Constructors can only be declared in a member context");
6269 
6270     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6271     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6272                                       D.getLocStart(), NameInfo,
6273                                       R, TInfo, isExplicit, isInline,
6274                                       /*isImplicitlyDeclared=*/false,
6275                                       isConstexpr);
6276 
6277   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6278     // This is a C++ destructor declaration.
6279     if (DC->isRecord()) {
6280       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6281       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6282       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6283                                         SemaRef.Context, Record,
6284                                         D.getLocStart(),
6285                                         NameInfo, R, TInfo, isInline,
6286                                         /*isImplicitlyDeclared=*/false);
6287 
6288       // If the class is complete, then we now create the implicit exception
6289       // specification. If the class is incomplete or dependent, we can't do
6290       // it yet.
6291       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6292           Record->getDefinition() && !Record->isBeingDefined() &&
6293           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6294         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6295       }
6296 
6297       // The Microsoft ABI requires that we perform the destructor body
6298       // checks (i.e. operator delete() lookup) at every declaration, as
6299       // any translation unit may need to emit a deleting destructor.
6300       if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6301           !Record->isDependentType() && Record->getDefinition() &&
6302           !Record->isBeingDefined() && !NewDD->isDeleted()) {
6303         SemaRef.CheckDestructor(NewDD);
6304       }
6305 
6306       IsVirtualOkay = true;
6307       return NewDD;
6308 
6309     } else {
6310       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6311       D.setInvalidType();
6312 
6313       // Create a FunctionDecl to satisfy the function definition parsing
6314       // code path.
6315       return FunctionDecl::Create(SemaRef.Context, DC,
6316                                   D.getLocStart(),
6317                                   D.getIdentifierLoc(), Name, R, TInfo,
6318                                   SC, isInline,
6319                                   /*hasPrototype=*/true, isConstexpr);
6320     }
6321 
6322   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6323     if (!DC->isRecord()) {
6324       SemaRef.Diag(D.getIdentifierLoc(),
6325            diag::err_conv_function_not_member);
6326       return 0;
6327     }
6328 
6329     SemaRef.CheckConversionDeclarator(D, R, SC);
6330     IsVirtualOkay = true;
6331     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6332                                      D.getLocStart(), NameInfo,
6333                                      R, TInfo, isInline, isExplicit,
6334                                      isConstexpr, SourceLocation());
6335 
6336   } else if (DC->isRecord()) {
6337     // If the name of the function is the same as the name of the record,
6338     // then this must be an invalid constructor that has a return type.
6339     // (The parser checks for a return type and makes the declarator a
6340     // constructor if it has no return type).
6341     if (Name.getAsIdentifierInfo() &&
6342         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6343       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6344         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6345         << SourceRange(D.getIdentifierLoc());
6346       return 0;
6347     }
6348 
6349     // This is a C++ method declaration.
6350     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6351                                                cast<CXXRecordDecl>(DC),
6352                                                D.getLocStart(), NameInfo, R,
6353                                                TInfo, SC, isInline,
6354                                                isConstexpr, SourceLocation());
6355     IsVirtualOkay = !Ret->isStatic();
6356     return Ret;
6357   } else {
6358     // Determine whether the function was written with a
6359     // prototype. This true when:
6360     //   - we're in C++ (where every function has a prototype),
6361     return FunctionDecl::Create(SemaRef.Context, DC,
6362                                 D.getLocStart(),
6363                                 NameInfo, R, TInfo, SC, isInline,
6364                                 true/*HasPrototype*/, isConstexpr);
6365   }
6366 }
6367 
6368 void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6369   // In C++, the empty parameter-type-list must be spelled "void"; a
6370   // typedef of void is not permitted.
6371   if (getLangOpts().CPlusPlus &&
6372       Param->getType().getUnqualifiedType() != Context.VoidTy) {
6373     bool IsTypeAlias = false;
6374     if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6375       IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6376     else if (const TemplateSpecializationType *TST =
6377                Param->getType()->getAs<TemplateSpecializationType>())
6378       IsTypeAlias = TST->isTypeAlias();
6379     Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6380       << IsTypeAlias;
6381   }
6382 }
6383 
6384 enum OpenCLParamType {
6385   ValidKernelParam,
6386   PtrPtrKernelParam,
6387   PtrKernelParam,
6388   InvalidKernelParam,
6389   RecordKernelParam
6390 };
6391 
6392 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6393   if (PT->isPointerType()) {
6394     QualType PointeeType = PT->getPointeeType();
6395     return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6396   }
6397 
6398   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6399   // be used as builtin types.
6400 
6401   if (PT->isImageType())
6402     return PtrKernelParam;
6403 
6404   if (PT->isBooleanType())
6405     return InvalidKernelParam;
6406 
6407   if (PT->isEventT())
6408     return InvalidKernelParam;
6409 
6410   if (PT->isHalfType())
6411     return InvalidKernelParam;
6412 
6413   if (PT->isRecordType())
6414     return RecordKernelParam;
6415 
6416   return ValidKernelParam;
6417 }
6418 
6419 static void checkIsValidOpenCLKernelParameter(
6420   Sema &S,
6421   Declarator &D,
6422   ParmVarDecl *Param,
6423   llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6424   QualType PT = Param->getType();
6425 
6426   // Cache the valid types we encounter to avoid rechecking structs that are
6427   // used again
6428   if (ValidTypes.count(PT.getTypePtr()))
6429     return;
6430 
6431   switch (getOpenCLKernelParameterType(PT)) {
6432   case PtrPtrKernelParam:
6433     // OpenCL v1.2 s6.9.a:
6434     // A kernel function argument cannot be declared as a
6435     // pointer to a pointer type.
6436     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6437     D.setInvalidType();
6438     return;
6439 
6440     // OpenCL v1.2 s6.9.k:
6441     // Arguments to kernel functions in a program cannot be declared with the
6442     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6443     // uintptr_t or a struct and/or union that contain fields declared to be
6444     // one of these built-in scalar types.
6445 
6446   case InvalidKernelParam:
6447     // OpenCL v1.2 s6.8 n:
6448     // A kernel function argument cannot be declared
6449     // of event_t type.
6450     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6451     D.setInvalidType();
6452     return;
6453 
6454   case PtrKernelParam:
6455   case ValidKernelParam:
6456     ValidTypes.insert(PT.getTypePtr());
6457     return;
6458 
6459   case RecordKernelParam:
6460     break;
6461   }
6462 
6463   // Track nested structs we will inspect
6464   SmallVector<const Decl *, 4> VisitStack;
6465 
6466   // Track where we are in the nested structs. Items will migrate from
6467   // VisitStack to HistoryStack as we do the DFS for bad field.
6468   SmallVector<const FieldDecl *, 4> HistoryStack;
6469   HistoryStack.push_back((const FieldDecl *) 0);
6470 
6471   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6472   VisitStack.push_back(PD);
6473 
6474   assert(VisitStack.back() && "First decl null?");
6475 
6476   do {
6477     const Decl *Next = VisitStack.pop_back_val();
6478     if (!Next) {
6479       assert(!HistoryStack.empty());
6480       // Found a marker, we have gone up a level
6481       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6482         ValidTypes.insert(Hist->getType().getTypePtr());
6483 
6484       continue;
6485     }
6486 
6487     // Adds everything except the original parameter declaration (which is not a
6488     // field itself) to the history stack.
6489     const RecordDecl *RD;
6490     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6491       HistoryStack.push_back(Field);
6492       RD = Field->getType()->castAs<RecordType>()->getDecl();
6493     } else {
6494       RD = cast<RecordDecl>(Next);
6495     }
6496 
6497     // Add a null marker so we know when we've gone back up a level
6498     VisitStack.push_back((const Decl *) 0);
6499 
6500     for (RecordDecl::field_iterator I = RD->field_begin(),
6501            E = RD->field_end(); I != E; ++I) {
6502       const FieldDecl *FD = *I;
6503       QualType QT = FD->getType();
6504 
6505       if (ValidTypes.count(QT.getTypePtr()))
6506         continue;
6507 
6508       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6509       if (ParamType == ValidKernelParam)
6510         continue;
6511 
6512       if (ParamType == RecordKernelParam) {
6513         VisitStack.push_back(FD);
6514         continue;
6515       }
6516 
6517       // OpenCL v1.2 s6.9.p:
6518       // Arguments to kernel functions that are declared to be a struct or union
6519       // do not allow OpenCL objects to be passed as elements of the struct or
6520       // union.
6521       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6522         S.Diag(Param->getLocation(),
6523                diag::err_record_with_pointers_kernel_param)
6524           << PT->isUnionType()
6525           << PT;
6526       } else {
6527         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6528       }
6529 
6530       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6531         << PD->getDeclName();
6532 
6533       // We have an error, now let's go back up through history and show where
6534       // the offending field came from
6535       for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6536              E = HistoryStack.end(); I != E; ++I) {
6537         const FieldDecl *OuterField = *I;
6538         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6539           << OuterField->getType();
6540       }
6541 
6542       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6543         << QT->isPointerType()
6544         << QT;
6545       D.setInvalidType();
6546       return;
6547     }
6548   } while (!VisitStack.empty());
6549 }
6550 
6551 NamedDecl*
6552 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6553                               TypeSourceInfo *TInfo, LookupResult &Previous,
6554                               MultiTemplateParamsArg TemplateParamLists,
6555                               bool &AddToScope) {
6556   QualType R = TInfo->getType();
6557 
6558   assert(R.getTypePtr()->isFunctionType());
6559 
6560   // TODO: consider using NameInfo for diagnostic.
6561   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6562   DeclarationName Name = NameInfo.getName();
6563   FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6564 
6565   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6566     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6567          diag::err_invalid_thread)
6568       << DeclSpec::getSpecifierName(TSCS);
6569 
6570   if (D.isFirstDeclarationOfMember())
6571     adjustMemberFunctionCC(R, D.isStaticMember());
6572 
6573   bool isFriend = false;
6574   FunctionTemplateDecl *FunctionTemplate = 0;
6575   bool isExplicitSpecialization = false;
6576   bool isFunctionTemplateSpecialization = false;
6577 
6578   bool isDependentClassScopeExplicitSpecialization = false;
6579   bool HasExplicitTemplateArgs = false;
6580   TemplateArgumentListInfo TemplateArgs;
6581 
6582   bool isVirtualOkay = false;
6583 
6584   DeclContext *OriginalDC = DC;
6585   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6586 
6587   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6588                                               isVirtualOkay);
6589   if (!NewFD) return 0;
6590 
6591   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6592     NewFD->setTopLevelDeclInObjCContainer();
6593 
6594   // Set the lexical context. If this is a function-scope declaration, or has a
6595   // C++ scope specifier, or is the object of a friend declaration, the lexical
6596   // context will be different from the semantic context.
6597   NewFD->setLexicalDeclContext(CurContext);
6598 
6599   if (IsLocalExternDecl)
6600     NewFD->setLocalExternDecl();
6601 
6602   if (getLangOpts().CPlusPlus) {
6603     bool isInline = D.getDeclSpec().isInlineSpecified();
6604     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6605     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6606     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6607     isFriend = D.getDeclSpec().isFriendSpecified();
6608     if (isFriend && !isInline && D.isFunctionDefinition()) {
6609       // C++ [class.friend]p5
6610       //   A function can be defined in a friend declaration of a
6611       //   class . . . . Such a function is implicitly inline.
6612       NewFD->setImplicitlyInline();
6613     }
6614 
6615     // If this is a method defined in an __interface, and is not a constructor
6616     // or an overloaded operator, then set the pure flag (isVirtual will already
6617     // return true).
6618     if (const CXXRecordDecl *Parent =
6619           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6620       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6621         NewFD->setPure(true);
6622     }
6623 
6624     SetNestedNameSpecifier(NewFD, D);
6625     isExplicitSpecialization = false;
6626     isFunctionTemplateSpecialization = false;
6627     if (D.isInvalidType())
6628       NewFD->setInvalidDecl();
6629 
6630     // Match up the template parameter lists with the scope specifier, then
6631     // determine whether we have a template or a template specialization.
6632     bool Invalid = false;
6633     if (TemplateParameterList *TemplateParams =
6634             MatchTemplateParametersToScopeSpecifier(
6635                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6636                 D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6637                 isExplicitSpecialization, Invalid)) {
6638       if (TemplateParams->size() > 0) {
6639         // This is a function template
6640 
6641         // Check that we can declare a template here.
6642         if (CheckTemplateDeclScope(S, TemplateParams))
6643           return 0;
6644 
6645         // A destructor cannot be a template.
6646         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6647           Diag(NewFD->getLocation(), diag::err_destructor_template);
6648           return 0;
6649         }
6650 
6651         // If we're adding a template to a dependent context, we may need to
6652         // rebuilding some of the types used within the template parameter list,
6653         // now that we know what the current instantiation is.
6654         if (DC->isDependentContext()) {
6655           ContextRAII SavedContext(*this, DC);
6656           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6657             Invalid = true;
6658         }
6659 
6660 
6661         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6662                                                         NewFD->getLocation(),
6663                                                         Name, TemplateParams,
6664                                                         NewFD);
6665         FunctionTemplate->setLexicalDeclContext(CurContext);
6666         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6667 
6668         // For source fidelity, store the other template param lists.
6669         if (TemplateParamLists.size() > 1) {
6670           NewFD->setTemplateParameterListsInfo(Context,
6671                                                TemplateParamLists.size() - 1,
6672                                                TemplateParamLists.data());
6673         }
6674       } else {
6675         // This is a function template specialization.
6676         isFunctionTemplateSpecialization = true;
6677         // For source fidelity, store all the template param lists.
6678         NewFD->setTemplateParameterListsInfo(Context,
6679                                              TemplateParamLists.size(),
6680                                              TemplateParamLists.data());
6681 
6682         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6683         if (isFriend) {
6684           // We want to remove the "template<>", found here.
6685           SourceRange RemoveRange = TemplateParams->getSourceRange();
6686 
6687           // If we remove the template<> and the name is not a
6688           // template-id, we're actually silently creating a problem:
6689           // the friend declaration will refer to an untemplated decl,
6690           // and clearly the user wants a template specialization.  So
6691           // we need to insert '<>' after the name.
6692           SourceLocation InsertLoc;
6693           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6694             InsertLoc = D.getName().getSourceRange().getEnd();
6695             InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6696           }
6697 
6698           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6699             << Name << RemoveRange
6700             << FixItHint::CreateRemoval(RemoveRange)
6701             << FixItHint::CreateInsertion(InsertLoc, "<>");
6702         }
6703       }
6704     }
6705     else {
6706       // All template param lists were matched against the scope specifier:
6707       // this is NOT (an explicit specialization of) a template.
6708       if (TemplateParamLists.size() > 0)
6709         // For source fidelity, store all the template param lists.
6710         NewFD->setTemplateParameterListsInfo(Context,
6711                                              TemplateParamLists.size(),
6712                                              TemplateParamLists.data());
6713     }
6714 
6715     if (Invalid) {
6716       NewFD->setInvalidDecl();
6717       if (FunctionTemplate)
6718         FunctionTemplate->setInvalidDecl();
6719     }
6720 
6721     // C++ [dcl.fct.spec]p5:
6722     //   The virtual specifier shall only be used in declarations of
6723     //   nonstatic class member functions that appear within a
6724     //   member-specification of a class declaration; see 10.3.
6725     //
6726     if (isVirtual && !NewFD->isInvalidDecl()) {
6727       if (!isVirtualOkay) {
6728         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6729              diag::err_virtual_non_function);
6730       } else if (!CurContext->isRecord()) {
6731         // 'virtual' was specified outside of the class.
6732         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6733              diag::err_virtual_out_of_class)
6734           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6735       } else if (NewFD->getDescribedFunctionTemplate()) {
6736         // C++ [temp.mem]p3:
6737         //  A member function template shall not be virtual.
6738         Diag(D.getDeclSpec().getVirtualSpecLoc(),
6739              diag::err_virtual_member_function_template)
6740           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6741       } else {
6742         // Okay: Add virtual to the method.
6743         NewFD->setVirtualAsWritten(true);
6744       }
6745 
6746       if (getLangOpts().CPlusPlus1y &&
6747           NewFD->getResultType()->isUndeducedType())
6748         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6749     }
6750 
6751     if (getLangOpts().CPlusPlus1y &&
6752         (NewFD->isDependentContext() ||
6753          (isFriend && CurContext->isDependentContext())) &&
6754         NewFD->getResultType()->isUndeducedType()) {
6755       // If the function template is referenced directly (for instance, as a
6756       // member of the current instantiation), pretend it has a dependent type.
6757       // This is not really justified by the standard, but is the only sane
6758       // thing to do.
6759       // FIXME: For a friend function, we have not marked the function as being
6760       // a friend yet, so 'isDependentContext' on the FD doesn't work.
6761       const FunctionProtoType *FPT =
6762           NewFD->getType()->castAs<FunctionProtoType>();
6763       QualType Result = SubstAutoType(FPT->getResultType(),
6764                                        Context.DependentTy);
6765       NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6766                                              FPT->getExtProtoInfo()));
6767     }
6768 
6769     // C++ [dcl.fct.spec]p3:
6770     //  The inline specifier shall not appear on a block scope function
6771     //  declaration.
6772     if (isInline && !NewFD->isInvalidDecl()) {
6773       if (CurContext->isFunctionOrMethod()) {
6774         // 'inline' is not allowed on block scope function declaration.
6775         Diag(D.getDeclSpec().getInlineSpecLoc(),
6776              diag::err_inline_declaration_block_scope) << Name
6777           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6778       }
6779     }
6780 
6781     // C++ [dcl.fct.spec]p6:
6782     //  The explicit specifier shall be used only in the declaration of a
6783     //  constructor or conversion function within its class definition;
6784     //  see 12.3.1 and 12.3.2.
6785     if (isExplicit && !NewFD->isInvalidDecl()) {
6786       if (!CurContext->isRecord()) {
6787         // 'explicit' was specified outside of the class.
6788         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6789              diag::err_explicit_out_of_class)
6790           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6791       } else if (!isa<CXXConstructorDecl>(NewFD) &&
6792                  !isa<CXXConversionDecl>(NewFD)) {
6793         // 'explicit' was specified on a function that wasn't a constructor
6794         // or conversion function.
6795         Diag(D.getDeclSpec().getExplicitSpecLoc(),
6796              diag::err_explicit_non_ctor_or_conv_function)
6797           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6798       }
6799     }
6800 
6801     if (isConstexpr) {
6802       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6803       // are implicitly inline.
6804       NewFD->setImplicitlyInline();
6805 
6806       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6807       // be either constructors or to return a literal type. Therefore,
6808       // destructors cannot be declared constexpr.
6809       if (isa<CXXDestructorDecl>(NewFD))
6810         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6811     }
6812 
6813     // If __module_private__ was specified, mark the function accordingly.
6814     if (D.getDeclSpec().isModulePrivateSpecified()) {
6815       if (isFunctionTemplateSpecialization) {
6816         SourceLocation ModulePrivateLoc
6817           = D.getDeclSpec().getModulePrivateSpecLoc();
6818         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6819           << 0
6820           << FixItHint::CreateRemoval(ModulePrivateLoc);
6821       } else {
6822         NewFD->setModulePrivate();
6823         if (FunctionTemplate)
6824           FunctionTemplate->setModulePrivate();
6825       }
6826     }
6827 
6828     if (isFriend) {
6829       if (FunctionTemplate) {
6830         FunctionTemplate->setObjectOfFriendDecl();
6831         FunctionTemplate->setAccess(AS_public);
6832       }
6833       NewFD->setObjectOfFriendDecl();
6834       NewFD->setAccess(AS_public);
6835     }
6836 
6837     // If a function is defined as defaulted or deleted, mark it as such now.
6838     switch (D.getFunctionDefinitionKind()) {
6839       case FDK_Declaration:
6840       case FDK_Definition:
6841         break;
6842 
6843       case FDK_Defaulted:
6844         NewFD->setDefaulted();
6845         break;
6846 
6847       case FDK_Deleted:
6848         NewFD->setDeletedAsWritten();
6849         break;
6850     }
6851 
6852     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6853         D.isFunctionDefinition()) {
6854       // C++ [class.mfct]p2:
6855       //   A member function may be defined (8.4) in its class definition, in
6856       //   which case it is an inline member function (7.1.2)
6857       NewFD->setImplicitlyInline();
6858     }
6859 
6860     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6861         !CurContext->isRecord()) {
6862       // C++ [class.static]p1:
6863       //   A data or function member of a class may be declared static
6864       //   in a class definition, in which case it is a static member of
6865       //   the class.
6866 
6867       // Complain about the 'static' specifier if it's on an out-of-line
6868       // member function definition.
6869       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6870            diag::err_static_out_of_line)
6871         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6872     }
6873 
6874     // C++11 [except.spec]p15:
6875     //   A deallocation function with no exception-specification is treated
6876     //   as if it were specified with noexcept(true).
6877     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6878     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6879          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6880         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6881       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6882       EPI.ExceptionSpecType = EST_BasicNoexcept;
6883       NewFD->setType(Context.getFunctionType(FPT->getResultType(),
6884                                              FPT->getArgTypes(), EPI));
6885     }
6886   }
6887 
6888   // Filter out previous declarations that don't match the scope.
6889   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
6890                        D.getCXXScopeSpec().isNotEmpty() ||
6891                        isExplicitSpecialization ||
6892                        isFunctionTemplateSpecialization);
6893 
6894   // Handle GNU asm-label extension (encoded as an attribute).
6895   if (Expr *E = (Expr*) D.getAsmLabel()) {
6896     // The parser guarantees this is a string.
6897     StringLiteral *SE = cast<StringLiteral>(E);
6898     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6899                                                 SE->getString(), 0));
6900   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6901     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6902       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6903     if (I != ExtnameUndeclaredIdentifiers.end()) {
6904       NewFD->addAttr(I->second);
6905       ExtnameUndeclaredIdentifiers.erase(I);
6906     }
6907   }
6908 
6909   // Copy the parameter declarations from the declarator D to the function
6910   // declaration NewFD, if they are available.  First scavenge them into Params.
6911   SmallVector<ParmVarDecl*, 16> Params;
6912   if (D.isFunctionDeclarator()) {
6913     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6914 
6915     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6916     // function that takes no arguments, not a function that takes a
6917     // single void argument.
6918     // We let through "const void" here because Sema::GetTypeForDeclarator
6919     // already checks for that case.
6920     if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6921         FTI.ArgInfo[0].Param &&
6922         cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
6923       // Empty arg list, don't push any params.
6924       checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
6925     } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
6926       for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6927         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
6928         assert(Param->getDeclContext() != NewFD && "Was set before ?");
6929         Param->setDeclContext(NewFD);
6930         Params.push_back(Param);
6931 
6932         if (Param->isInvalidDecl())
6933           NewFD->setInvalidDecl();
6934       }
6935     }
6936 
6937   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
6938     // When we're declaring a function with a typedef, typeof, etc as in the
6939     // following example, we'll need to synthesize (unnamed)
6940     // parameters for use in the declaration.
6941     //
6942     // @code
6943     // typedef void fn(int);
6944     // fn f;
6945     // @endcode
6946 
6947     // Synthesize a parameter for each argument type.
6948     for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6949          AE = FT->arg_type_end(); AI != AE; ++AI) {
6950       ParmVarDecl *Param =
6951         BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
6952       Param->setScopeInfo(0, Params.size());
6953       Params.push_back(Param);
6954     }
6955   } else {
6956     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6957            "Should not need args for typedef of non-prototype fn");
6958   }
6959 
6960   // Finally, we know we have the right number of parameters, install them.
6961   NewFD->setParams(Params);
6962 
6963   // Find all anonymous symbols defined during the declaration of this function
6964   // and add to NewFD. This lets us track decls such 'enum Y' in:
6965   //
6966   //   void f(enum Y {AA} x) {}
6967   //
6968   // which would otherwise incorrectly end up in the translation unit scope.
6969   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6970   DeclsInPrototypeScope.clear();
6971 
6972   if (D.getDeclSpec().isNoreturnSpecified())
6973     NewFD->addAttr(
6974         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6975                                        Context, 0));
6976 
6977   // Functions returning a variably modified type violate C99 6.7.5.2p2
6978   // because all functions have linkage.
6979   if (!NewFD->isInvalidDecl() &&
6980       NewFD->getResultType()->isVariablyModifiedType()) {
6981     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6982     NewFD->setInvalidDecl();
6983   }
6984 
6985   // Handle attributes.
6986   ProcessDeclAttributes(S, NewFD, D);
6987 
6988   QualType RetType = NewFD->getResultType();
6989   const CXXRecordDecl *Ret = RetType->isRecordType() ?
6990       RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6991   if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6992       Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
6993     const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6994     // Attach the attribute to the new decl. Don't apply the attribute if it
6995     // returns an instance of the class (e.g. assignment operators).
6996     if (!MD || MD->getParent() != Ret) {
6997       NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context));
6998     }
6999   }
7000 
7001   if (getLangOpts().OpenCL) {
7002     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7003     // type declaration will generate a compilation error.
7004     unsigned AddressSpace = RetType.getAddressSpace();
7005     if (AddressSpace == LangAS::opencl_local ||
7006         AddressSpace == LangAS::opencl_global ||
7007         AddressSpace == LangAS::opencl_constant) {
7008       Diag(NewFD->getLocation(),
7009            diag::err_opencl_return_value_with_address_space);
7010       NewFD->setInvalidDecl();
7011     }
7012   }
7013 
7014   if (!getLangOpts().CPlusPlus) {
7015     // Perform semantic checking on the function declaration.
7016     bool isExplicitSpecialization=false;
7017     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7018       CheckMain(NewFD, D.getDeclSpec());
7019 
7020     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7021       CheckMSVCRTEntryPoint(NewFD);
7022 
7023     if (!NewFD->isInvalidDecl())
7024       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7025                                                   isExplicitSpecialization));
7026     else if (!Previous.empty())
7027       // Make graceful recovery from an invalid redeclaration.
7028       D.setRedeclaration(true);
7029     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7030             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7031            "previous declaration set still overloaded");
7032   } else {
7033     // C++11 [replacement.functions]p3:
7034     //  The program's definitions shall not be specified as inline.
7035     //
7036     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7037     //
7038     // Suppress the diagnostic if the function is __attribute__((used)), since
7039     // that forces an external definition to be emitted.
7040     if (D.getDeclSpec().isInlineSpecified() &&
7041         NewFD->isReplaceableGlobalAllocationFunction() &&
7042         !NewFD->hasAttr<UsedAttr>())
7043       Diag(D.getDeclSpec().getInlineSpecLoc(),
7044            diag::ext_operator_new_delete_declared_inline)
7045         << NewFD->getDeclName();
7046 
7047     // If the declarator is a template-id, translate the parser's template
7048     // argument list into our AST format.
7049     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7050       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7051       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7052       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7053       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7054                                          TemplateId->NumArgs);
7055       translateTemplateArguments(TemplateArgsPtr,
7056                                  TemplateArgs);
7057 
7058       HasExplicitTemplateArgs = true;
7059 
7060       if (NewFD->isInvalidDecl()) {
7061         HasExplicitTemplateArgs = false;
7062       } else if (FunctionTemplate) {
7063         // Function template with explicit template arguments.
7064         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7065           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7066 
7067         HasExplicitTemplateArgs = false;
7068       } else if (!isFunctionTemplateSpecialization &&
7069                  !D.getDeclSpec().isFriendSpecified()) {
7070         // We have encountered something that the user meant to be a
7071         // specialization (because it has explicitly-specified template
7072         // arguments) but that was not introduced with a "template<>" (or had
7073         // too few of them).
7074         // FIXME: Differentiate between attempts for explicit instantiations
7075         // (starting with "template") and the rest.
7076         Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7077           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7078           << FixItHint::CreateInsertion(
7079                                     D.getDeclSpec().getLocStart(),
7080                                         "template<> ");
7081         isFunctionTemplateSpecialization = true;
7082       } else {
7083         // "friend void foo<>(int);" is an implicit specialization decl.
7084         isFunctionTemplateSpecialization = true;
7085       }
7086     } else if (isFriend && isFunctionTemplateSpecialization) {
7087       // This combination is only possible in a recovery case;  the user
7088       // wrote something like:
7089       //   template <> friend void foo(int);
7090       // which we're recovering from as if the user had written:
7091       //   friend void foo<>(int);
7092       // Go ahead and fake up a template id.
7093       HasExplicitTemplateArgs = true;
7094         TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7095       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7096     }
7097 
7098     // If it's a friend (and only if it's a friend), it's possible
7099     // that either the specialized function type or the specialized
7100     // template is dependent, and therefore matching will fail.  In
7101     // this case, don't check the specialization yet.
7102     bool InstantiationDependent = false;
7103     if (isFunctionTemplateSpecialization && isFriend &&
7104         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7105          TemplateSpecializationType::anyDependentTemplateArguments(
7106             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7107             InstantiationDependent))) {
7108       assert(HasExplicitTemplateArgs &&
7109              "friend function specialization without template args");
7110       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7111                                                        Previous))
7112         NewFD->setInvalidDecl();
7113     } else if (isFunctionTemplateSpecialization) {
7114       if (CurContext->isDependentContext() && CurContext->isRecord()
7115           && !isFriend) {
7116         isDependentClassScopeExplicitSpecialization = true;
7117         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7118           diag::ext_function_specialization_in_class :
7119           diag::err_function_specialization_in_class)
7120           << NewFD->getDeclName();
7121       } else if (CheckFunctionTemplateSpecialization(NewFD,
7122                                   (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7123                                                      Previous))
7124         NewFD->setInvalidDecl();
7125 
7126       // C++ [dcl.stc]p1:
7127       //   A storage-class-specifier shall not be specified in an explicit
7128       //   specialization (14.7.3)
7129       FunctionTemplateSpecializationInfo *Info =
7130           NewFD->getTemplateSpecializationInfo();
7131       if (Info && SC != SC_None) {
7132         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7133           Diag(NewFD->getLocation(),
7134                diag::err_explicit_specialization_inconsistent_storage_class)
7135             << SC
7136             << FixItHint::CreateRemoval(
7137                                       D.getDeclSpec().getStorageClassSpecLoc());
7138 
7139         else
7140           Diag(NewFD->getLocation(),
7141                diag::ext_explicit_specialization_storage_class)
7142             << FixItHint::CreateRemoval(
7143                                       D.getDeclSpec().getStorageClassSpecLoc());
7144       }
7145 
7146     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7147       if (CheckMemberSpecialization(NewFD, Previous))
7148           NewFD->setInvalidDecl();
7149     }
7150 
7151     // Perform semantic checking on the function declaration.
7152     if (!isDependentClassScopeExplicitSpecialization) {
7153       if (!NewFD->isInvalidDecl() && NewFD->isMain())
7154         CheckMain(NewFD, D.getDeclSpec());
7155 
7156       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7157         CheckMSVCRTEntryPoint(NewFD);
7158 
7159       if (!NewFD->isInvalidDecl())
7160         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7161                                                     isExplicitSpecialization));
7162     }
7163 
7164     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7165             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7166            "previous declaration set still overloaded");
7167 
7168     NamedDecl *PrincipalDecl = (FunctionTemplate
7169                                 ? cast<NamedDecl>(FunctionTemplate)
7170                                 : NewFD);
7171 
7172     if (isFriend && D.isRedeclaration()) {
7173       AccessSpecifier Access = AS_public;
7174       if (!NewFD->isInvalidDecl())
7175         Access = NewFD->getPreviousDecl()->getAccess();
7176 
7177       NewFD->setAccess(Access);
7178       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7179     }
7180 
7181     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7182         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7183       PrincipalDecl->setNonMemberOperator();
7184 
7185     // If we have a function template, check the template parameter
7186     // list. This will check and merge default template arguments.
7187     if (FunctionTemplate) {
7188       FunctionTemplateDecl *PrevTemplate =
7189                                      FunctionTemplate->getPreviousDecl();
7190       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7191                        PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
7192                             D.getDeclSpec().isFriendSpecified()
7193                               ? (D.isFunctionDefinition()
7194                                    ? TPC_FriendFunctionTemplateDefinition
7195                                    : TPC_FriendFunctionTemplate)
7196                               : (D.getCXXScopeSpec().isSet() &&
7197                                  DC && DC->isRecord() &&
7198                                  DC->isDependentContext())
7199                                   ? TPC_ClassTemplateMember
7200                                   : TPC_FunctionTemplate);
7201     }
7202 
7203     if (NewFD->isInvalidDecl()) {
7204       // Ignore all the rest of this.
7205     } else if (!D.isRedeclaration()) {
7206       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7207                                        AddToScope };
7208       // Fake up an access specifier if it's supposed to be a class member.
7209       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7210         NewFD->setAccess(AS_public);
7211 
7212       // Qualified decls generally require a previous declaration.
7213       if (D.getCXXScopeSpec().isSet()) {
7214         // ...with the major exception of templated-scope or
7215         // dependent-scope friend declarations.
7216 
7217         // TODO: we currently also suppress this check in dependent
7218         // contexts because (1) the parameter depth will be off when
7219         // matching friend templates and (2) we might actually be
7220         // selecting a friend based on a dependent factor.  But there
7221         // are situations where these conditions don't apply and we
7222         // can actually do this check immediately.
7223         if (isFriend &&
7224             (TemplateParamLists.size() ||
7225              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7226              CurContext->isDependentContext())) {
7227           // ignore these
7228         } else {
7229           // The user tried to provide an out-of-line definition for a
7230           // function that is a member of a class or namespace, but there
7231           // was no such member function declared (C++ [class.mfct]p2,
7232           // C++ [namespace.memdef]p2). For example:
7233           //
7234           // class X {
7235           //   void f() const;
7236           // };
7237           //
7238           // void X::f() { } // ill-formed
7239           //
7240           // Complain about this problem, and attempt to suggest close
7241           // matches (e.g., those that differ only in cv-qualifiers and
7242           // whether the parameter types are references).
7243 
7244           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7245                   *this, Previous, NewFD, ExtraArgs, false, 0)) {
7246             AddToScope = ExtraArgs.AddToScope;
7247             return Result;
7248           }
7249         }
7250 
7251         // Unqualified local friend declarations are required to resolve
7252         // to something.
7253       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7254         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7255                 *this, Previous, NewFD, ExtraArgs, true, S)) {
7256           AddToScope = ExtraArgs.AddToScope;
7257           return Result;
7258         }
7259       }
7260 
7261     } else if (!D.isFunctionDefinition() &&
7262                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
7263                !isFriend && !isFunctionTemplateSpecialization &&
7264                !isExplicitSpecialization) {
7265       // An out-of-line member function declaration must also be a
7266       // definition (C++ [class.mfct]p2).
7267       // Note that this is not the case for explicit specializations of
7268       // function templates or member functions of class templates, per
7269       // C++ [temp.expl.spec]p2. We also allow these declarations as an
7270       // extension for compatibility with old SWIG code which likes to
7271       // generate them.
7272       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7273         << D.getCXXScopeSpec().getRange();
7274     }
7275   }
7276 
7277   ProcessPragmaWeak(S, NewFD);
7278   checkAttributesAfterMerging(*this, *NewFD);
7279 
7280   AddKnownFunctionAttributes(NewFD);
7281 
7282   if (NewFD->hasAttr<OverloadableAttr>() &&
7283       !NewFD->getType()->getAs<FunctionProtoType>()) {
7284     Diag(NewFD->getLocation(),
7285          diag::err_attribute_overloadable_no_prototype)
7286       << NewFD;
7287 
7288     // Turn this into a variadic function with no parameters.
7289     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7290     FunctionProtoType::ExtProtoInfo EPI(
7291         Context.getDefaultCallingConvention(true, false));
7292     EPI.Variadic = true;
7293     EPI.ExtInfo = FT->getExtInfo();
7294 
7295     QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
7296     NewFD->setType(R);
7297   }
7298 
7299   // If there's a #pragma GCC visibility in scope, and this isn't a class
7300   // member, set the visibility of this function.
7301   if (!DC->isRecord() && NewFD->isExternallyVisible())
7302     AddPushedVisibilityAttribute(NewFD);
7303 
7304   // If there's a #pragma clang arc_cf_code_audited in scope, consider
7305   // marking the function.
7306   AddCFAuditedAttribute(NewFD);
7307 
7308   // If this is the first declaration of an extern C variable, update
7309   // the map of such variables.
7310   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7311       isIncompleteDeclExternC(*this, NewFD))
7312     RegisterLocallyScopedExternCDecl(NewFD, S);
7313 
7314   // Set this FunctionDecl's range up to the right paren.
7315   NewFD->setRangeEnd(D.getSourceRange().getEnd());
7316 
7317   if (getLangOpts().CPlusPlus) {
7318     if (FunctionTemplate) {
7319       if (NewFD->isInvalidDecl())
7320         FunctionTemplate->setInvalidDecl();
7321       return FunctionTemplate;
7322     }
7323   }
7324 
7325   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7326     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7327     if ((getLangOpts().OpenCLVersion >= 120)
7328         && (SC == SC_Static)) {
7329       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7330       D.setInvalidType();
7331     }
7332 
7333     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7334     if (!NewFD->getResultType()->isVoidType()) {
7335       Diag(D.getIdentifierLoc(),
7336            diag::err_expected_kernel_void_return_type);
7337       D.setInvalidType();
7338     }
7339 
7340     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7341     for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7342          PE = NewFD->param_end(); PI != PE; ++PI) {
7343       ParmVarDecl *Param = *PI;
7344       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7345     }
7346   }
7347 
7348   MarkUnusedFileScopedDecl(NewFD);
7349 
7350   if (getLangOpts().CUDA)
7351     if (IdentifierInfo *II = NewFD->getIdentifier())
7352       if (!NewFD->isInvalidDecl() &&
7353           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7354         if (II->isStr("cudaConfigureCall")) {
7355           if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7356             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7357 
7358           Context.setcudaConfigureCallDecl(NewFD);
7359         }
7360       }
7361 
7362   // Here we have an function template explicit specialization at class scope.
7363   // The actually specialization will be postponed to template instatiation
7364   // time via the ClassScopeFunctionSpecializationDecl node.
7365   if (isDependentClassScopeExplicitSpecialization) {
7366     ClassScopeFunctionSpecializationDecl *NewSpec =
7367                          ClassScopeFunctionSpecializationDecl::Create(
7368                                 Context, CurContext, SourceLocation(),
7369                                 cast<CXXMethodDecl>(NewFD),
7370                                 HasExplicitTemplateArgs, TemplateArgs);
7371     CurContext->addDecl(NewSpec);
7372     AddToScope = false;
7373   }
7374 
7375   return NewFD;
7376 }
7377 
7378 /// \brief Perform semantic checking of a new function declaration.
7379 ///
7380 /// Performs semantic analysis of the new function declaration
7381 /// NewFD. This routine performs all semantic checking that does not
7382 /// require the actual declarator involved in the declaration, and is
7383 /// used both for the declaration of functions as they are parsed
7384 /// (called via ActOnDeclarator) and for the declaration of functions
7385 /// that have been instantiated via C++ template instantiation (called
7386 /// via InstantiateDecl).
7387 ///
7388 /// \param IsExplicitSpecialization whether this new function declaration is
7389 /// an explicit specialization of the previous declaration.
7390 ///
7391 /// This sets NewFD->isInvalidDecl() to true if there was an error.
7392 ///
7393 /// \returns true if the function declaration is a redeclaration.
7394 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7395                                     LookupResult &Previous,
7396                                     bool IsExplicitSpecialization) {
7397   assert(!NewFD->getResultType()->isVariablyModifiedType()
7398          && "Variably modified return types are not handled here");
7399 
7400   // Determine whether the type of this function should be merged with
7401   // a previous visible declaration. This never happens for functions in C++,
7402   // and always happens in C if the previous declaration was visible.
7403   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7404                                !Previous.isShadowed();
7405 
7406   // Filter out any non-conflicting previous declarations.
7407   filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7408 
7409   bool Redeclaration = false;
7410   NamedDecl *OldDecl = 0;
7411 
7412   // Merge or overload the declaration with an existing declaration of
7413   // the same name, if appropriate.
7414   if (!Previous.empty()) {
7415     // Determine whether NewFD is an overload of PrevDecl or
7416     // a declaration that requires merging. If it's an overload,
7417     // there's no more work to do here; we'll just add the new
7418     // function to the scope.
7419     if (!AllowOverloadingOfFunction(Previous, Context)) {
7420       NamedDecl *Candidate = Previous.getFoundDecl();
7421       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7422         Redeclaration = true;
7423         OldDecl = Candidate;
7424       }
7425     } else {
7426       switch (CheckOverload(S, NewFD, Previous, OldDecl,
7427                             /*NewIsUsingDecl*/ false)) {
7428       case Ovl_Match:
7429         Redeclaration = true;
7430         break;
7431 
7432       case Ovl_NonFunction:
7433         Redeclaration = true;
7434         break;
7435 
7436       case Ovl_Overload:
7437         Redeclaration = false;
7438         break;
7439       }
7440 
7441       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7442         // If a function name is overloadable in C, then every function
7443         // with that name must be marked "overloadable".
7444         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7445           << Redeclaration << NewFD;
7446         NamedDecl *OverloadedDecl = 0;
7447         if (Redeclaration)
7448           OverloadedDecl = OldDecl;
7449         else if (!Previous.empty())
7450           OverloadedDecl = Previous.getRepresentativeDecl();
7451         if (OverloadedDecl)
7452           Diag(OverloadedDecl->getLocation(),
7453                diag::note_attribute_overloadable_prev_overload);
7454         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7455       }
7456     }
7457   }
7458 
7459   // Check for a previous extern "C" declaration with this name.
7460   if (!Redeclaration &&
7461       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7462     filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7463     if (!Previous.empty()) {
7464       // This is an extern "C" declaration with the same name as a previous
7465       // declaration, and thus redeclares that entity...
7466       Redeclaration = true;
7467       OldDecl = Previous.getFoundDecl();
7468       MergeTypeWithPrevious = false;
7469 
7470       // ... except in the presence of __attribute__((overloadable)).
7471       if (OldDecl->hasAttr<OverloadableAttr>()) {
7472         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7473           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7474             << Redeclaration << NewFD;
7475           Diag(Previous.getFoundDecl()->getLocation(),
7476                diag::note_attribute_overloadable_prev_overload);
7477           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
7478         }
7479         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7480           Redeclaration = false;
7481           OldDecl = 0;
7482         }
7483       }
7484     }
7485   }
7486 
7487   // C++11 [dcl.constexpr]p8:
7488   //   A constexpr specifier for a non-static member function that is not
7489   //   a constructor declares that member function to be const.
7490   //
7491   // This needs to be delayed until we know whether this is an out-of-line
7492   // definition of a static member function.
7493   //
7494   // This rule is not present in C++1y, so we produce a backwards
7495   // compatibility warning whenever it happens in C++11.
7496   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7497   if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7498       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7499       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7500     CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7501     if (FunctionTemplateDecl *OldTD =
7502           dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7503       OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7504     if (!OldMD || !OldMD->isStatic()) {
7505       const FunctionProtoType *FPT =
7506         MD->getType()->castAs<FunctionProtoType>();
7507       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7508       EPI.TypeQuals |= Qualifiers::Const;
7509       MD->setType(Context.getFunctionType(FPT->getResultType(),
7510                                           FPT->getArgTypes(), EPI));
7511 
7512       // Warn that we did this, if we're not performing template instantiation.
7513       // In that case, we'll have warned already when the template was defined.
7514       if (ActiveTemplateInstantiations.empty()) {
7515         SourceLocation AddConstLoc;
7516         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7517                 .IgnoreParens().getAs<FunctionTypeLoc>())
7518           AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7519 
7520         Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7521           << FixItHint::CreateInsertion(AddConstLoc, " const");
7522       }
7523     }
7524   }
7525 
7526   if (Redeclaration) {
7527     // NewFD and OldDecl represent declarations that need to be
7528     // merged.
7529     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7530       NewFD->setInvalidDecl();
7531       return Redeclaration;
7532     }
7533 
7534     Previous.clear();
7535     Previous.addDecl(OldDecl);
7536 
7537     if (FunctionTemplateDecl *OldTemplateDecl
7538                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7539       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7540       FunctionTemplateDecl *NewTemplateDecl
7541         = NewFD->getDescribedFunctionTemplate();
7542       assert(NewTemplateDecl && "Template/non-template mismatch");
7543       if (CXXMethodDecl *Method
7544             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7545         Method->setAccess(OldTemplateDecl->getAccess());
7546         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7547       }
7548 
7549       // If this is an explicit specialization of a member that is a function
7550       // template, mark it as a member specialization.
7551       if (IsExplicitSpecialization &&
7552           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7553         NewTemplateDecl->setMemberSpecialization();
7554         assert(OldTemplateDecl->isMemberSpecialization());
7555       }
7556 
7557     } else {
7558       // This needs to happen first so that 'inline' propagates.
7559       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7560 
7561       if (isa<CXXMethodDecl>(NewFD)) {
7562         // A valid redeclaration of a C++ method must be out-of-line,
7563         // but (unfortunately) it's not necessarily a definition
7564         // because of templates, which means that the previous
7565         // declaration is not necessarily from the class definition.
7566 
7567         // For just setting the access, that doesn't matter.
7568         CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7569         NewFD->setAccess(oldMethod->getAccess());
7570 
7571         // Update the key-function state if necessary for this ABI.
7572         if (NewFD->isInlined() &&
7573             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7574           // setNonKeyFunction needs to work with the original
7575           // declaration from the class definition, and isVirtual() is
7576           // just faster in that case, so map back to that now.
7577           oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7578           if (oldMethod->isVirtual()) {
7579             Context.setNonKeyFunction(oldMethod);
7580           }
7581         }
7582       }
7583     }
7584   }
7585 
7586   // Semantic checking for this function declaration (in isolation).
7587   if (getLangOpts().CPlusPlus) {
7588     // C++-specific checks.
7589     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7590       CheckConstructor(Constructor);
7591     } else if (CXXDestructorDecl *Destructor =
7592                 dyn_cast<CXXDestructorDecl>(NewFD)) {
7593       CXXRecordDecl *Record = Destructor->getParent();
7594       QualType ClassType = Context.getTypeDeclType(Record);
7595 
7596       // FIXME: Shouldn't we be able to perform this check even when the class
7597       // type is dependent? Both gcc and edg can handle that.
7598       if (!ClassType->isDependentType()) {
7599         DeclarationName Name
7600           = Context.DeclarationNames.getCXXDestructorName(
7601                                         Context.getCanonicalType(ClassType));
7602         if (NewFD->getDeclName() != Name) {
7603           Diag(NewFD->getLocation(), diag::err_destructor_name);
7604           NewFD->setInvalidDecl();
7605           return Redeclaration;
7606         }
7607       }
7608     } else if (CXXConversionDecl *Conversion
7609                = dyn_cast<CXXConversionDecl>(NewFD)) {
7610       ActOnConversionDeclarator(Conversion);
7611     }
7612 
7613     // Find any virtual functions that this function overrides.
7614     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7615       if (!Method->isFunctionTemplateSpecialization() &&
7616           !Method->getDescribedFunctionTemplate() &&
7617           Method->isCanonicalDecl()) {
7618         if (AddOverriddenMethods(Method->getParent(), Method)) {
7619           // If the function was marked as "static", we have a problem.
7620           if (NewFD->getStorageClass() == SC_Static) {
7621             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7622           }
7623         }
7624       }
7625 
7626       if (Method->isStatic())
7627         checkThisInStaticMemberFunctionType(Method);
7628     }
7629 
7630     // Extra checking for C++ overloaded operators (C++ [over.oper]).
7631     if (NewFD->isOverloadedOperator() &&
7632         CheckOverloadedOperatorDeclaration(NewFD)) {
7633       NewFD->setInvalidDecl();
7634       return Redeclaration;
7635     }
7636 
7637     // Extra checking for C++0x literal operators (C++0x [over.literal]).
7638     if (NewFD->getLiteralIdentifier() &&
7639         CheckLiteralOperatorDeclaration(NewFD)) {
7640       NewFD->setInvalidDecl();
7641       return Redeclaration;
7642     }
7643 
7644     // In C++, check default arguments now that we have merged decls. Unless
7645     // the lexical context is the class, because in this case this is done
7646     // during delayed parsing anyway.
7647     if (!CurContext->isRecord())
7648       CheckCXXDefaultArguments(NewFD);
7649 
7650     // If this function declares a builtin function, check the type of this
7651     // declaration against the expected type for the builtin.
7652     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7653       ASTContext::GetBuiltinTypeError Error;
7654       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7655       QualType T = Context.GetBuiltinType(BuiltinID, Error);
7656       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7657         // The type of this function differs from the type of the builtin,
7658         // so forget about the builtin entirely.
7659         Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7660       }
7661     }
7662 
7663     // If this function is declared as being extern "C", then check to see if
7664     // the function returns a UDT (class, struct, or union type) that is not C
7665     // compatible, and if it does, warn the user.
7666     // But, issue any diagnostic on the first declaration only.
7667     if (NewFD->isExternC() && Previous.empty()) {
7668       QualType R = NewFD->getResultType();
7669       if (R->isIncompleteType() && !R->isVoidType())
7670         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7671             << NewFD << R;
7672       else if (!R.isPODType(Context) && !R->isVoidType() &&
7673                !R->isObjCObjectPointerType())
7674         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7675     }
7676   }
7677   return Redeclaration;
7678 }
7679 
7680 static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7681   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7682   if (!TSI)
7683     return SourceRange();
7684 
7685   TypeLoc TL = TSI->getTypeLoc();
7686   FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7687   if (!FunctionTL)
7688     return SourceRange();
7689 
7690   TypeLoc ResultTL = FunctionTL.getResultLoc();
7691   if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7692     return ResultTL.getSourceRange();
7693 
7694   return SourceRange();
7695 }
7696 
7697 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7698   // C++11 [basic.start.main]p3:  A program that declares main to be inline,
7699   //   static or constexpr is ill-formed.
7700   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7701   //   appear in a declaration of main.
7702   // static main is not an error under C99, but we should warn about it.
7703   // We accept _Noreturn main as an extension.
7704   if (FD->getStorageClass() == SC_Static)
7705     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7706          ? diag::err_static_main : diag::warn_static_main)
7707       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7708   if (FD->isInlineSpecified())
7709     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7710       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7711   if (DS.isNoreturnSpecified()) {
7712     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7713     SourceRange NoreturnRange(NoreturnLoc,
7714                               PP.getLocForEndOfToken(NoreturnLoc));
7715     Diag(NoreturnLoc, diag::ext_noreturn_main);
7716     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7717       << FixItHint::CreateRemoval(NoreturnRange);
7718   }
7719   if (FD->isConstexpr()) {
7720     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7721       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7722     FD->setConstexpr(false);
7723   }
7724 
7725   if (getLangOpts().OpenCL) {
7726     Diag(FD->getLocation(), diag::err_opencl_no_main)
7727         << FD->hasAttr<OpenCLKernelAttr>();
7728     FD->setInvalidDecl();
7729     return;
7730   }
7731 
7732   QualType T = FD->getType();
7733   assert(T->isFunctionType() && "function decl is not of function type");
7734   const FunctionType* FT = T->castAs<FunctionType>();
7735 
7736   // All the standards say that main() should should return 'int'.
7737   if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7738     // In C and C++, main magically returns 0 if you fall off the end;
7739     // set the flag which tells us that.
7740     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7741     FD->setHasImplicitReturnZero(true);
7742 
7743   // In C with GNU extensions we allow main() to have non-integer return
7744   // type, but we should warn about the extension, and we disable the
7745   // implicit-return-zero rule.
7746   } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7747     Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7748 
7749     SourceRange ResultRange = getResultSourceRange(FD);
7750     if (ResultRange.isValid())
7751       Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7752           << FixItHint::CreateReplacement(ResultRange, "int");
7753 
7754   // Otherwise, this is just a flat-out error.
7755   } else {
7756     SourceRange ResultRange = getResultSourceRange(FD);
7757     if (ResultRange.isValid())
7758       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7759           << FixItHint::CreateReplacement(ResultRange, "int");
7760     else
7761       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7762 
7763     FD->setInvalidDecl(true);
7764   }
7765 
7766   // Treat protoless main() as nullary.
7767   if (isa<FunctionNoProtoType>(FT)) return;
7768 
7769   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7770   unsigned nparams = FTP->getNumArgs();
7771   assert(FD->getNumParams() == nparams);
7772 
7773   bool HasExtraParameters = (nparams > 3);
7774 
7775   // Darwin passes an undocumented fourth argument of type char**.  If
7776   // other platforms start sprouting these, the logic below will start
7777   // getting shifty.
7778   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7779     HasExtraParameters = false;
7780 
7781   if (HasExtraParameters) {
7782     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7783     FD->setInvalidDecl(true);
7784     nparams = 3;
7785   }
7786 
7787   // FIXME: a lot of the following diagnostics would be improved
7788   // if we had some location information about types.
7789 
7790   QualType CharPP =
7791     Context.getPointerType(Context.getPointerType(Context.CharTy));
7792   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7793 
7794   for (unsigned i = 0; i < nparams; ++i) {
7795     QualType AT = FTP->getArgType(i);
7796 
7797     bool mismatch = true;
7798 
7799     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7800       mismatch = false;
7801     else if (Expected[i] == CharPP) {
7802       // As an extension, the following forms are okay:
7803       //   char const **
7804       //   char const * const *
7805       //   char * const *
7806 
7807       QualifierCollector qs;
7808       const PointerType* PT;
7809       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7810           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7811           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7812                               Context.CharTy)) {
7813         qs.removeConst();
7814         mismatch = !qs.empty();
7815       }
7816     }
7817 
7818     if (mismatch) {
7819       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7820       // TODO: suggest replacing given type with expected type
7821       FD->setInvalidDecl(true);
7822     }
7823   }
7824 
7825   if (nparams == 1 && !FD->isInvalidDecl()) {
7826     Diag(FD->getLocation(), diag::warn_main_one_arg);
7827   }
7828 
7829   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7830     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7831     FD->setInvalidDecl();
7832   }
7833 }
7834 
7835 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7836   QualType T = FD->getType();
7837   assert(T->isFunctionType() && "function decl is not of function type");
7838   const FunctionType *FT = T->castAs<FunctionType>();
7839 
7840   // Set an implicit return of 'zero' if the function can return some integral,
7841   // enumeration, pointer or nullptr type.
7842   if (FT->getResultType()->isIntegralOrEnumerationType() ||
7843       FT->getResultType()->isAnyPointerType() ||
7844       FT->getResultType()->isNullPtrType())
7845     // DllMain is exempt because a return value of zero means it failed.
7846     if (FD->getName() != "DllMain")
7847       FD->setHasImplicitReturnZero(true);
7848 
7849   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7850     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
7851     FD->setInvalidDecl();
7852   }
7853 }
7854 
7855 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
7856   // FIXME: Need strict checking.  In C89, we need to check for
7857   // any assignment, increment, decrement, function-calls, or
7858   // commas outside of a sizeof.  In C99, it's the same list,
7859   // except that the aforementioned are allowed in unevaluated
7860   // expressions.  Everything else falls under the
7861   // "may accept other forms of constant expressions" exception.
7862   // (We never end up here for C++, so the constant expression
7863   // rules there don't matter.)
7864   if (Init->isConstantInitializer(Context, false))
7865     return false;
7866   Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7867     << Init->getSourceRange();
7868   return true;
7869 }
7870 
7871 namespace {
7872   // Visits an initialization expression to see if OrigDecl is evaluated in
7873   // its own initialization and throws a warning if it does.
7874   class SelfReferenceChecker
7875       : public EvaluatedExprVisitor<SelfReferenceChecker> {
7876     Sema &S;
7877     Decl *OrigDecl;
7878     bool isRecordType;
7879     bool isPODType;
7880     bool isReferenceType;
7881 
7882   public:
7883     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7884 
7885     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7886                                                     S(S), OrigDecl(OrigDecl) {
7887       isPODType = false;
7888       isRecordType = false;
7889       isReferenceType = false;
7890       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7891         isPODType = VD->getType().isPODType(S.Context);
7892         isRecordType = VD->getType()->isRecordType();
7893         isReferenceType = VD->getType()->isReferenceType();
7894       }
7895     }
7896 
7897     // For most expressions, the cast is directly above the DeclRefExpr.
7898     // For conditional operators, the cast can be outside the conditional
7899     // operator if both expressions are DeclRefExpr's.
7900     void HandleValue(Expr *E) {
7901       if (isReferenceType)
7902         return;
7903       E = E->IgnoreParenImpCasts();
7904       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7905         HandleDeclRefExpr(DRE);
7906         return;
7907       }
7908 
7909       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7910         HandleValue(CO->getTrueExpr());
7911         HandleValue(CO->getFalseExpr());
7912         return;
7913       }
7914 
7915       if (isa<MemberExpr>(E)) {
7916         Expr *Base = E->IgnoreParenImpCasts();
7917         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7918           // Check for static member variables and don't warn on them.
7919           if (!isa<FieldDecl>(ME->getMemberDecl()))
7920             return;
7921           Base = ME->getBase()->IgnoreParenImpCasts();
7922         }
7923         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7924           HandleDeclRefExpr(DRE);
7925         return;
7926       }
7927     }
7928 
7929     // Reference types are handled here since all uses of references are
7930     // bad, not just r-value uses.
7931     void VisitDeclRefExpr(DeclRefExpr *E) {
7932       if (isReferenceType)
7933         HandleDeclRefExpr(E);
7934     }
7935 
7936     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
7937       if (E->getCastKind() == CK_LValueToRValue ||
7938           (isRecordType && E->getCastKind() == CK_NoOp))
7939         HandleValue(E->getSubExpr());
7940 
7941       Inherited::VisitImplicitCastExpr(E);
7942     }
7943 
7944     void VisitMemberExpr(MemberExpr *E) {
7945       // Don't warn on arrays since they can be treated as pointers.
7946       if (E->getType()->canDecayToPointerType()) return;
7947 
7948       // Warn when a non-static method call is followed by non-static member
7949       // field accesses, which is followed by a DeclRefExpr.
7950       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7951       bool Warn = (MD && !MD->isStatic());
7952       Expr *Base = E->getBase()->IgnoreParenImpCasts();
7953       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7954         if (!isa<FieldDecl>(ME->getMemberDecl()))
7955           Warn = false;
7956         Base = ME->getBase()->IgnoreParenImpCasts();
7957       }
7958 
7959       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7960         if (Warn)
7961           HandleDeclRefExpr(DRE);
7962         return;
7963       }
7964 
7965       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7966       // Visit that expression.
7967       Visit(Base);
7968     }
7969 
7970     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7971       if (E->getNumArgs() > 0)
7972         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7973           HandleDeclRefExpr(DRE);
7974 
7975       Inherited::VisitCXXOperatorCallExpr(E);
7976     }
7977 
7978     void VisitUnaryOperator(UnaryOperator *E) {
7979       // For POD record types, addresses of its own members are well-defined.
7980       if (E->getOpcode() == UO_AddrOf && isRecordType &&
7981           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7982         if (!isPODType)
7983           HandleValue(E->getSubExpr());
7984         return;
7985       }
7986       Inherited::VisitUnaryOperator(E);
7987     }
7988 
7989     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7990 
7991     void HandleDeclRefExpr(DeclRefExpr *DRE) {
7992       Decl* ReferenceDecl = DRE->getDecl();
7993       if (OrigDecl != ReferenceDecl) return;
7994       unsigned diag;
7995       if (isReferenceType) {
7996         diag = diag::warn_uninit_self_reference_in_reference_init;
7997       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7998         diag = diag::warn_static_self_reference_in_init;
7999       } else {
8000         diag = diag::warn_uninit_self_reference_in_init;
8001       }
8002 
8003       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
8004                             S.PDiag(diag)
8005                               << DRE->getNameInfo().getName()
8006                               << OrigDecl->getLocation()
8007                               << DRE->getSourceRange());
8008     }
8009   };
8010 
8011   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
8012   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
8013                                  bool DirectInit) {
8014     // Parameters arguments are occassionially constructed with itself,
8015     // for instance, in recursive functions.  Skip them.
8016     if (isa<ParmVarDecl>(OrigDecl))
8017       return;
8018 
8019     E = E->IgnoreParens();
8020 
8021     // Skip checking T a = a where T is not a record or reference type.
8022     // Doing so is a way to silence uninitialized warnings.
8023     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
8024       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
8025         if (ICE->getCastKind() == CK_LValueToRValue)
8026           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
8027             if (DRE->getDecl() == OrigDecl)
8028               return;
8029 
8030     SelfReferenceChecker(S, OrigDecl).Visit(E);
8031   }
8032 }
8033 
8034 /// AddInitializerToDecl - Adds the initializer Init to the
8035 /// declaration dcl. If DirectInit is true, this is C++ direct
8036 /// initialization rather than copy initialization.
8037 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8038                                 bool DirectInit, bool TypeMayContainAuto) {
8039   // If there is no declaration, there was an error parsing it.  Just ignore
8040   // the initializer.
8041   if (RealDecl == 0 || RealDecl->isInvalidDecl())
8042     return;
8043 
8044   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8045     // With declarators parsed the way they are, the parser cannot
8046     // distinguish between a normal initializer and a pure-specifier.
8047     // Thus this grotesque test.
8048     IntegerLiteral *IL;
8049     if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8050         Context.getCanonicalType(IL->getType()) == Context.IntTy)
8051       CheckPureMethod(Method, Init->getSourceRange());
8052     else {
8053       Diag(Method->getLocation(), diag::err_member_function_initialization)
8054         << Method->getDeclName() << Init->getSourceRange();
8055       Method->setInvalidDecl();
8056     }
8057     return;
8058   }
8059 
8060   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8061   if (!VDecl) {
8062     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8063     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8064     RealDecl->setInvalidDecl();
8065     return;
8066   }
8067   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8068 
8069   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8070   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8071     Expr *DeduceInit = Init;
8072     // Initializer could be a C++ direct-initializer. Deduction only works if it
8073     // contains exactly one expression.
8074     if (CXXDirectInit) {
8075       if (CXXDirectInit->getNumExprs() == 0) {
8076         // It isn't possible to write this directly, but it is possible to
8077         // end up in this situation with "auto x(some_pack...);"
8078         Diag(CXXDirectInit->getLocStart(),
8079              VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8080                                     : diag::err_auto_var_init_no_expression)
8081           << VDecl->getDeclName() << VDecl->getType()
8082           << VDecl->getSourceRange();
8083         RealDecl->setInvalidDecl();
8084         return;
8085       } else if (CXXDirectInit->getNumExprs() > 1) {
8086         Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8087              VDecl->isInitCapture()
8088                  ? diag::err_init_capture_multiple_expressions
8089                  : diag::err_auto_var_init_multiple_expressions)
8090           << VDecl->getDeclName() << VDecl->getType()
8091           << VDecl->getSourceRange();
8092         RealDecl->setInvalidDecl();
8093         return;
8094       } else {
8095         DeduceInit = CXXDirectInit->getExpr(0);
8096       }
8097     }
8098 
8099     // Expressions default to 'id' when we're in a debugger.
8100     bool DefaultedToAuto = false;
8101     if (getLangOpts().DebuggerCastResultToId &&
8102         Init->getType() == Context.UnknownAnyTy) {
8103       ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8104       if (Result.isInvalid()) {
8105         VDecl->setInvalidDecl();
8106         return;
8107       }
8108       Init = Result.take();
8109       DefaultedToAuto = true;
8110     }
8111 
8112     QualType DeducedType;
8113     if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8114             DAR_Failed)
8115       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8116     if (DeducedType.isNull()) {
8117       RealDecl->setInvalidDecl();
8118       return;
8119     }
8120     VDecl->setType(DeducedType);
8121     assert(VDecl->isLinkageValid());
8122 
8123     // In ARC, infer lifetime.
8124     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8125       VDecl->setInvalidDecl();
8126 
8127     // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8128     // 'id' instead of a specific object type prevents most of our usual checks.
8129     // We only want to warn outside of template instantiations, though:
8130     // inside a template, the 'id' could have come from a parameter.
8131     if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8132         DeducedType->isObjCIdType()) {
8133       SourceLocation Loc =
8134           VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8135       Diag(Loc, diag::warn_auto_var_is_id)
8136         << VDecl->getDeclName() << DeduceInit->getSourceRange();
8137     }
8138 
8139     // If this is a redeclaration, check that the type we just deduced matches
8140     // the previously declared type.
8141     if (VarDecl *Old = VDecl->getPreviousDecl()) {
8142       // We never need to merge the type, because we cannot form an incomplete
8143       // array of auto, nor deduce such a type.
8144       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8145     }
8146 
8147     // Check the deduced type is valid for a variable declaration.
8148     CheckVariableDeclarationType(VDecl);
8149     if (VDecl->isInvalidDecl())
8150       return;
8151   }
8152 
8153   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8154     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8155     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8156     VDecl->setInvalidDecl();
8157     return;
8158   }
8159 
8160   if (!VDecl->getType()->isDependentType()) {
8161     // A definition must end up with a complete type, which means it must be
8162     // complete with the restriction that an array type might be completed by
8163     // the initializer; note that later code assumes this restriction.
8164     QualType BaseDeclType = VDecl->getType();
8165     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8166       BaseDeclType = Array->getElementType();
8167     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8168                             diag::err_typecheck_decl_incomplete_type)) {
8169       RealDecl->setInvalidDecl();
8170       return;
8171     }
8172 
8173     // The variable can not have an abstract class type.
8174     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8175                                diag::err_abstract_type_in_decl,
8176                                AbstractVariableType))
8177       VDecl->setInvalidDecl();
8178   }
8179 
8180   const VarDecl *Def;
8181   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8182     Diag(VDecl->getLocation(), diag::err_redefinition)
8183       << VDecl->getDeclName();
8184     Diag(Def->getLocation(), diag::note_previous_definition);
8185     VDecl->setInvalidDecl();
8186     return;
8187   }
8188 
8189   const VarDecl* PrevInit = 0;
8190   if (getLangOpts().CPlusPlus) {
8191     // C++ [class.static.data]p4
8192     //   If a static data member is of const integral or const
8193     //   enumeration type, its declaration in the class definition can
8194     //   specify a constant-initializer which shall be an integral
8195     //   constant expression (5.19). In that case, the member can appear
8196     //   in integral constant expressions. The member shall still be
8197     //   defined in a namespace scope if it is used in the program and the
8198     //   namespace scope definition shall not contain an initializer.
8199     //
8200     // We already performed a redefinition check above, but for static
8201     // data members we also need to check whether there was an in-class
8202     // declaration with an initializer.
8203     if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8204       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
8205           << VDecl->getDeclName();
8206       Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0;
8207       return;
8208     }
8209 
8210     if (VDecl->hasLocalStorage())
8211       getCurFunction()->setHasBranchProtectedScope();
8212 
8213     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8214       VDecl->setInvalidDecl();
8215       return;
8216     }
8217   }
8218 
8219   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8220   // a kernel function cannot be initialized."
8221   if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8222     Diag(VDecl->getLocation(), diag::err_local_cant_init);
8223     VDecl->setInvalidDecl();
8224     return;
8225   }
8226 
8227   // Get the decls type and save a reference for later, since
8228   // CheckInitializerTypes may change it.
8229   QualType DclT = VDecl->getType(), SavT = DclT;
8230 
8231   // Expressions default to 'id' when we're in a debugger
8232   // and we are assigning it to a variable of Objective-C pointer type.
8233   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8234       Init->getType() == Context.UnknownAnyTy) {
8235     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8236     if (Result.isInvalid()) {
8237       VDecl->setInvalidDecl();
8238       return;
8239     }
8240     Init = Result.take();
8241   }
8242 
8243   // Perform the initialization.
8244   if (!VDecl->isInvalidDecl()) {
8245     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8246     InitializationKind Kind
8247       = DirectInit ?
8248           CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8249                                                            Init->getLocStart(),
8250                                                            Init->getLocEnd())
8251                         : InitializationKind::CreateDirectList(
8252                                                           VDecl->getLocation())
8253                    : InitializationKind::CreateCopy(VDecl->getLocation(),
8254                                                     Init->getLocStart());
8255 
8256     MultiExprArg Args = Init;
8257     if (CXXDirectInit)
8258       Args = MultiExprArg(CXXDirectInit->getExprs(),
8259                           CXXDirectInit->getNumExprs());
8260 
8261     InitializationSequence InitSeq(*this, Entity, Kind, Args);
8262     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8263     if (Result.isInvalid()) {
8264       VDecl->setInvalidDecl();
8265       return;
8266     }
8267 
8268     Init = Result.takeAs<Expr>();
8269   }
8270 
8271   // Check for self-references within variable initializers.
8272   // Variables declared within a function/method body (except for references)
8273   // are handled by a dataflow analysis.
8274   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8275       VDecl->getType()->isReferenceType()) {
8276     CheckSelfReference(*this, RealDecl, Init, DirectInit);
8277   }
8278 
8279   // If the type changed, it means we had an incomplete type that was
8280   // completed by the initializer. For example:
8281   //   int ary[] = { 1, 3, 5 };
8282   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8283   if (!VDecl->isInvalidDecl() && (DclT != SavT))
8284     VDecl->setType(DclT);
8285 
8286   if (!VDecl->isInvalidDecl()) {
8287     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8288 
8289     if (VDecl->hasAttr<BlocksAttr>())
8290       checkRetainCycles(VDecl, Init);
8291 
8292     // It is safe to assign a weak reference into a strong variable.
8293     // Although this code can still have problems:
8294     //   id x = self.weakProp;
8295     //   id y = self.weakProp;
8296     // we do not warn to warn spuriously when 'x' and 'y' are on separate
8297     // paths through the function. This should be revisited if
8298     // -Wrepeated-use-of-weak is made flow-sensitive.
8299     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
8300       DiagnosticsEngine::Level Level =
8301         Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8302                                  Init->getLocStart());
8303       if (Level != DiagnosticsEngine::Ignored)
8304         getCurFunction()->markSafeWeakUse(Init);
8305     }
8306   }
8307 
8308   // The initialization is usually a full-expression.
8309   //
8310   // FIXME: If this is a braced initialization of an aggregate, it is not
8311   // an expression, and each individual field initializer is a separate
8312   // full-expression. For instance, in:
8313   //
8314   //   struct Temp { ~Temp(); };
8315   //   struct S { S(Temp); };
8316   //   struct T { S a, b; } t = { Temp(), Temp() }
8317   //
8318   // we should destroy the first Temp before constructing the second.
8319   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8320                                           false,
8321                                           VDecl->isConstexpr());
8322   if (Result.isInvalid()) {
8323     VDecl->setInvalidDecl();
8324     return;
8325   }
8326   Init = Result.take();
8327 
8328   // Attach the initializer to the decl.
8329   VDecl->setInit(Init);
8330 
8331   if (VDecl->isLocalVarDecl()) {
8332     // C99 6.7.8p4: All the expressions in an initializer for an object that has
8333     // static storage duration shall be constant expressions or string literals.
8334     // C++ does not have this restriction.
8335     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8336       if (VDecl->getStorageClass() == SC_Static)
8337         CheckForConstantInitializer(Init, DclT);
8338       // C89 is stricter than C99 for non-static aggregate types.
8339       // C89 6.5.7p3: All the expressions [...] in an initializer list
8340       // for an object that has aggregate or union type shall be
8341       // constant expressions.
8342       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8343                isa<InitListExpr>(Init) &&
8344                !Init->isConstantInitializer(Context, false))
8345         Diag(Init->getExprLoc(),
8346              diag::ext_aggregate_init_not_constant)
8347           << Init->getSourceRange();
8348     }
8349   } else if (VDecl->isStaticDataMember() &&
8350              VDecl->getLexicalDeclContext()->isRecord()) {
8351     // This is an in-class initialization for a static data member, e.g.,
8352     //
8353     // struct S {
8354     //   static const int value = 17;
8355     // };
8356 
8357     // C++ [class.mem]p4:
8358     //   A member-declarator can contain a constant-initializer only
8359     //   if it declares a static member (9.4) of const integral or
8360     //   const enumeration type, see 9.4.2.
8361     //
8362     // C++11 [class.static.data]p3:
8363     //   If a non-volatile const static data member is of integral or
8364     //   enumeration type, its declaration in the class definition can
8365     //   specify a brace-or-equal-initializer in which every initalizer-clause
8366     //   that is an assignment-expression is a constant expression. A static
8367     //   data member of literal type can be declared in the class definition
8368     //   with the constexpr specifier; if so, its declaration shall specify a
8369     //   brace-or-equal-initializer in which every initializer-clause that is
8370     //   an assignment-expression is a constant expression.
8371 
8372     // Do nothing on dependent types.
8373     if (DclT->isDependentType()) {
8374 
8375     // Allow any 'static constexpr' members, whether or not they are of literal
8376     // type. We separately check that every constexpr variable is of literal
8377     // type.
8378     } else if (VDecl->isConstexpr()) {
8379 
8380     // Require constness.
8381     } else if (!DclT.isConstQualified()) {
8382       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8383         << Init->getSourceRange();
8384       VDecl->setInvalidDecl();
8385 
8386     // We allow integer constant expressions in all cases.
8387     } else if (DclT->isIntegralOrEnumerationType()) {
8388       // Check whether the expression is a constant expression.
8389       SourceLocation Loc;
8390       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8391         // In C++11, a non-constexpr const static data member with an
8392         // in-class initializer cannot be volatile.
8393         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8394       else if (Init->isValueDependent())
8395         ; // Nothing to check.
8396       else if (Init->isIntegerConstantExpr(Context, &Loc))
8397         ; // Ok, it's an ICE!
8398       else if (Init->isEvaluatable(Context)) {
8399         // If we can constant fold the initializer through heroics, accept it,
8400         // but report this as a use of an extension for -pedantic.
8401         Diag(Loc, diag::ext_in_class_initializer_non_constant)
8402           << Init->getSourceRange();
8403       } else {
8404         // Otherwise, this is some crazy unknown case.  Report the issue at the
8405         // location provided by the isIntegerConstantExpr failed check.
8406         Diag(Loc, diag::err_in_class_initializer_non_constant)
8407           << Init->getSourceRange();
8408         VDecl->setInvalidDecl();
8409       }
8410 
8411     // We allow foldable floating-point constants as an extension.
8412     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8413       // In C++98, this is a GNU extension. In C++11, it is not, but we support
8414       // it anyway and provide a fixit to add the 'constexpr'.
8415       if (getLangOpts().CPlusPlus11) {
8416         Diag(VDecl->getLocation(),
8417              diag::ext_in_class_initializer_float_type_cxx11)
8418             << DclT << Init->getSourceRange();
8419         Diag(VDecl->getLocStart(),
8420              diag::note_in_class_initializer_float_type_cxx11)
8421             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8422       } else {
8423         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8424           << DclT << Init->getSourceRange();
8425 
8426         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8427           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8428             << Init->getSourceRange();
8429           VDecl->setInvalidDecl();
8430         }
8431       }
8432 
8433     // Suggest adding 'constexpr' in C++11 for literal types.
8434     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8435       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8436         << DclT << Init->getSourceRange()
8437         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8438       VDecl->setConstexpr(true);
8439 
8440     } else {
8441       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8442         << DclT << Init->getSourceRange();
8443       VDecl->setInvalidDecl();
8444     }
8445   } else if (VDecl->isFileVarDecl()) {
8446     if (VDecl->getStorageClass() == SC_Extern &&
8447         (!getLangOpts().CPlusPlus ||
8448          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8449            VDecl->isExternC())) &&
8450         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8451       Diag(VDecl->getLocation(), diag::warn_extern_init);
8452 
8453     // C99 6.7.8p4. All file scoped initializers need to be constant.
8454     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8455       CheckForConstantInitializer(Init, DclT);
8456     else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8457              !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8458              !Init->isValueDependent() && !VDecl->isConstexpr() &&
8459              !Init->isConstantInitializer(
8460                  Context, VDecl->getType()->isReferenceType())) {
8461       // GNU C++98 edits for __thread, [basic.start.init]p4:
8462       //   An object of thread storage duration shall not require dynamic
8463       //   initialization.
8464       // FIXME: Need strict checking here.
8465       Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8466       if (getLangOpts().CPlusPlus11)
8467         Diag(VDecl->getLocation(), diag::note_use_thread_local);
8468     }
8469   }
8470 
8471   // We will represent direct-initialization similarly to copy-initialization:
8472   //    int x(1);  -as-> int x = 1;
8473   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8474   //
8475   // Clients that want to distinguish between the two forms, can check for
8476   // direct initializer using VarDecl::getInitStyle().
8477   // A major benefit is that clients that don't particularly care about which
8478   // exactly form was it (like the CodeGen) can handle both cases without
8479   // special case code.
8480 
8481   // C++ 8.5p11:
8482   // The form of initialization (using parentheses or '=') is generally
8483   // insignificant, but does matter when the entity being initialized has a
8484   // class type.
8485   if (CXXDirectInit) {
8486     assert(DirectInit && "Call-style initializer must be direct init.");
8487     VDecl->setInitStyle(VarDecl::CallInit);
8488   } else if (DirectInit) {
8489     // This must be list-initialization. No other way is direct-initialization.
8490     VDecl->setInitStyle(VarDecl::ListInit);
8491   }
8492 
8493   CheckCompleteVariableDeclaration(VDecl);
8494 }
8495 
8496 /// ActOnInitializerError - Given that there was an error parsing an
8497 /// initializer for the given declaration, try to return to some form
8498 /// of sanity.
8499 void Sema::ActOnInitializerError(Decl *D) {
8500   // Our main concern here is re-establishing invariants like "a
8501   // variable's type is either dependent or complete".
8502   if (!D || D->isInvalidDecl()) return;
8503 
8504   VarDecl *VD = dyn_cast<VarDecl>(D);
8505   if (!VD) return;
8506 
8507   // Auto types are meaningless if we can't make sense of the initializer.
8508   if (ParsingInitForAutoVars.count(D)) {
8509     D->setInvalidDecl();
8510     return;
8511   }
8512 
8513   QualType Ty = VD->getType();
8514   if (Ty->isDependentType()) return;
8515 
8516   // Require a complete type.
8517   if (RequireCompleteType(VD->getLocation(),
8518                           Context.getBaseElementType(Ty),
8519                           diag::err_typecheck_decl_incomplete_type)) {
8520     VD->setInvalidDecl();
8521     return;
8522   }
8523 
8524   // Require an abstract type.
8525   if (RequireNonAbstractType(VD->getLocation(), Ty,
8526                              diag::err_abstract_type_in_decl,
8527                              AbstractVariableType)) {
8528     VD->setInvalidDecl();
8529     return;
8530   }
8531 
8532   // Don't bother complaining about constructors or destructors,
8533   // though.
8534 }
8535 
8536 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8537                                   bool TypeMayContainAuto) {
8538   // If there is no declaration, there was an error parsing it. Just ignore it.
8539   if (RealDecl == 0)
8540     return;
8541 
8542   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8543     QualType Type = Var->getType();
8544 
8545     // C++11 [dcl.spec.auto]p3
8546     if (TypeMayContainAuto && Type->getContainedAutoType()) {
8547       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8548         << Var->getDeclName() << Type;
8549       Var->setInvalidDecl();
8550       return;
8551     }
8552 
8553     // C++11 [class.static.data]p3: A static data member can be declared with
8554     // the constexpr specifier; if so, its declaration shall specify
8555     // a brace-or-equal-initializer.
8556     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8557     // the definition of a variable [...] or the declaration of a static data
8558     // member.
8559     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8560       if (Var->isStaticDataMember())
8561         Diag(Var->getLocation(),
8562              diag::err_constexpr_static_mem_var_requires_init)
8563           << Var->getDeclName();
8564       else
8565         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8566       Var->setInvalidDecl();
8567       return;
8568     }
8569 
8570     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
8571     // be initialized.
8572     if (!Var->isInvalidDecl() &&
8573         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
8574         !Var->getInit()) {
8575       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
8576       Var->setInvalidDecl();
8577       return;
8578     }
8579 
8580     switch (Var->isThisDeclarationADefinition()) {
8581     case VarDecl::Definition:
8582       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8583         break;
8584 
8585       // We have an out-of-line definition of a static data member
8586       // that has an in-class initializer, so we type-check this like
8587       // a declaration.
8588       //
8589       // Fall through
8590 
8591     case VarDecl::DeclarationOnly:
8592       // It's only a declaration.
8593 
8594       // Block scope. C99 6.7p7: If an identifier for an object is
8595       // declared with no linkage (C99 6.2.2p6), the type for the
8596       // object shall be complete.
8597       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8598           !Var->hasLinkage() && !Var->isInvalidDecl() &&
8599           RequireCompleteType(Var->getLocation(), Type,
8600                               diag::err_typecheck_decl_incomplete_type))
8601         Var->setInvalidDecl();
8602 
8603       // Make sure that the type is not abstract.
8604       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8605           RequireNonAbstractType(Var->getLocation(), Type,
8606                                  diag::err_abstract_type_in_decl,
8607                                  AbstractVariableType))
8608         Var->setInvalidDecl();
8609       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8610           Var->getStorageClass() == SC_PrivateExtern) {
8611         Diag(Var->getLocation(), diag::warn_private_extern);
8612         Diag(Var->getLocation(), diag::note_private_extern);
8613       }
8614 
8615       return;
8616 
8617     case VarDecl::TentativeDefinition:
8618       // File scope. C99 6.9.2p2: A declaration of an identifier for an
8619       // object that has file scope without an initializer, and without a
8620       // storage-class specifier or with the storage-class specifier "static",
8621       // constitutes a tentative definition. Note: A tentative definition with
8622       // external linkage is valid (C99 6.2.2p5).
8623       if (!Var->isInvalidDecl()) {
8624         if (const IncompleteArrayType *ArrayT
8625                                     = Context.getAsIncompleteArrayType(Type)) {
8626           if (RequireCompleteType(Var->getLocation(),
8627                                   ArrayT->getElementType(),
8628                                   diag::err_illegal_decl_array_incomplete_type))
8629             Var->setInvalidDecl();
8630         } else if (Var->getStorageClass() == SC_Static) {
8631           // C99 6.9.2p3: If the declaration of an identifier for an object is
8632           // a tentative definition and has internal linkage (C99 6.2.2p3), the
8633           // declared type shall not be an incomplete type.
8634           // NOTE: code such as the following
8635           //     static struct s;
8636           //     struct s { int a; };
8637           // is accepted by gcc. Hence here we issue a warning instead of
8638           // an error and we do not invalidate the static declaration.
8639           // NOTE: to avoid multiple warnings, only check the first declaration.
8640           if (Var->isFirstDecl())
8641             RequireCompleteType(Var->getLocation(), Type,
8642                                 diag::ext_typecheck_decl_incomplete_type);
8643         }
8644       }
8645 
8646       // Record the tentative definition; we're done.
8647       if (!Var->isInvalidDecl())
8648         TentativeDefinitions.push_back(Var);
8649       return;
8650     }
8651 
8652     // Provide a specific diagnostic for uninitialized variable
8653     // definitions with incomplete array type.
8654     if (Type->isIncompleteArrayType()) {
8655       Diag(Var->getLocation(),
8656            diag::err_typecheck_incomplete_array_needs_initializer);
8657       Var->setInvalidDecl();
8658       return;
8659     }
8660 
8661     // Provide a specific diagnostic for uninitialized variable
8662     // definitions with reference type.
8663     if (Type->isReferenceType()) {
8664       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8665         << Var->getDeclName()
8666         << SourceRange(Var->getLocation(), Var->getLocation());
8667       Var->setInvalidDecl();
8668       return;
8669     }
8670 
8671     // Do not attempt to type-check the default initializer for a
8672     // variable with dependent type.
8673     if (Type->isDependentType())
8674       return;
8675 
8676     if (Var->isInvalidDecl())
8677       return;
8678 
8679     if (RequireCompleteType(Var->getLocation(),
8680                             Context.getBaseElementType(Type),
8681                             diag::err_typecheck_decl_incomplete_type)) {
8682       Var->setInvalidDecl();
8683       return;
8684     }
8685 
8686     // The variable can not have an abstract class type.
8687     if (RequireNonAbstractType(Var->getLocation(), Type,
8688                                diag::err_abstract_type_in_decl,
8689                                AbstractVariableType)) {
8690       Var->setInvalidDecl();
8691       return;
8692     }
8693 
8694     // Check for jumps past the implicit initializer.  C++0x
8695     // clarifies that this applies to a "variable with automatic
8696     // storage duration", not a "local variable".
8697     // C++11 [stmt.dcl]p3
8698     //   A program that jumps from a point where a variable with automatic
8699     //   storage duration is not in scope to a point where it is in scope is
8700     //   ill-formed unless the variable has scalar type, class type with a
8701     //   trivial default constructor and a trivial destructor, a cv-qualified
8702     //   version of one of these types, or an array of one of the preceding
8703     //   types and is declared without an initializer.
8704     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8705       if (const RecordType *Record
8706             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8707         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8708         // Mark the function for further checking even if the looser rules of
8709         // C++11 do not require such checks, so that we can diagnose
8710         // incompatibilities with C++98.
8711         if (!CXXRecord->isPOD())
8712           getCurFunction()->setHasBranchProtectedScope();
8713       }
8714     }
8715 
8716     // C++03 [dcl.init]p9:
8717     //   If no initializer is specified for an object, and the
8718     //   object is of (possibly cv-qualified) non-POD class type (or
8719     //   array thereof), the object shall be default-initialized; if
8720     //   the object is of const-qualified type, the underlying class
8721     //   type shall have a user-declared default
8722     //   constructor. Otherwise, if no initializer is specified for
8723     //   a non- static object, the object and its subobjects, if
8724     //   any, have an indeterminate initial value); if the object
8725     //   or any of its subobjects are of const-qualified type, the
8726     //   program is ill-formed.
8727     // C++0x [dcl.init]p11:
8728     //   If no initializer is specified for an object, the object is
8729     //   default-initialized; [...].
8730     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8731     InitializationKind Kind
8732       = InitializationKind::CreateDefault(Var->getLocation());
8733 
8734     InitializationSequence InitSeq(*this, Entity, Kind, None);
8735     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8736     if (Init.isInvalid())
8737       Var->setInvalidDecl();
8738     else if (Init.get()) {
8739       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8740       // This is important for template substitution.
8741       Var->setInitStyle(VarDecl::CallInit);
8742     }
8743 
8744     CheckCompleteVariableDeclaration(Var);
8745   }
8746 }
8747 
8748 void Sema::ActOnCXXForRangeDecl(Decl *D) {
8749   VarDecl *VD = dyn_cast<VarDecl>(D);
8750   if (!VD) {
8751     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8752     D->setInvalidDecl();
8753     return;
8754   }
8755 
8756   VD->setCXXForRangeDecl(true);
8757 
8758   // for-range-declaration cannot be given a storage class specifier.
8759   int Error = -1;
8760   switch (VD->getStorageClass()) {
8761   case SC_None:
8762     break;
8763   case SC_Extern:
8764     Error = 0;
8765     break;
8766   case SC_Static:
8767     Error = 1;
8768     break;
8769   case SC_PrivateExtern:
8770     Error = 2;
8771     break;
8772   case SC_Auto:
8773     Error = 3;
8774     break;
8775   case SC_Register:
8776     Error = 4;
8777     break;
8778   case SC_OpenCLWorkGroupLocal:
8779     llvm_unreachable("Unexpected storage class");
8780   }
8781   if (VD->isConstexpr())
8782     Error = 5;
8783   if (Error != -1) {
8784     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8785       << VD->getDeclName() << Error;
8786     D->setInvalidDecl();
8787   }
8788 }
8789 
8790 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8791   if (var->isInvalidDecl()) return;
8792 
8793   // In ARC, don't allow jumps past the implicit initialization of a
8794   // local retaining variable.
8795   if (getLangOpts().ObjCAutoRefCount &&
8796       var->hasLocalStorage()) {
8797     switch (var->getType().getObjCLifetime()) {
8798     case Qualifiers::OCL_None:
8799     case Qualifiers::OCL_ExplicitNone:
8800     case Qualifiers::OCL_Autoreleasing:
8801       break;
8802 
8803     case Qualifiers::OCL_Weak:
8804     case Qualifiers::OCL_Strong:
8805       getCurFunction()->setHasBranchProtectedScope();
8806       break;
8807     }
8808   }
8809 
8810   if (var->isThisDeclarationADefinition() &&
8811       var->isExternallyVisible() && var->hasLinkage() &&
8812       getDiagnostics().getDiagnosticLevel(
8813                        diag::warn_missing_variable_declarations,
8814                        var->getLocation())) {
8815     // Find a previous declaration that's not a definition.
8816     VarDecl *prev = var->getPreviousDecl();
8817     while (prev && prev->isThisDeclarationADefinition())
8818       prev = prev->getPreviousDecl();
8819 
8820     if (!prev)
8821       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8822   }
8823 
8824   if (var->getTLSKind() == VarDecl::TLS_Static &&
8825       var->getType().isDestructedType()) {
8826     // GNU C++98 edits for __thread, [basic.start.term]p3:
8827     //   The type of an object with thread storage duration shall not
8828     //   have a non-trivial destructor.
8829     Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8830     if (getLangOpts().CPlusPlus11)
8831       Diag(var->getLocation(), diag::note_use_thread_local);
8832   }
8833 
8834   // All the following checks are C++ only.
8835   if (!getLangOpts().CPlusPlus) return;
8836 
8837   QualType type = var->getType();
8838   if (type->isDependentType()) return;
8839 
8840   // __block variables might require us to capture a copy-initializer.
8841   if (var->hasAttr<BlocksAttr>()) {
8842     // It's currently invalid to ever have a __block variable with an
8843     // array type; should we diagnose that here?
8844 
8845     // Regardless, we don't want to ignore array nesting when
8846     // constructing this copy.
8847     if (type->isStructureOrClassType()) {
8848       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
8849       SourceLocation poi = var->getLocation();
8850       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
8851       ExprResult result
8852         = PerformMoveOrCopyInitialization(
8853             InitializedEntity::InitializeBlock(poi, type, false),
8854             var, var->getType(), varRef, /*AllowNRVO=*/true);
8855       if (!result.isInvalid()) {
8856         result = MaybeCreateExprWithCleanups(result);
8857         Expr *init = result.takeAs<Expr>();
8858         Context.setBlockVarCopyInits(var, init);
8859       }
8860     }
8861   }
8862 
8863   Expr *Init = var->getInit();
8864   bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
8865   QualType baseType = Context.getBaseElementType(type);
8866 
8867   if (!var->getDeclContext()->isDependentContext() &&
8868       Init && !Init->isValueDependent()) {
8869     if (IsGlobal && !var->isConstexpr() &&
8870         getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8871                                             var->getLocation())
8872           != DiagnosticsEngine::Ignored) {
8873       // Warn about globals which don't have a constant initializer.  Don't
8874       // warn about globals with a non-trivial destructor because we already
8875       // warned about them.
8876       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8877       if (!(RD && !RD->hasTrivialDestructor()) &&
8878           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8879         Diag(var->getLocation(), diag::warn_global_constructor)
8880           << Init->getSourceRange();
8881     }
8882 
8883     if (var->isConstexpr()) {
8884       SmallVector<PartialDiagnosticAt, 8> Notes;
8885       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8886         SourceLocation DiagLoc = var->getLocation();
8887         // If the note doesn't add any useful information other than a source
8888         // location, fold it into the primary diagnostic.
8889         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8890               diag::note_invalid_subexpr_in_const_expr) {
8891           DiagLoc = Notes[0].first;
8892           Notes.clear();
8893         }
8894         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8895           << var << Init->getSourceRange();
8896         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8897           Diag(Notes[I].first, Notes[I].second);
8898       }
8899     } else if (var->isUsableInConstantExpressions(Context)) {
8900       // Check whether the initializer of a const variable of integral or
8901       // enumeration type is an ICE now, since we can't tell whether it was
8902       // initialized by a constant expression if we check later.
8903       var->checkInitIsICE();
8904     }
8905   }
8906 
8907   // Require the destructor.
8908   if (const RecordType *recordType = baseType->getAs<RecordType>())
8909     FinalizeVarWithDestructor(var, recordType);
8910 }
8911 
8912 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8913 /// any semantic actions necessary after any initializer has been attached.
8914 void
8915 Sema::FinalizeDeclaration(Decl *ThisDecl) {
8916   // Note that we are no longer parsing the initializer for this declaration.
8917   ParsingInitForAutoVars.erase(ThisDecl);
8918 
8919   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
8920   if (!VD)
8921     return;
8922 
8923   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8924     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8925       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
8926       VD->dropAttr<UsedAttr>();
8927     }
8928   }
8929 
8930   if (!VD->isInvalidDecl() &&
8931       VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8932     if (const VarDecl *Def = VD->getDefinition()) {
8933       if (Def->hasAttr<AliasAttr>()) {
8934         Diag(VD->getLocation(), diag::err_tentative_after_alias)
8935             << VD->getDeclName();
8936         Diag(Def->getLocation(), diag::note_previous_definition);
8937         VD->setInvalidDecl();
8938       }
8939     }
8940   }
8941 
8942   const DeclContext *DC = VD->getDeclContext();
8943   // If there's a #pragma GCC visibility in scope, and this isn't a class
8944   // member, set the visibility of this variable.
8945   if (!DC->isRecord() && VD->isExternallyVisible())
8946     AddPushedVisibilityAttribute(VD);
8947 
8948   if (VD->isFileVarDecl())
8949     MarkUnusedFileScopedDecl(VD);
8950 
8951   // Now we have parsed the initializer and can update the table of magic
8952   // tag values.
8953   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8954       !VD->getType()->isIntegralOrEnumerationType())
8955     return;
8956 
8957   for (specific_attr_iterator<TypeTagForDatatypeAttr>
8958          I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8959          E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8960        I != E; ++I) {
8961     const Expr *MagicValueExpr = VD->getInit();
8962     if (!MagicValueExpr) {
8963       continue;
8964     }
8965     llvm::APSInt MagicValueInt;
8966     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8967       Diag(I->getRange().getBegin(),
8968            diag::err_type_tag_for_datatype_not_ice)
8969         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8970       continue;
8971     }
8972     if (MagicValueInt.getActiveBits() > 64) {
8973       Diag(I->getRange().getBegin(),
8974            diag::err_type_tag_for_datatype_too_large)
8975         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8976       continue;
8977     }
8978     uint64_t MagicValue = MagicValueInt.getZExtValue();
8979     RegisterTypeTagForDatatype(I->getArgumentKind(),
8980                                MagicValue,
8981                                I->getMatchingCType(),
8982                                I->getLayoutCompatible(),
8983                                I->getMustBeNull());
8984   }
8985 }
8986 
8987 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8988                                                    ArrayRef<Decl *> Group) {
8989   SmallVector<Decl*, 8> Decls;
8990 
8991   if (DS.isTypeSpecOwned())
8992     Decls.push_back(DS.getRepAsDecl());
8993 
8994   DeclaratorDecl *FirstDeclaratorInGroup = 0;
8995   for (unsigned i = 0, e = Group.size(); i != e; ++i)
8996     if (Decl *D = Group[i]) {
8997       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8998         if (!FirstDeclaratorInGroup)
8999           FirstDeclaratorInGroup = DD;
9000       Decls.push_back(D);
9001     }
9002 
9003   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
9004     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
9005       HandleTagNumbering(*this, Tag);
9006       if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
9007         Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
9008     }
9009   }
9010 
9011   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
9012 }
9013 
9014 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
9015 /// group, performing any necessary semantic checking.
9016 Sema::DeclGroupPtrTy
9017 Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
9018                            bool TypeMayContainAuto) {
9019   // C++0x [dcl.spec.auto]p7:
9020   //   If the type deduced for the template parameter U is not the same in each
9021   //   deduction, the program is ill-formed.
9022   // FIXME: When initializer-list support is added, a distinction is needed
9023   // between the deduced type U and the deduced type which 'auto' stands for.
9024   //   auto a = 0, b = { 1, 2, 3 };
9025   // is legal because the deduced type U is 'int' in both cases.
9026   if (TypeMayContainAuto && Group.size() > 1) {
9027     QualType Deduced;
9028     CanQualType DeducedCanon;
9029     VarDecl *DeducedDecl = 0;
9030     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
9031       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
9032         AutoType *AT = D->getType()->getContainedAutoType();
9033         // Don't reissue diagnostics when instantiating a template.
9034         if (AT && D->isInvalidDecl())
9035           break;
9036         QualType U = AT ? AT->getDeducedType() : QualType();
9037         if (!U.isNull()) {
9038           CanQualType UCanon = Context.getCanonicalType(U);
9039           if (Deduced.isNull()) {
9040             Deduced = U;
9041             DeducedCanon = UCanon;
9042             DeducedDecl = D;
9043           } else if (DeducedCanon != UCanon) {
9044             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9045                  diag::err_auto_different_deductions)
9046               << (AT->isDecltypeAuto() ? 1 : 0)
9047               << Deduced << DeducedDecl->getDeclName()
9048               << U << D->getDeclName()
9049               << DeducedDecl->getInit()->getSourceRange()
9050               << D->getInit()->getSourceRange();
9051             D->setInvalidDecl();
9052             break;
9053           }
9054         }
9055       }
9056     }
9057   }
9058 
9059   ActOnDocumentableDecls(Group);
9060 
9061   return DeclGroupPtrTy::make(
9062       DeclGroupRef::Create(Context, Group.data(), Group.size()));
9063 }
9064 
9065 void Sema::ActOnDocumentableDecl(Decl *D) {
9066   ActOnDocumentableDecls(D);
9067 }
9068 
9069 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9070   // Don't parse the comment if Doxygen diagnostics are ignored.
9071   if (Group.empty() || !Group[0])
9072    return;
9073 
9074   if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9075                                Group[0]->getLocation())
9076         == DiagnosticsEngine::Ignored)
9077     return;
9078 
9079   if (Group.size() >= 2) {
9080     // This is a decl group.  Normally it will contain only declarations
9081     // produced from declarator list.  But in case we have any definitions or
9082     // additional declaration references:
9083     //   'typedef struct S {} S;'
9084     //   'typedef struct S *S;'
9085     //   'struct S *pS;'
9086     // FinalizeDeclaratorGroup adds these as separate declarations.
9087     Decl *MaybeTagDecl = Group[0];
9088     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9089       Group = Group.slice(1);
9090     }
9091   }
9092 
9093   // See if there are any new comments that are not attached to a decl.
9094   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9095   if (!Comments.empty() &&
9096       !Comments.back()->isAttached()) {
9097     // There is at least one comment that not attached to a decl.
9098     // Maybe it should be attached to one of these decls?
9099     //
9100     // Note that this way we pick up not only comments that precede the
9101     // declaration, but also comments that *follow* the declaration -- thanks to
9102     // the lookahead in the lexer: we've consumed the semicolon and looked
9103     // ahead through comments.
9104     for (unsigned i = 0, e = Group.size(); i != e; ++i)
9105       Context.getCommentForDecl(Group[i], &PP);
9106   }
9107 }
9108 
9109 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9110 /// to introduce parameters into function prototype scope.
9111 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9112   const DeclSpec &DS = D.getDeclSpec();
9113 
9114   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9115 
9116   // C++03 [dcl.stc]p2 also permits 'auto'.
9117   VarDecl::StorageClass StorageClass = SC_None;
9118   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9119     StorageClass = SC_Register;
9120   } else if (getLangOpts().CPlusPlus &&
9121              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9122     StorageClass = SC_Auto;
9123   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9124     Diag(DS.getStorageClassSpecLoc(),
9125          diag::err_invalid_storage_class_in_func_decl);
9126     D.getMutableDeclSpec().ClearStorageClassSpecs();
9127   }
9128 
9129   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9130     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9131       << DeclSpec::getSpecifierName(TSCS);
9132   if (DS.isConstexprSpecified())
9133     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9134       << 0;
9135 
9136   DiagnoseFunctionSpecifiers(DS);
9137 
9138   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9139   QualType parmDeclType = TInfo->getType();
9140 
9141   if (getLangOpts().CPlusPlus) {
9142     // Check that there are no default arguments inside the type of this
9143     // parameter.
9144     CheckExtraCXXDefaultArguments(D);
9145 
9146     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9147     if (D.getCXXScopeSpec().isSet()) {
9148       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9149         << D.getCXXScopeSpec().getRange();
9150       D.getCXXScopeSpec().clear();
9151     }
9152   }
9153 
9154   // Ensure we have a valid name
9155   IdentifierInfo *II = 0;
9156   if (D.hasName()) {
9157     II = D.getIdentifier();
9158     if (!II) {
9159       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9160         << GetNameForDeclarator(D).getName();
9161       D.setInvalidType(true);
9162     }
9163   }
9164 
9165   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9166   if (II) {
9167     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9168                    ForRedeclaration);
9169     LookupName(R, S);
9170     if (R.isSingleResult()) {
9171       NamedDecl *PrevDecl = R.getFoundDecl();
9172       if (PrevDecl->isTemplateParameter()) {
9173         // Maybe we will complain about the shadowed template parameter.
9174         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9175         // Just pretend that we didn't see the previous declaration.
9176         PrevDecl = 0;
9177       } else if (S->isDeclScope(PrevDecl)) {
9178         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9179         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9180 
9181         // Recover by removing the name
9182         II = 0;
9183         D.SetIdentifier(0, D.getIdentifierLoc());
9184         D.setInvalidType(true);
9185       }
9186     }
9187   }
9188 
9189   // Temporarily put parameter variables in the translation unit, not
9190   // the enclosing context.  This prevents them from accidentally
9191   // looking like class members in C++.
9192   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9193                                     D.getLocStart(),
9194                                     D.getIdentifierLoc(), II,
9195                                     parmDeclType, TInfo,
9196                                     StorageClass);
9197 
9198   if (D.isInvalidType())
9199     New->setInvalidDecl();
9200 
9201   assert(S->isFunctionPrototypeScope());
9202   assert(S->getFunctionPrototypeDepth() >= 1);
9203   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9204                     S->getNextFunctionPrototypeIndex());
9205 
9206   // Add the parameter declaration into this scope.
9207   S->AddDecl(New);
9208   if (II)
9209     IdResolver.AddDecl(New);
9210 
9211   ProcessDeclAttributes(S, New, D);
9212 
9213   if (D.getDeclSpec().isModulePrivateSpecified())
9214     Diag(New->getLocation(), diag::err_module_private_local)
9215       << 1 << New->getDeclName()
9216       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9217       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9218 
9219   if (New->hasAttr<BlocksAttr>()) {
9220     Diag(New->getLocation(), diag::err_block_on_nonlocal);
9221   }
9222   return New;
9223 }
9224 
9225 /// \brief Synthesizes a variable for a parameter arising from a
9226 /// typedef.
9227 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9228                                               SourceLocation Loc,
9229                                               QualType T) {
9230   /* FIXME: setting StartLoc == Loc.
9231      Would it be worth to modify callers so as to provide proper source
9232      location for the unnamed parameters, embedding the parameter's type? */
9233   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
9234                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
9235                                            SC_None, 0);
9236   Param->setImplicit();
9237   return Param;
9238 }
9239 
9240 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9241                                     ParmVarDecl * const *ParamEnd) {
9242   // Don't diagnose unused-parameter errors in template instantiations; we
9243   // will already have done so in the template itself.
9244   if (!ActiveTemplateInstantiations.empty())
9245     return;
9246 
9247   for (; Param != ParamEnd; ++Param) {
9248     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9249         !(*Param)->hasAttr<UnusedAttr>()) {
9250       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9251         << (*Param)->getDeclName();
9252     }
9253   }
9254 }
9255 
9256 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9257                                                   ParmVarDecl * const *ParamEnd,
9258                                                   QualType ReturnTy,
9259                                                   NamedDecl *D) {
9260   if (LangOpts.NumLargeByValueCopy == 0) // No check.
9261     return;
9262 
9263   // Warn if the return value is pass-by-value and larger than the specified
9264   // threshold.
9265   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9266     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9267     if (Size > LangOpts.NumLargeByValueCopy)
9268       Diag(D->getLocation(), diag::warn_return_value_size)
9269           << D->getDeclName() << Size;
9270   }
9271 
9272   // Warn if any parameter is pass-by-value and larger than the specified
9273   // threshold.
9274   for (; Param != ParamEnd; ++Param) {
9275     QualType T = (*Param)->getType();
9276     if (T->isDependentType() || !T.isPODType(Context))
9277       continue;
9278     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9279     if (Size > LangOpts.NumLargeByValueCopy)
9280       Diag((*Param)->getLocation(), diag::warn_parameter_size)
9281           << (*Param)->getDeclName() << Size;
9282   }
9283 }
9284 
9285 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9286                                   SourceLocation NameLoc, IdentifierInfo *Name,
9287                                   QualType T, TypeSourceInfo *TSInfo,
9288                                   VarDecl::StorageClass StorageClass) {
9289   // In ARC, infer a lifetime qualifier for appropriate parameter types.
9290   if (getLangOpts().ObjCAutoRefCount &&
9291       T.getObjCLifetime() == Qualifiers::OCL_None &&
9292       T->isObjCLifetimeType()) {
9293 
9294     Qualifiers::ObjCLifetime lifetime;
9295 
9296     // Special cases for arrays:
9297     //   - if it's const, use __unsafe_unretained
9298     //   - otherwise, it's an error
9299     if (T->isArrayType()) {
9300       if (!T.isConstQualified()) {
9301         DelayedDiagnostics.add(
9302             sema::DelayedDiagnostic::makeForbiddenType(
9303             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9304       }
9305       lifetime = Qualifiers::OCL_ExplicitNone;
9306     } else {
9307       lifetime = T->getObjCARCImplicitLifetime();
9308     }
9309     T = Context.getLifetimeQualifiedType(T, lifetime);
9310   }
9311 
9312   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9313                                          Context.getAdjustedParameterType(T),
9314                                          TSInfo,
9315                                          StorageClass, 0);
9316 
9317   // Parameters can not be abstract class types.
9318   // For record types, this is done by the AbstractClassUsageDiagnoser once
9319   // the class has been completely parsed.
9320   if (!CurContext->isRecord() &&
9321       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9322                              AbstractParamType))
9323     New->setInvalidDecl();
9324 
9325   // Parameter declarators cannot be interface types. All ObjC objects are
9326   // passed by reference.
9327   if (T->isObjCObjectType()) {
9328     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9329     Diag(NameLoc,
9330          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9331       << FixItHint::CreateInsertion(TypeEndLoc, "*");
9332     T = Context.getObjCObjectPointerType(T);
9333     New->setType(T);
9334   }
9335 
9336   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9337   // duration shall not be qualified by an address-space qualifier."
9338   // Since all parameters have automatic store duration, they can not have
9339   // an address space.
9340   if (T.getAddressSpace() != 0) {
9341     Diag(NameLoc, diag::err_arg_with_address_space);
9342     New->setInvalidDecl();
9343   }
9344 
9345   return New;
9346 }
9347 
9348 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9349                                            SourceLocation LocAfterDecls) {
9350   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9351 
9352   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9353   // for a K&R function.
9354   if (!FTI.hasPrototype) {
9355     for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9356       --i;
9357       if (FTI.ArgInfo[i].Param == 0) {
9358         SmallString<256> Code;
9359         llvm::raw_svector_ostream(Code) << "  int "
9360                                         << FTI.ArgInfo[i].Ident->getName()
9361                                         << ";\n";
9362         Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
9363           << FTI.ArgInfo[i].Ident
9364           << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9365 
9366         // Implicitly declare the argument as type 'int' for lack of a better
9367         // type.
9368         AttributeFactory attrs;
9369         DeclSpec DS(attrs);
9370         const char* PrevSpec; // unused
9371         unsigned DiagID; // unused
9372         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
9373                            PrevSpec, DiagID, Context.getPrintingPolicy());
9374         // Use the identifier location for the type source range.
9375         DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9376         DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
9377         Declarator ParamD(DS, Declarator::KNRTypeListContext);
9378         ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
9379         FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
9380       }
9381     }
9382   }
9383 }
9384 
9385 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9386   assert(getCurFunctionDecl() == 0 && "Function parsing confused");
9387   assert(D.isFunctionDeclarator() && "Not a function declarator!");
9388   Scope *ParentScope = FnBodyScope->getParent();
9389 
9390   D.setFunctionDefinitionKind(FDK_Definition);
9391   Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9392   return ActOnStartOfFunctionDef(FnBodyScope, DP);
9393 }
9394 
9395 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9396                              const FunctionDecl*& PossibleZeroParamPrototype) {
9397   // Don't warn about invalid declarations.
9398   if (FD->isInvalidDecl())
9399     return false;
9400 
9401   // Or declarations that aren't global.
9402   if (!FD->isGlobal())
9403     return false;
9404 
9405   // Don't warn about C++ member functions.
9406   if (isa<CXXMethodDecl>(FD))
9407     return false;
9408 
9409   // Don't warn about 'main'.
9410   if (FD->isMain())
9411     return false;
9412 
9413   // Don't warn about inline functions.
9414   if (FD->isInlined())
9415     return false;
9416 
9417   // Don't warn about function templates.
9418   if (FD->getDescribedFunctionTemplate())
9419     return false;
9420 
9421   // Don't warn about function template specializations.
9422   if (FD->isFunctionTemplateSpecialization())
9423     return false;
9424 
9425   // Don't warn for OpenCL kernels.
9426   if (FD->hasAttr<OpenCLKernelAttr>())
9427     return false;
9428 
9429   bool MissingPrototype = true;
9430   for (const FunctionDecl *Prev = FD->getPreviousDecl();
9431        Prev; Prev = Prev->getPreviousDecl()) {
9432     // Ignore any declarations that occur in function or method
9433     // scope, because they aren't visible from the header.
9434     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9435       continue;
9436 
9437     MissingPrototype = !Prev->getType()->isFunctionProtoType();
9438     if (FD->getNumParams() == 0)
9439       PossibleZeroParamPrototype = Prev;
9440     break;
9441   }
9442 
9443   return MissingPrototype;
9444 }
9445 
9446 void
9447 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9448                                    const FunctionDecl *EffectiveDefinition) {
9449   // Don't complain if we're in GNU89 mode and the previous definition
9450   // was an extern inline function.
9451   const FunctionDecl *Definition = EffectiveDefinition;
9452   if (!Definition)
9453     if (!FD->isDefined(Definition))
9454       return;
9455 
9456   if (canRedefineFunction(Definition, getLangOpts()))
9457     return;
9458 
9459   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9460       Definition->getStorageClass() == SC_Extern)
9461     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9462         << FD->getDeclName() << getLangOpts().CPlusPlus;
9463   else
9464     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9465 
9466   Diag(Definition->getLocation(), diag::note_previous_definition);
9467   FD->setInvalidDecl();
9468 }
9469 
9470 
9471 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9472                                    Sema &S) {
9473   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9474 
9475   LambdaScopeInfo *LSI = S.PushLambdaScope();
9476   LSI->CallOperator = CallOperator;
9477   LSI->Lambda = LambdaClass;
9478   LSI->ReturnType = CallOperator->getResultType();
9479   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9480 
9481   if (LCD == LCD_None)
9482     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9483   else if (LCD == LCD_ByCopy)
9484     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9485   else if (LCD == LCD_ByRef)
9486     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9487   DeclarationNameInfo DNI = CallOperator->getNameInfo();
9488 
9489   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9490   LSI->Mutable = !CallOperator->isConst();
9491 
9492   // Add the captures to the LSI so they can be noted as already
9493   // captured within tryCaptureVar.
9494   for (LambdaExpr::capture_iterator C = LambdaClass->captures_begin(),
9495       CEnd = LambdaClass->captures_end(); C != CEnd; ++C) {
9496     if (C->capturesVariable()) {
9497       VarDecl *VD = C->getCapturedVar();
9498       if (VD->isInitCapture())
9499         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
9500       QualType CaptureType = VD->getType();
9501       const bool ByRef = C->getCaptureKind() == LCK_ByRef;
9502       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
9503           /*RefersToEnclosingLocal*/true, C->getLocation(),
9504           /*EllipsisLoc*/C->isPackExpansion()
9505                          ? C->getEllipsisLoc() : SourceLocation(),
9506           CaptureType, /*Expr*/ 0);
9507 
9508     } else if (C->capturesThis()) {
9509       LSI->addThisCapture(/*Nested*/ false, C->getLocation(),
9510                               S.getCurrentThisType(), /*Expr*/ 0);
9511     }
9512   }
9513 }
9514 
9515 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9516   // Clear the last template instantiation error context.
9517   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9518 
9519   if (!D)
9520     return D;
9521   FunctionDecl *FD = 0;
9522 
9523   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9524     FD = FunTmpl->getTemplatedDecl();
9525   else
9526     FD = cast<FunctionDecl>(D);
9527   // If we are instantiating a generic lambda call operator, push
9528   // a LambdaScopeInfo onto the function stack.  But use the information
9529   // that's already been calculated (ActOnLambdaExpr) to prime the current
9530   // LambdaScopeInfo.
9531   // When the template operator is being specialized, the LambdaScopeInfo,
9532   // has to be properly restored so that tryCaptureVariable doesn't try
9533   // and capture any new variables. In addition when calculating potential
9534   // captures during transformation of nested lambdas, it is necessary to
9535   // have the LSI properly restored.
9536   if (isGenericLambdaCallOperatorSpecialization(FD)) {
9537     assert(ActiveTemplateInstantiations.size() &&
9538       "There should be an active template instantiation on the stack "
9539       "when instantiating a generic lambda!");
9540     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
9541   }
9542   else
9543     // Enter a new function scope
9544     PushFunctionScope();
9545 
9546   // See if this is a redefinition.
9547   if (!FD->isLateTemplateParsed())
9548     CheckForFunctionRedefinition(FD);
9549 
9550   // Builtin functions cannot be defined.
9551   if (unsigned BuiltinID = FD->getBuiltinID()) {
9552     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9553         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9554       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9555       FD->setInvalidDecl();
9556     }
9557   }
9558 
9559   // The return type of a function definition must be complete
9560   // (C99 6.9.1p3, C++ [dcl.fct]p6).
9561   QualType ResultType = FD->getResultType();
9562   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9563       !FD->isInvalidDecl() &&
9564       RequireCompleteType(FD->getLocation(), ResultType,
9565                           diag::err_func_def_incomplete_result))
9566     FD->setInvalidDecl();
9567 
9568   // GNU warning -Wmissing-prototypes:
9569   //   Warn if a global function is defined without a previous
9570   //   prototype declaration. This warning is issued even if the
9571   //   definition itself provides a prototype. The aim is to detect
9572   //   global functions that fail to be declared in header files.
9573   const FunctionDecl *PossibleZeroParamPrototype = 0;
9574   if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9575     Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9576 
9577     if (PossibleZeroParamPrototype) {
9578       // We found a declaration that is not a prototype,
9579       // but that could be a zero-parameter prototype
9580       if (TypeSourceInfo *TI =
9581               PossibleZeroParamPrototype->getTypeSourceInfo()) {
9582         TypeLoc TL = TI->getTypeLoc();
9583         if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9584           Diag(PossibleZeroParamPrototype->getLocation(),
9585                diag::note_declaration_not_a_prototype)
9586             << PossibleZeroParamPrototype
9587             << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9588       }
9589     }
9590   }
9591 
9592   if (FnBodyScope)
9593     PushDeclContext(FnBodyScope, FD);
9594 
9595   // Check the validity of our function parameters
9596   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9597                            /*CheckParameterNames=*/true);
9598 
9599   // Introduce our parameters into the function scope
9600   for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9601     ParmVarDecl *Param = FD->getParamDecl(p);
9602     Param->setOwningFunction(FD);
9603 
9604     // If this has an identifier, add it to the scope stack.
9605     if (Param->getIdentifier() && FnBodyScope) {
9606       CheckShadow(FnBodyScope, Param);
9607 
9608       PushOnScopeChains(Param, FnBodyScope);
9609     }
9610   }
9611 
9612   // If we had any tags defined in the function prototype,
9613   // introduce them into the function scope.
9614   if (FnBodyScope) {
9615     for (ArrayRef<NamedDecl *>::iterator
9616              I = FD->getDeclsInPrototypeScope().begin(),
9617              E = FD->getDeclsInPrototypeScope().end();
9618          I != E; ++I) {
9619       NamedDecl *D = *I;
9620 
9621       // Some of these decls (like enums) may have been pinned to the translation unit
9622       // for lack of a real context earlier. If so, remove from the translation unit
9623       // and reattach to the current context.
9624       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9625         // Is the decl actually in the context?
9626         for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9627                DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9628           if (*DI == D) {
9629             Context.getTranslationUnitDecl()->removeDecl(D);
9630             break;
9631           }
9632         }
9633         // Either way, reassign the lexical decl context to our FunctionDecl.
9634         D->setLexicalDeclContext(CurContext);
9635       }
9636 
9637       // If the decl has a non-null name, make accessible in the current scope.
9638       if (!D->getName().empty())
9639         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9640 
9641       // Similarly, dive into enums and fish their constants out, making them
9642       // accessible in this scope.
9643       if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9644         for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9645                EE = ED->enumerator_end(); EI != EE; ++EI)
9646           PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
9647       }
9648     }
9649   }
9650 
9651   // Ensure that the function's exception specification is instantiated.
9652   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9653     ResolveExceptionSpec(D->getLocation(), FPT);
9654 
9655   // Checking attributes of current function definition
9656   // dllimport attribute.
9657   DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9658   if (DA && (!FD->hasAttr<DLLExportAttr>())) {
9659     // dllimport attribute cannot be directly applied to definition.
9660     // Microsoft accepts dllimport for functions defined within class scope.
9661     if (!DA->isInherited() &&
9662         !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
9663       Diag(FD->getLocation(),
9664            diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9665         << DA;
9666       FD->setInvalidDecl();
9667       return D;
9668     }
9669 
9670     // Visual C++ appears to not think this is an issue, so only issue
9671     // a warning when Microsoft extensions are disabled.
9672     if (!LangOpts.MicrosoftExt) {
9673       // If a symbol previously declared dllimport is later defined, the
9674       // attribute is ignored in subsequent references, and a warning is
9675       // emitted.
9676       Diag(FD->getLocation(),
9677            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
9678         << FD << DA;
9679     }
9680   }
9681   // We want to attach documentation to original Decl (which might be
9682   // a function template).
9683   ActOnDocumentableDecl(D);
9684   return D;
9685 }
9686 
9687 /// \brief Given the set of return statements within a function body,
9688 /// compute the variables that are subject to the named return value
9689 /// optimization.
9690 ///
9691 /// Each of the variables that is subject to the named return value
9692 /// optimization will be marked as NRVO variables in the AST, and any
9693 /// return statement that has a marked NRVO variable as its NRVO candidate can
9694 /// use the named return value optimization.
9695 ///
9696 /// This function applies a very simplistic algorithm for NRVO: if every return
9697 /// statement in the function has the same NRVO candidate, that candidate is
9698 /// the NRVO variable.
9699 ///
9700 /// FIXME: Employ a smarter algorithm that accounts for multiple return
9701 /// statements and the lifetimes of the NRVO candidates. We should be able to
9702 /// find a maximal set of NRVO variables.
9703 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9704   ReturnStmt **Returns = Scope->Returns.data();
9705 
9706   const VarDecl *NRVOCandidate = 0;
9707   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9708     if (!Returns[I]->getNRVOCandidate())
9709       return;
9710 
9711     if (!NRVOCandidate)
9712       NRVOCandidate = Returns[I]->getNRVOCandidate();
9713     else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9714       return;
9715   }
9716 
9717   if (NRVOCandidate)
9718     const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9719 }
9720 
9721 bool Sema::canSkipFunctionBody(Decl *D) {
9722   if (!Consumer.shouldSkipFunctionBody(D))
9723     return false;
9724 
9725   if (isa<ObjCMethodDecl>(D))
9726     return true;
9727 
9728   FunctionDecl *FD = 0;
9729   if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9730     FD = FTD->getTemplatedDecl();
9731   else
9732     FD = cast<FunctionDecl>(D);
9733 
9734   // We cannot skip the body of a function (or function template) which is
9735   // constexpr, since we may need to evaluate its body in order to parse the
9736   // rest of the file.
9737   // We cannot skip the body of a function with an undeduced return type,
9738   // because any callers of that function need to know the type.
9739   return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
9740 }
9741 
9742 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9743   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9744     FD->setHasSkippedBody();
9745   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9746     MD->setHasSkippedBody();
9747   return ActOnFinishFunctionBody(Decl, 0);
9748 }
9749 
9750 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
9751   return ActOnFinishFunctionBody(D, BodyArg, false);
9752 }
9753 
9754 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9755                                     bool IsInstantiation) {
9756   FunctionDecl *FD = 0;
9757   FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9758   if (FunTmpl)
9759     FD = FunTmpl->getTemplatedDecl();
9760   else
9761     FD = dyn_cast_or_null<FunctionDecl>(dcl);
9762 
9763   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
9764   sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
9765 
9766   if (FD) {
9767     FD->setBody(Body);
9768 
9769     if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9770         !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9771       // If the function has a deduced result type but contains no 'return'
9772       // statements, the result type as written must be exactly 'auto', and
9773       // the deduced result type is 'void'.
9774       if (!FD->getResultType()->getAs<AutoType>()) {
9775         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9776           << FD->getResultType();
9777         FD->setInvalidDecl();
9778       } else {
9779         // Substitute 'void' for the 'auto' in the type.
9780         TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9781             IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9782         Context.adjustDeducedFunctionResultType(
9783             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
9784       }
9785     }
9786 
9787     // The only way to be included in UndefinedButUsed is if there is an
9788     // ODR use before the definition. Avoid the expensive map lookup if this
9789     // is the first declaration.
9790     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
9791       if (!FD->isExternallyVisible())
9792         UndefinedButUsed.erase(FD);
9793       else if (FD->isInlined() &&
9794                (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9795                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9796         UndefinedButUsed.erase(FD);
9797     }
9798 
9799     // If the function implicitly returns zero (like 'main') or is naked,
9800     // don't complain about missing return statements.
9801     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
9802       WP.disableCheckFallThrough();
9803 
9804     // MSVC permits the use of pure specifier (=0) on function definition,
9805     // defined at class scope, warn about this non-standard construct.
9806     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
9807       Diag(FD->getLocation(), diag::warn_pure_function_definition);
9808 
9809     if (!FD->isInvalidDecl()) {
9810       DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
9811       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9812                                              FD->getResultType(), FD);
9813 
9814       // If this is a constructor, we need a vtable.
9815       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9816         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
9817 
9818       // Try to apply the named return value optimization. We have to check
9819       // if we can do this here because lambdas keep return statements around
9820       // to deduce an implicit return type.
9821       if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9822           !FD->isDependentContext())
9823         computeNRVO(Body, getCurFunction());
9824     }
9825 
9826     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9827            "Function parsing confused");
9828   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
9829     assert(MD == getCurMethodDecl() && "Method parsing confused");
9830     MD->setBody(Body);
9831     if (!MD->isInvalidDecl()) {
9832       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
9833       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9834                                              MD->getResultType(), MD);
9835 
9836       if (Body)
9837         computeNRVO(Body, getCurFunction());
9838     }
9839     if (getCurFunction()->ObjCShouldCallSuper) {
9840       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9841         << MD->getSelector().getAsString();
9842       getCurFunction()->ObjCShouldCallSuper = false;
9843     }
9844     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
9845       const ObjCMethodDecl *InitMethod = 0;
9846       bool isDesignated =
9847           MD->isDesignatedInitializerForTheInterface(&InitMethod);
9848       assert(isDesignated && InitMethod);
9849       (void)isDesignated;
9850       Diag(MD->getLocation(),
9851            diag::warn_objc_designated_init_missing_super_call);
9852       Diag(InitMethod->getLocation(),
9853            diag::note_objc_designated_init_marked_here);
9854       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
9855     }
9856     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
9857       Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call);
9858       getCurFunction()->ObjCWarnForNoInitDelegation = false;
9859     }
9860   } else {
9861     return 0;
9862   }
9863 
9864   assert(!getCurFunction()->ObjCShouldCallSuper &&
9865          "This should only be set for ObjC methods, which should have been "
9866          "handled in the block above.");
9867 
9868   // Verify and clean out per-function state.
9869   if (Body) {
9870     // C++ constructors that have function-try-blocks can't have return
9871     // statements in the handlers of that block. (C++ [except.handle]p14)
9872     // Verify this.
9873     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9874       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9875 
9876     // Verify that gotos and switch cases don't jump into scopes illegally.
9877     if (getCurFunction()->NeedsScopeChecking() &&
9878         !dcl->isInvalidDecl() &&
9879         !hasAnyUnrecoverableErrorsInThisFunction() &&
9880         !PP.isCodeCompletionEnabled())
9881       DiagnoseInvalidJumps(Body);
9882 
9883     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9884       if (!Destructor->getParent()->isDependentType())
9885         CheckDestructor(Destructor);
9886 
9887       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9888                                              Destructor->getParent());
9889     }
9890 
9891     // If any errors have occurred, clear out any temporaries that may have
9892     // been leftover. This ensures that these temporaries won't be picked up for
9893     // deletion in some later function.
9894     if (PP.getDiagnostics().hasErrorOccurred() ||
9895         PP.getDiagnostics().getSuppressAllDiagnostics()) {
9896       DiscardCleanupsInEvaluationContext();
9897     }
9898     if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9899         !isa<FunctionTemplateDecl>(dcl)) {
9900       // Since the body is valid, issue any analysis-based warnings that are
9901       // enabled.
9902       ActivePolicy = &WP;
9903     }
9904 
9905     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9906         (!CheckConstexprFunctionDecl(FD) ||
9907          !CheckConstexprFunctionBody(FD, Body)))
9908       FD->setInvalidDecl();
9909 
9910     assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
9911     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
9912     assert(MaybeODRUseExprs.empty() &&
9913            "Leftover expressions for odr-use checking");
9914   }
9915 
9916   if (!IsInstantiation)
9917     PopDeclContext();
9918 
9919   PopFunctionScopeInfo(ActivePolicy, dcl);
9920   // If any errors have occurred, clear out any temporaries that may have
9921   // been leftover. This ensures that these temporaries won't be picked up for
9922   // deletion in some later function.
9923   if (getDiagnostics().hasErrorOccurred()) {
9924     DiscardCleanupsInEvaluationContext();
9925   }
9926 
9927   return dcl;
9928 }
9929 
9930 
9931 /// When we finish delayed parsing of an attribute, we must attach it to the
9932 /// relevant Decl.
9933 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9934                                        ParsedAttributes &Attrs) {
9935   // Always attach attributes to the underlying decl.
9936   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9937     D = TD->getTemplatedDecl();
9938   ProcessDeclAttributeList(S, D, Attrs.getList());
9939 
9940   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9941     if (Method->isStatic())
9942       checkThisInStaticMemberFunctionAttributes(Method);
9943 }
9944 
9945 
9946 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9947 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
9948 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
9949                                           IdentifierInfo &II, Scope *S) {
9950   // Before we produce a declaration for an implicitly defined
9951   // function, see whether there was a locally-scoped declaration of
9952   // this name as a function or variable. If so, use that
9953   // (non-visible) declaration, and complain about it.
9954   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9955     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9956     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9957     return ExternCPrev;
9958   }
9959 
9960   // Extension in C99.  Legal in C90, but warn about it.
9961   unsigned diag_id;
9962   if (II.getName().startswith("__builtin_"))
9963     diag_id = diag::warn_builtin_unknown;
9964   else if (getLangOpts().C99)
9965     diag_id = diag::ext_implicit_function_decl;
9966   else
9967     diag_id = diag::warn_implicit_function_decl;
9968   Diag(Loc, diag_id) << &II;
9969 
9970   // Because typo correction is expensive, only do it if the implicit
9971   // function declaration is going to be treated as an error.
9972   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9973     TypoCorrection Corrected;
9974     DeclFilterCCC<FunctionDecl> Validator;
9975     if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
9976                                       LookupOrdinaryName, S, 0, Validator)))
9977       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9978                    /*ErrorRecovery*/false);
9979   }
9980 
9981   // Set a Declarator for the implicit definition: int foo();
9982   const char *Dummy;
9983   AttributeFactory attrFactory;
9984   DeclSpec DS(attrFactory);
9985   unsigned DiagID;
9986   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
9987                                   Context.getPrintingPolicy());
9988   (void)Error; // Silence warning.
9989   assert(!Error && "Error setting up implicit decl!");
9990   SourceLocation NoLoc;
9991   Declarator D(DS, Declarator::BlockContext);
9992   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9993                                              /*IsAmbiguous=*/false,
9994                                              /*RParenLoc=*/NoLoc,
9995                                              /*ArgInfo=*/0,
9996                                              /*NumArgs=*/0,
9997                                              /*EllipsisLoc=*/NoLoc,
9998                                              /*RParenLoc=*/NoLoc,
9999                                              /*TypeQuals=*/0,
10000                                              /*RefQualifierIsLvalueRef=*/true,
10001                                              /*RefQualifierLoc=*/NoLoc,
10002                                              /*ConstQualifierLoc=*/NoLoc,
10003                                              /*VolatileQualifierLoc=*/NoLoc,
10004                                              /*MutableLoc=*/NoLoc,
10005                                              EST_None,
10006                                              /*ESpecLoc=*/NoLoc,
10007                                              /*Exceptions=*/0,
10008                                              /*ExceptionRanges=*/0,
10009                                              /*NumExceptions=*/0,
10010                                              /*NoexceptExpr=*/0,
10011                                              Loc, Loc, D),
10012                 DS.getAttributes(),
10013                 SourceLocation());
10014   D.SetIdentifier(&II, Loc);
10015 
10016   // Insert this function into translation-unit scope.
10017 
10018   DeclContext *PrevDC = CurContext;
10019   CurContext = Context.getTranslationUnitDecl();
10020 
10021   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
10022   FD->setImplicit();
10023 
10024   CurContext = PrevDC;
10025 
10026   AddKnownFunctionAttributes(FD);
10027 
10028   return FD;
10029 }
10030 
10031 /// \brief Adds any function attributes that we know a priori based on
10032 /// the declaration of this function.
10033 ///
10034 /// These attributes can apply both to implicitly-declared builtins
10035 /// (like __builtin___printf_chk) or to library-declared functions
10036 /// like NSLog or printf.
10037 ///
10038 /// We need to check for duplicate attributes both here and where user-written
10039 /// attributes are applied to declarations.
10040 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
10041   if (FD->isInvalidDecl())
10042     return;
10043 
10044   // If this is a built-in function, map its builtin attributes to
10045   // actual attributes.
10046   if (unsigned BuiltinID = FD->getBuiltinID()) {
10047     // Handle printf-formatting attributes.
10048     unsigned FormatIdx;
10049     bool HasVAListArg;
10050     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
10051       if (!FD->hasAttr<FormatAttr>()) {
10052         const char *fmt = "printf";
10053         unsigned int NumParams = FD->getNumParams();
10054         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
10055             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
10056           fmt = "NSString";
10057         FD->addAttr(FormatAttr::CreateImplicit(Context,
10058                                                &Context.Idents.get(fmt),
10059                                                FormatIdx+1,
10060                                                HasVAListArg ? 0 : FormatIdx+2,
10061                                                FD->getLocation()));
10062       }
10063     }
10064     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
10065                                              HasVAListArg)) {
10066      if (!FD->hasAttr<FormatAttr>())
10067        FD->addAttr(FormatAttr::CreateImplicit(Context,
10068                                               &Context.Idents.get("scanf"),
10069                                               FormatIdx+1,
10070                                               HasVAListArg ? 0 : FormatIdx+2,
10071                                               FD->getLocation()));
10072     }
10073 
10074     // Mark const if we don't care about errno and that is the only
10075     // thing preventing the function from being const. This allows
10076     // IRgen to use LLVM intrinsics for such functions.
10077     if (!getLangOpts().MathErrno &&
10078         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10079       if (!FD->hasAttr<ConstAttr>())
10080         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10081     }
10082 
10083     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10084         !FD->hasAttr<ReturnsTwiceAttr>())
10085       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
10086                                          FD->getLocation()));
10087     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
10088       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
10089     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
10090       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
10091   }
10092 
10093   IdentifierInfo *Name = FD->getIdentifier();
10094   if (!Name)
10095     return;
10096   if ((!getLangOpts().CPlusPlus &&
10097        FD->getDeclContext()->isTranslationUnit()) ||
10098       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10099        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10100        LinkageSpecDecl::lang_c)) {
10101     // Okay: this could be a libc/libm/Objective-C function we know
10102     // about.
10103   } else
10104     return;
10105 
10106   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10107     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10108     // target-specific builtins, perhaps?
10109     if (!FD->hasAttr<FormatAttr>())
10110       FD->addAttr(FormatAttr::CreateImplicit(Context,
10111                                              &Context.Idents.get("printf"), 2,
10112                                              Name->isStr("vasprintf") ? 0 : 3,
10113                                              FD->getLocation()));
10114   }
10115 
10116   if (Name->isStr("__CFStringMakeConstantString")) {
10117     // We already have a __builtin___CFStringMakeConstantString,
10118     // but builds that use -fno-constant-cfstrings don't go through that.
10119     if (!FD->hasAttr<FormatArgAttr>())
10120       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
10121                                                 FD->getLocation()));
10122   }
10123 }
10124 
10125 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10126                                     TypeSourceInfo *TInfo) {
10127   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10128   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10129 
10130   if (!TInfo) {
10131     assert(D.isInvalidType() && "no declarator info for valid type");
10132     TInfo = Context.getTrivialTypeSourceInfo(T);
10133   }
10134 
10135   // Scope manipulation handled by caller.
10136   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10137                                            D.getLocStart(),
10138                                            D.getIdentifierLoc(),
10139                                            D.getIdentifier(),
10140                                            TInfo);
10141 
10142   // Bail out immediately if we have an invalid declaration.
10143   if (D.isInvalidType()) {
10144     NewTD->setInvalidDecl();
10145     return NewTD;
10146   }
10147 
10148   if (D.getDeclSpec().isModulePrivateSpecified()) {
10149     if (CurContext->isFunctionOrMethod())
10150       Diag(NewTD->getLocation(), diag::err_module_private_local)
10151         << 2 << NewTD->getDeclName()
10152         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10153         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10154     else
10155       NewTD->setModulePrivate();
10156   }
10157 
10158   // C++ [dcl.typedef]p8:
10159   //   If the typedef declaration defines an unnamed class (or
10160   //   enum), the first typedef-name declared by the declaration
10161   //   to be that class type (or enum type) is used to denote the
10162   //   class type (or enum type) for linkage purposes only.
10163   // We need to check whether the type was declared in the declaration.
10164   switch (D.getDeclSpec().getTypeSpecType()) {
10165   case TST_enum:
10166   case TST_struct:
10167   case TST_interface:
10168   case TST_union:
10169   case TST_class: {
10170     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10171 
10172     // Do nothing if the tag is not anonymous or already has an
10173     // associated typedef (from an earlier typedef in this decl group).
10174     if (tagFromDeclSpec->getIdentifier()) break;
10175     if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10176 
10177     // A well-formed anonymous tag must always be a TUK_Definition.
10178     assert(tagFromDeclSpec->isThisDeclarationADefinition());
10179 
10180     // The type must match the tag exactly;  no qualifiers allowed.
10181     if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10182       break;
10183 
10184     // Otherwise, set this is the anon-decl typedef for the tag.
10185     tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10186     break;
10187   }
10188 
10189   default:
10190     break;
10191   }
10192 
10193   return NewTD;
10194 }
10195 
10196 
10197 /// \brief Check that this is a valid underlying type for an enum declaration.
10198 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10199   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10200   QualType T = TI->getType();
10201 
10202   if (T->isDependentType())
10203     return false;
10204 
10205   if (const BuiltinType *BT = T->getAs<BuiltinType>())
10206     if (BT->isInteger())
10207       return false;
10208 
10209   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10210   return true;
10211 }
10212 
10213 /// Check whether this is a valid redeclaration of a previous enumeration.
10214 /// \return true if the redeclaration was invalid.
10215 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10216                                   QualType EnumUnderlyingTy,
10217                                   const EnumDecl *Prev) {
10218   bool IsFixed = !EnumUnderlyingTy.isNull();
10219 
10220   if (IsScoped != Prev->isScoped()) {
10221     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10222       << Prev->isScoped();
10223     Diag(Prev->getLocation(), diag::note_previous_declaration);
10224     return true;
10225   }
10226 
10227   if (IsFixed && Prev->isFixed()) {
10228     if (!EnumUnderlyingTy->isDependentType() &&
10229         !Prev->getIntegerType()->isDependentType() &&
10230         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10231                                         Prev->getIntegerType())) {
10232       // TODO: Highlight the underlying type of the redeclaration.
10233       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10234         << EnumUnderlyingTy << Prev->getIntegerType();
10235       Diag(Prev->getLocation(), diag::note_previous_declaration)
10236           << Prev->getIntegerTypeRange();
10237       return true;
10238     }
10239   } else if (IsFixed != Prev->isFixed()) {
10240     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10241       << Prev->isFixed();
10242     Diag(Prev->getLocation(), diag::note_previous_declaration);
10243     return true;
10244   }
10245 
10246   return false;
10247 }
10248 
10249 /// \brief Get diagnostic %select index for tag kind for
10250 /// redeclaration diagnostic message.
10251 /// WARNING: Indexes apply to particular diagnostics only!
10252 ///
10253 /// \returns diagnostic %select index.
10254 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10255   switch (Tag) {
10256   case TTK_Struct: return 0;
10257   case TTK_Interface: return 1;
10258   case TTK_Class:  return 2;
10259   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10260   }
10261 }
10262 
10263 /// \brief Determine if tag kind is a class-key compatible with
10264 /// class for redeclaration (class, struct, or __interface).
10265 ///
10266 /// \returns true iff the tag kind is compatible.
10267 static bool isClassCompatTagKind(TagTypeKind Tag)
10268 {
10269   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10270 }
10271 
10272 /// \brief Determine whether a tag with a given kind is acceptable
10273 /// as a redeclaration of the given tag declaration.
10274 ///
10275 /// \returns true if the new tag kind is acceptable, false otherwise.
10276 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10277                                         TagTypeKind NewTag, bool isDefinition,
10278                                         SourceLocation NewTagLoc,
10279                                         const IdentifierInfo &Name) {
10280   // C++ [dcl.type.elab]p3:
10281   //   The class-key or enum keyword present in the
10282   //   elaborated-type-specifier shall agree in kind with the
10283   //   declaration to which the name in the elaborated-type-specifier
10284   //   refers. This rule also applies to the form of
10285   //   elaborated-type-specifier that declares a class-name or
10286   //   friend class since it can be construed as referring to the
10287   //   definition of the class. Thus, in any
10288   //   elaborated-type-specifier, the enum keyword shall be used to
10289   //   refer to an enumeration (7.2), the union class-key shall be
10290   //   used to refer to a union (clause 9), and either the class or
10291   //   struct class-key shall be used to refer to a class (clause 9)
10292   //   declared using the class or struct class-key.
10293   TagTypeKind OldTag = Previous->getTagKind();
10294   if (!isDefinition || !isClassCompatTagKind(NewTag))
10295     if (OldTag == NewTag)
10296       return true;
10297 
10298   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10299     // Warn about the struct/class tag mismatch.
10300     bool isTemplate = false;
10301     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10302       isTemplate = Record->getDescribedClassTemplate();
10303 
10304     if (!ActiveTemplateInstantiations.empty()) {
10305       // In a template instantiation, do not offer fix-its for tag mismatches
10306       // since they usually mess up the template instead of fixing the problem.
10307       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10308         << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10309         << getRedeclDiagFromTagKind(OldTag);
10310       return true;
10311     }
10312 
10313     if (isDefinition) {
10314       // On definitions, check previous tags and issue a fix-it for each
10315       // one that doesn't match the current tag.
10316       if (Previous->getDefinition()) {
10317         // Don't suggest fix-its for redefinitions.
10318         return true;
10319       }
10320 
10321       bool previousMismatch = false;
10322       for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10323            E(Previous->redecls_end()); I != E; ++I) {
10324         if (I->getTagKind() != NewTag) {
10325           if (!previousMismatch) {
10326             previousMismatch = true;
10327             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10328               << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10329               << getRedeclDiagFromTagKind(I->getTagKind());
10330           }
10331           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10332             << getRedeclDiagFromTagKind(NewTag)
10333             << FixItHint::CreateReplacement(I->getInnerLocStart(),
10334                  TypeWithKeyword::getTagTypeKindName(NewTag));
10335         }
10336       }
10337       return true;
10338     }
10339 
10340     // Check for a previous definition.  If current tag and definition
10341     // are same type, do nothing.  If no definition, but disagree with
10342     // with previous tag type, give a warning, but no fix-it.
10343     const TagDecl *Redecl = Previous->getDefinition() ?
10344                             Previous->getDefinition() : Previous;
10345     if (Redecl->getTagKind() == NewTag) {
10346       return true;
10347     }
10348 
10349     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10350       << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10351       << getRedeclDiagFromTagKind(OldTag);
10352     Diag(Redecl->getLocation(), diag::note_previous_use);
10353 
10354     // If there is a previous definition, suggest a fix-it.
10355     if (Previous->getDefinition()) {
10356         Diag(NewTagLoc, diag::note_struct_class_suggestion)
10357           << getRedeclDiagFromTagKind(Redecl->getTagKind())
10358           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10359                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10360     }
10361 
10362     return true;
10363   }
10364   return false;
10365 }
10366 
10367 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10368 /// former case, Name will be non-null.  In the later case, Name will be null.
10369 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10370 /// reference/declaration/definition of a tag.
10371 ///
10372 /// IsTypeSpecifier is true if this is a type-specifier (or
10373 /// trailing-type-specifier) other than one in an alias-declaration.
10374 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10375                      SourceLocation KWLoc, CXXScopeSpec &SS,
10376                      IdentifierInfo *Name, SourceLocation NameLoc,
10377                      AttributeList *Attr, AccessSpecifier AS,
10378                      SourceLocation ModulePrivateLoc,
10379                      MultiTemplateParamsArg TemplateParameterLists,
10380                      bool &OwnedDecl, bool &IsDependent,
10381                      SourceLocation ScopedEnumKWLoc,
10382                      bool ScopedEnumUsesClassTag,
10383                      TypeResult UnderlyingType,
10384                      bool IsTypeSpecifier) {
10385   // If this is not a definition, it must have a name.
10386   IdentifierInfo *OrigName = Name;
10387   assert((Name != 0 || TUK == TUK_Definition) &&
10388          "Nameless record must be a definition!");
10389   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10390 
10391   OwnedDecl = false;
10392   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10393   bool ScopedEnum = ScopedEnumKWLoc.isValid();
10394 
10395   // FIXME: Check explicit specializations more carefully.
10396   bool isExplicitSpecialization = false;
10397   bool Invalid = false;
10398 
10399   // We only need to do this matching if we have template parameters
10400   // or a scope specifier, which also conveniently avoids this work
10401   // for non-C++ cases.
10402   if (TemplateParameterLists.size() > 0 ||
10403       (SS.isNotEmpty() && TUK != TUK_Reference)) {
10404     if (TemplateParameterList *TemplateParams =
10405             MatchTemplateParametersToScopeSpecifier(
10406                 KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10407                 isExplicitSpecialization, Invalid)) {
10408       if (Kind == TTK_Enum) {
10409         Diag(KWLoc, diag::err_enum_template);
10410         return 0;
10411       }
10412 
10413       if (TemplateParams->size() > 0) {
10414         // This is a declaration or definition of a class template (which may
10415         // be a member of another template).
10416 
10417         if (Invalid)
10418           return 0;
10419 
10420         OwnedDecl = false;
10421         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10422                                                SS, Name, NameLoc, Attr,
10423                                                TemplateParams, AS,
10424                                                ModulePrivateLoc,
10425                                                TemplateParameterLists.size()-1,
10426                                                TemplateParameterLists.data());
10427         return Result.get();
10428       } else {
10429         // The "template<>" header is extraneous.
10430         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10431           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10432         isExplicitSpecialization = true;
10433       }
10434     }
10435   }
10436 
10437   // Figure out the underlying type if this a enum declaration. We need to do
10438   // this early, because it's needed to detect if this is an incompatible
10439   // redeclaration.
10440   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10441 
10442   if (Kind == TTK_Enum) {
10443     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10444       // No underlying type explicitly specified, or we failed to parse the
10445       // type, default to int.
10446       EnumUnderlying = Context.IntTy.getTypePtr();
10447     else if (UnderlyingType.get()) {
10448       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10449       // integral type; any cv-qualification is ignored.
10450       TypeSourceInfo *TI = 0;
10451       GetTypeFromParser(UnderlyingType.get(), &TI);
10452       EnumUnderlying = TI;
10453 
10454       if (CheckEnumUnderlyingType(TI))
10455         // Recover by falling back to int.
10456         EnumUnderlying = Context.IntTy.getTypePtr();
10457 
10458       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10459                                           UPPC_FixedUnderlyingType))
10460         EnumUnderlying = Context.IntTy.getTypePtr();
10461 
10462     } else if (getLangOpts().MSVCCompat)
10463       // Microsoft enums are always of int type.
10464       EnumUnderlying = Context.IntTy.getTypePtr();
10465   }
10466 
10467   DeclContext *SearchDC = CurContext;
10468   DeclContext *DC = CurContext;
10469   bool isStdBadAlloc = false;
10470 
10471   RedeclarationKind Redecl = ForRedeclaration;
10472   if (TUK == TUK_Friend || TUK == TUK_Reference)
10473     Redecl = NotForRedeclaration;
10474 
10475   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10476   bool FriendSawTagOutsideEnclosingNamespace = false;
10477   if (Name && SS.isNotEmpty()) {
10478     // We have a nested-name tag ('struct foo::bar').
10479 
10480     // Check for invalid 'foo::'.
10481     if (SS.isInvalid()) {
10482       Name = 0;
10483       goto CreateNewDecl;
10484     }
10485 
10486     // If this is a friend or a reference to a class in a dependent
10487     // context, don't try to make a decl for it.
10488     if (TUK == TUK_Friend || TUK == TUK_Reference) {
10489       DC = computeDeclContext(SS, false);
10490       if (!DC) {
10491         IsDependent = true;
10492         return 0;
10493       }
10494     } else {
10495       DC = computeDeclContext(SS, true);
10496       if (!DC) {
10497         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10498           << SS.getRange();
10499         return 0;
10500       }
10501     }
10502 
10503     if (RequireCompleteDeclContext(SS, DC))
10504       return 0;
10505 
10506     SearchDC = DC;
10507     // Look-up name inside 'foo::'.
10508     LookupQualifiedName(Previous, DC);
10509 
10510     if (Previous.isAmbiguous())
10511       return 0;
10512 
10513     if (Previous.empty()) {
10514       // Name lookup did not find anything. However, if the
10515       // nested-name-specifier refers to the current instantiation,
10516       // and that current instantiation has any dependent base
10517       // classes, we might find something at instantiation time: treat
10518       // this as a dependent elaborated-type-specifier.
10519       // But this only makes any sense for reference-like lookups.
10520       if (Previous.wasNotFoundInCurrentInstantiation() &&
10521           (TUK == TUK_Reference || TUK == TUK_Friend)) {
10522         IsDependent = true;
10523         return 0;
10524       }
10525 
10526       // A tag 'foo::bar' must already exist.
10527       Diag(NameLoc, diag::err_not_tag_in_scope)
10528         << Kind << Name << DC << SS.getRange();
10529       Name = 0;
10530       Invalid = true;
10531       goto CreateNewDecl;
10532     }
10533   } else if (Name) {
10534     // If this is a named struct, check to see if there was a previous forward
10535     // declaration or definition.
10536     // FIXME: We're looking into outer scopes here, even when we
10537     // shouldn't be. Doing so can result in ambiguities that we
10538     // shouldn't be diagnosing.
10539     LookupName(Previous, S);
10540 
10541     // When declaring or defining a tag, ignore ambiguities introduced
10542     // by types using'ed into this scope.
10543     if (Previous.isAmbiguous() &&
10544         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10545       LookupResult::Filter F = Previous.makeFilter();
10546       while (F.hasNext()) {
10547         NamedDecl *ND = F.next();
10548         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10549           F.erase();
10550       }
10551       F.done();
10552     }
10553 
10554     // C++11 [namespace.memdef]p3:
10555     //   If the name in a friend declaration is neither qualified nor
10556     //   a template-id and the declaration is a function or an
10557     //   elaborated-type-specifier, the lookup to determine whether
10558     //   the entity has been previously declared shall not consider
10559     //   any scopes outside the innermost enclosing namespace.
10560     //
10561     // Does it matter that this should be by scope instead of by
10562     // semantic context?
10563     if (!Previous.empty() && TUK == TUK_Friend) {
10564       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10565       LookupResult::Filter F = Previous.makeFilter();
10566       while (F.hasNext()) {
10567         NamedDecl *ND = F.next();
10568         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10569         if (DC->isFileContext() &&
10570             !EnclosingNS->Encloses(ND->getDeclContext())) {
10571           F.erase();
10572           FriendSawTagOutsideEnclosingNamespace = true;
10573         }
10574       }
10575       F.done();
10576     }
10577 
10578     // Note:  there used to be some attempt at recovery here.
10579     if (Previous.isAmbiguous())
10580       return 0;
10581 
10582     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10583       // FIXME: This makes sure that we ignore the contexts associated
10584       // with C structs, unions, and enums when looking for a matching
10585       // tag declaration or definition. See the similar lookup tweak
10586       // in Sema::LookupName; is there a better way to deal with this?
10587       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10588         SearchDC = SearchDC->getParent();
10589     }
10590   } else if (S->isFunctionPrototypeScope()) {
10591     // If this is an enum declaration in function prototype scope, set its
10592     // initial context to the translation unit.
10593     // FIXME: [citation needed]
10594     SearchDC = Context.getTranslationUnitDecl();
10595   }
10596 
10597   if (Previous.isSingleResult() &&
10598       Previous.getFoundDecl()->isTemplateParameter()) {
10599     // Maybe we will complain about the shadowed template parameter.
10600     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10601     // Just pretend that we didn't see the previous declaration.
10602     Previous.clear();
10603   }
10604 
10605   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10606       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10607     // This is a declaration of or a reference to "std::bad_alloc".
10608     isStdBadAlloc = true;
10609 
10610     if (Previous.empty() && StdBadAlloc) {
10611       // std::bad_alloc has been implicitly declared (but made invisible to
10612       // name lookup). Fill in this implicit declaration as the previous
10613       // declaration, so that the declarations get chained appropriately.
10614       Previous.addDecl(getStdBadAlloc());
10615     }
10616   }
10617 
10618   // If we didn't find a previous declaration, and this is a reference
10619   // (or friend reference), move to the correct scope.  In C++, we
10620   // also need to do a redeclaration lookup there, just in case
10621   // there's a shadow friend decl.
10622   if (Name && Previous.empty() &&
10623       (TUK == TUK_Reference || TUK == TUK_Friend)) {
10624     if (Invalid) goto CreateNewDecl;
10625     assert(SS.isEmpty());
10626 
10627     if (TUK == TUK_Reference) {
10628       // C++ [basic.scope.pdecl]p5:
10629       //   -- for an elaborated-type-specifier of the form
10630       //
10631       //          class-key identifier
10632       //
10633       //      if the elaborated-type-specifier is used in the
10634       //      decl-specifier-seq or parameter-declaration-clause of a
10635       //      function defined in namespace scope, the identifier is
10636       //      declared as a class-name in the namespace that contains
10637       //      the declaration; otherwise, except as a friend
10638       //      declaration, the identifier is declared in the smallest
10639       //      non-class, non-function-prototype scope that contains the
10640       //      declaration.
10641       //
10642       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10643       // C structs and unions.
10644       //
10645       // It is an error in C++ to declare (rather than define) an enum
10646       // type, including via an elaborated type specifier.  We'll
10647       // diagnose that later; for now, declare the enum in the same
10648       // scope as we would have picked for any other tag type.
10649       //
10650       // GNU C also supports this behavior as part of its incomplete
10651       // enum types extension, while GNU C++ does not.
10652       //
10653       // Find the context where we'll be declaring the tag.
10654       // FIXME: We would like to maintain the current DeclContext as the
10655       // lexical context,
10656       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10657         SearchDC = SearchDC->getParent();
10658 
10659       // Find the scope where we'll be declaring the tag.
10660       while (S->isClassScope() ||
10661              (getLangOpts().CPlusPlus &&
10662               S->isFunctionPrototypeScope()) ||
10663              ((S->getFlags() & Scope::DeclScope) == 0) ||
10664              (S->getEntity() && S->getEntity()->isTransparentContext()))
10665         S = S->getParent();
10666     } else {
10667       assert(TUK == TUK_Friend);
10668       // C++ [namespace.memdef]p3:
10669       //   If a friend declaration in a non-local class first declares a
10670       //   class or function, the friend class or function is a member of
10671       //   the innermost enclosing namespace.
10672       SearchDC = SearchDC->getEnclosingNamespaceContext();
10673     }
10674 
10675     // In C++, we need to do a redeclaration lookup to properly
10676     // diagnose some problems.
10677     if (getLangOpts().CPlusPlus) {
10678       Previous.setRedeclarationKind(ForRedeclaration);
10679       LookupQualifiedName(Previous, SearchDC);
10680     }
10681   }
10682 
10683   if (!Previous.empty()) {
10684     NamedDecl *PrevDecl = Previous.getFoundDecl();
10685     NamedDecl *DirectPrevDecl =
10686         getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl;
10687 
10688     // It's okay to have a tag decl in the same scope as a typedef
10689     // which hides a tag decl in the same scope.  Finding this
10690     // insanity with a redeclaration lookup can only actually happen
10691     // in C++.
10692     //
10693     // This is also okay for elaborated-type-specifiers, which is
10694     // technically forbidden by the current standard but which is
10695     // okay according to the likely resolution of an open issue;
10696     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10697     if (getLangOpts().CPlusPlus) {
10698       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10699         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10700           TagDecl *Tag = TT->getDecl();
10701           if (Tag->getDeclName() == Name &&
10702               Tag->getDeclContext()->getRedeclContext()
10703                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
10704             PrevDecl = Tag;
10705             Previous.clear();
10706             Previous.addDecl(Tag);
10707             Previous.resolveKind();
10708           }
10709         }
10710       }
10711     }
10712 
10713     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10714       // If this is a use of a previous tag, or if the tag is already declared
10715       // in the same scope (so that the definition/declaration completes or
10716       // rementions the tag), reuse the decl.
10717       if (TUK == TUK_Reference || TUK == TUK_Friend ||
10718           isDeclInScope(DirectPrevDecl, SearchDC, S,
10719                         SS.isNotEmpty() || isExplicitSpecialization)) {
10720         // Make sure that this wasn't declared as an enum and now used as a
10721         // struct or something similar.
10722         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10723                                           TUK == TUK_Definition, KWLoc,
10724                                           *Name)) {
10725           bool SafeToContinue
10726             = (PrevTagDecl->getTagKind() != TTK_Enum &&
10727                Kind != TTK_Enum);
10728           if (SafeToContinue)
10729             Diag(KWLoc, diag::err_use_with_wrong_tag)
10730               << Name
10731               << FixItHint::CreateReplacement(SourceRange(KWLoc),
10732                                               PrevTagDecl->getKindName());
10733           else
10734             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
10735           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
10736 
10737           if (SafeToContinue)
10738             Kind = PrevTagDecl->getTagKind();
10739           else {
10740             // Recover by making this an anonymous redefinition.
10741             Name = 0;
10742             Previous.clear();
10743             Invalid = true;
10744           }
10745         }
10746 
10747         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10748           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10749 
10750           // If this is an elaborated-type-specifier for a scoped enumeration,
10751           // the 'class' keyword is not necessary and not permitted.
10752           if (TUK == TUK_Reference || TUK == TUK_Friend) {
10753             if (ScopedEnum)
10754               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10755                 << PrevEnum->isScoped()
10756                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10757             return PrevTagDecl;
10758           }
10759 
10760           QualType EnumUnderlyingTy;
10761           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10762             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
10763           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10764             EnumUnderlyingTy = QualType(T, 0);
10765 
10766           // All conflicts with previous declarations are recovered by
10767           // returning the previous declaration, unless this is a definition,
10768           // in which case we want the caller to bail out.
10769           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10770                                      ScopedEnum, EnumUnderlyingTy, PrevEnum))
10771             return TUK == TUK_Declaration ? PrevTagDecl : 0;
10772         }
10773 
10774         // C++11 [class.mem]p1:
10775         //   A member shall not be declared twice in the member-specification,
10776         //   except that a nested class or member class template can be declared
10777         //   and then later defined.
10778         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10779             S->isDeclScope(PrevDecl)) {
10780           Diag(NameLoc, diag::ext_member_redeclared);
10781           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10782         }
10783 
10784         if (!Invalid) {
10785           // If this is a use, just return the declaration we found.
10786 
10787           // FIXME: In the future, return a variant or some other clue
10788           // for the consumer of this Decl to know it doesn't own it.
10789           // For our current ASTs this shouldn't be a problem, but will
10790           // need to be changed with DeclGroups.
10791           if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
10792                getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
10793             return PrevTagDecl;
10794 
10795           // Diagnose attempts to redefine a tag.
10796           if (TUK == TUK_Definition) {
10797             if (TagDecl *Def = PrevTagDecl->getDefinition()) {
10798               // If we're defining a specialization and the previous definition
10799               // is from an implicit instantiation, don't emit an error
10800               // here; we'll catch this in the general case below.
10801               bool IsExplicitSpecializationAfterInstantiation = false;
10802               if (isExplicitSpecialization) {
10803                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10804                   IsExplicitSpecializationAfterInstantiation =
10805                     RD->getTemplateSpecializationKind() !=
10806                     TSK_ExplicitSpecialization;
10807                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10808                   IsExplicitSpecializationAfterInstantiation =
10809                     ED->getTemplateSpecializationKind() !=
10810                     TSK_ExplicitSpecialization;
10811               }
10812 
10813               if (!IsExplicitSpecializationAfterInstantiation) {
10814                 // A redeclaration in function prototype scope in C isn't
10815                 // visible elsewhere, so merely issue a warning.
10816                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
10817                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10818                 else
10819                   Diag(NameLoc, diag::err_redefinition) << Name;
10820                 Diag(Def->getLocation(), diag::note_previous_definition);
10821                 // If this is a redefinition, recover by making this
10822                 // struct be anonymous, which will make any later
10823                 // references get the previous definition.
10824                 Name = 0;
10825                 Previous.clear();
10826                 Invalid = true;
10827               }
10828             } else {
10829               // If the type is currently being defined, complain
10830               // about a nested redefinition.
10831               const TagType *Tag
10832                 = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
10833               if (Tag->isBeingDefined()) {
10834                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
10835                 Diag(PrevTagDecl->getLocation(),
10836                      diag::note_previous_definition);
10837                 Name = 0;
10838                 Previous.clear();
10839                 Invalid = true;
10840               }
10841             }
10842 
10843             // Okay, this is definition of a previously declared or referenced
10844             // tag PrevDecl. We're going to create a new Decl for it.
10845           }
10846         }
10847         // If we get here we have (another) forward declaration or we
10848         // have a definition.  Just create a new decl.
10849 
10850       } else {
10851         // If we get here, this is a definition of a new tag type in a nested
10852         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
10853         // new decl/type.  We set PrevDecl to NULL so that the entities
10854         // have distinct types.
10855         Previous.clear();
10856       }
10857       // If we get here, we're going to create a new Decl. If PrevDecl
10858       // is non-NULL, it's a definition of the tag declared by
10859       // PrevDecl. If it's NULL, we have a new definition.
10860 
10861 
10862     // Otherwise, PrevDecl is not a tag, but was found with tag
10863     // lookup.  This is only actually possible in C++, where a few
10864     // things like templates still live in the tag namespace.
10865     } else {
10866       // Use a better diagnostic if an elaborated-type-specifier
10867       // found the wrong kind of type on the first
10868       // (non-redeclaration) lookup.
10869       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10870           !Previous.isForRedeclaration()) {
10871         unsigned Kind = 0;
10872         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10873         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10874         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10875         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10876         Diag(PrevDecl->getLocation(), diag::note_declared_at);
10877         Invalid = true;
10878 
10879       // Otherwise, only diagnose if the declaration is in scope.
10880       } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10881                                 SS.isNotEmpty() || isExplicitSpecialization)) {
10882         // do nothing
10883 
10884       // Diagnose implicit declarations introduced by elaborated types.
10885       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10886         unsigned Kind = 0;
10887         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10888         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10889         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10890         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10891         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10892         Invalid = true;
10893 
10894       // Otherwise it's a declaration.  Call out a particularly common
10895       // case here.
10896       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10897         unsigned Kind = 0;
10898         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
10899         Diag(NameLoc, diag::err_tag_definition_of_typedef)
10900           << Name << Kind << TND->getUnderlyingType();
10901         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10902         Invalid = true;
10903 
10904       // Otherwise, diagnose.
10905       } else {
10906         // The tag name clashes with something else in the target scope,
10907         // issue an error and recover by making this tag be anonymous.
10908         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
10909         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10910         Name = 0;
10911         Invalid = true;
10912       }
10913 
10914       // The existing declaration isn't relevant to us; we're in a
10915       // new scope, so clear out the previous declaration.
10916       Previous.clear();
10917     }
10918   }
10919 
10920 CreateNewDecl:
10921 
10922   TagDecl *PrevDecl = 0;
10923   if (Previous.isSingleResult())
10924     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10925 
10926   // If there is an identifier, use the location of the identifier as the
10927   // location of the decl, otherwise use the location of the struct/union
10928   // keyword.
10929   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
10930 
10931   // Otherwise, create a new declaration. If there is a previous
10932   // declaration of the same entity, the two will be linked via
10933   // PrevDecl.
10934   TagDecl *New;
10935 
10936   bool IsForwardReference = false;
10937   if (Kind == TTK_Enum) {
10938     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10939     // enum X { A, B, C } D;    D should chain to X.
10940     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
10941                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
10942                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
10943     // If this is an undefined enum, warn.
10944     if (TUK != TUK_Definition && !Invalid) {
10945       TagDecl *Def;
10946       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10947           cast<EnumDecl>(New)->isFixed()) {
10948         // C++0x: 7.2p2: opaque-enum-declaration.
10949         // Conflicts are diagnosed above. Do nothing.
10950       }
10951       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
10952         Diag(Loc, diag::ext_forward_ref_enum_def)
10953           << New;
10954         Diag(Def->getLocation(), diag::note_previous_definition);
10955       } else {
10956         unsigned DiagID = diag::ext_forward_ref_enum;
10957         if (getLangOpts().MSVCCompat)
10958           DiagID = diag::ext_ms_forward_ref_enum;
10959         else if (getLangOpts().CPlusPlus)
10960           DiagID = diag::err_forward_ref_enum;
10961         Diag(Loc, DiagID);
10962 
10963         // If this is a forward-declared reference to an enumeration, make a
10964         // note of it; we won't actually be introducing the declaration into
10965         // the declaration context.
10966         if (TUK == TUK_Reference)
10967           IsForwardReference = true;
10968       }
10969     }
10970 
10971     if (EnumUnderlying) {
10972       EnumDecl *ED = cast<EnumDecl>(New);
10973       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10974         ED->setIntegerTypeSourceInfo(TI);
10975       else
10976         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10977       ED->setPromotionType(ED->getIntegerType());
10978     }
10979 
10980   } else {
10981     // struct/union/class
10982 
10983     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10984     // struct X { int A; } D;    D should chain to X.
10985     if (getLangOpts().CPlusPlus) {
10986       // FIXME: Look for a way to use RecordDecl for simple structs.
10987       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10988                                   cast_or_null<CXXRecordDecl>(PrevDecl));
10989 
10990       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
10991         StdBadAlloc = cast<CXXRecordDecl>(New);
10992     } else
10993       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10994                                cast_or_null<RecordDecl>(PrevDecl));
10995   }
10996 
10997   // C++11 [dcl.type]p3:
10998   //   A type-specifier-seq shall not define a class or enumeration [...].
10999   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
11000     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
11001       << Context.getTagDeclType(New);
11002     Invalid = true;
11003   }
11004 
11005   // Maybe add qualifier info.
11006   if (SS.isNotEmpty()) {
11007     if (SS.isSet()) {
11008       // If this is either a declaration or a definition, check the
11009       // nested-name-specifier against the current context. We don't do this
11010       // for explicit specializations, because they have similar checking
11011       // (with more specific diagnostics) in the call to
11012       // CheckMemberSpecialization, below.
11013       if (!isExplicitSpecialization &&
11014           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
11015           diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
11016         Invalid = true;
11017 
11018       New->setQualifierInfo(SS.getWithLocInContext(Context));
11019       if (TemplateParameterLists.size() > 0) {
11020         New->setTemplateParameterListsInfo(Context,
11021                                            TemplateParameterLists.size(),
11022                                            TemplateParameterLists.data());
11023       }
11024     }
11025     else
11026       Invalid = true;
11027   }
11028 
11029   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
11030     // Add alignment attributes if necessary; these attributes are checked when
11031     // the ASTContext lays out the structure.
11032     //
11033     // It is important for implementing the correct semantics that this
11034     // happen here (in act on tag decl). The #pragma pack stack is
11035     // maintained as a result of parser callbacks which can occur at
11036     // many points during the parsing of a struct declaration (because
11037     // the #pragma tokens are effectively skipped over during the
11038     // parsing of the struct).
11039     if (TUK == TUK_Definition) {
11040       AddAlignmentAttributesForRecord(RD);
11041       AddMsStructLayoutForRecord(RD);
11042     }
11043   }
11044 
11045   if (ModulePrivateLoc.isValid()) {
11046     if (isExplicitSpecialization)
11047       Diag(New->getLocation(), diag::err_module_private_specialization)
11048         << 2
11049         << FixItHint::CreateRemoval(ModulePrivateLoc);
11050     // __module_private__ does not apply to local classes. However, we only
11051     // diagnose this as an error when the declaration specifiers are
11052     // freestanding. Here, we just ignore the __module_private__.
11053     else if (!SearchDC->isFunctionOrMethod())
11054       New->setModulePrivate();
11055   }
11056 
11057   // If this is a specialization of a member class (of a class template),
11058   // check the specialization.
11059   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
11060     Invalid = true;
11061 
11062   if (Invalid)
11063     New->setInvalidDecl();
11064 
11065   if (Attr)
11066     ProcessDeclAttributeList(S, New, Attr);
11067 
11068   // If we're declaring or defining a tag in function prototype scope
11069   // in C, note that this type can only be used within the function.
11070   if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
11071     Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
11072 
11073   // Set the lexical context. If the tag has a C++ scope specifier, the
11074   // lexical context will be different from the semantic context.
11075   New->setLexicalDeclContext(CurContext);
11076 
11077   // Mark this as a friend decl if applicable.
11078   // In Microsoft mode, a friend declaration also acts as a forward
11079   // declaration so we always pass true to setObjectOfFriendDecl to make
11080   // the tag name visible.
11081   if (TUK == TUK_Friend)
11082     New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
11083                                getLangOpts().MicrosoftExt);
11084 
11085   // Set the access specifier.
11086   if (!Invalid && SearchDC->isRecord())
11087     SetMemberAccessSpecifier(New, PrevDecl, AS);
11088 
11089   if (TUK == TUK_Definition)
11090     New->startDefinition();
11091 
11092   // If this has an identifier, add it to the scope stack.
11093   if (TUK == TUK_Friend) {
11094     // We might be replacing an existing declaration in the lookup tables;
11095     // if so, borrow its access specifier.
11096     if (PrevDecl)
11097       New->setAccess(PrevDecl->getAccess());
11098 
11099     DeclContext *DC = New->getDeclContext()->getRedeclContext();
11100     DC->makeDeclVisibleInContext(New);
11101     if (Name) // can be null along some error paths
11102       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11103         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11104   } else if (Name) {
11105     S = getNonFieldDeclScope(S);
11106     PushOnScopeChains(New, S, !IsForwardReference);
11107     if (IsForwardReference)
11108       SearchDC->makeDeclVisibleInContext(New);
11109 
11110   } else {
11111     CurContext->addDecl(New);
11112   }
11113 
11114   // If this is the C FILE type, notify the AST context.
11115   if (IdentifierInfo *II = New->getIdentifier())
11116     if (!New->isInvalidDecl() &&
11117         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11118         II->isStr("FILE"))
11119       Context.setFILEDecl(New);
11120 
11121   // If we were in function prototype scope (and not in C++ mode), add this
11122   // tag to the list of decls to inject into the function definition scope.
11123   if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
11124       InFunctionDeclarator && Name)
11125     DeclsInPrototypeScope.push_back(New);
11126 
11127   if (PrevDecl)
11128     mergeDeclAttributes(New, PrevDecl);
11129 
11130   // If there's a #pragma GCC visibility in scope, set the visibility of this
11131   // record.
11132   AddPushedVisibilityAttribute(New);
11133 
11134   OwnedDecl = true;
11135   // In C++, don't return an invalid declaration. We can't recover well from
11136   // the cases where we make the type anonymous.
11137   return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
11138 }
11139 
11140 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11141   AdjustDeclIfTemplate(TagD);
11142   TagDecl *Tag = cast<TagDecl>(TagD);
11143 
11144   // Enter the tag context.
11145   PushDeclContext(S, Tag);
11146 
11147   ActOnDocumentableDecl(TagD);
11148 
11149   // If there's a #pragma GCC visibility in scope, set the visibility of this
11150   // record.
11151   AddPushedVisibilityAttribute(Tag);
11152 }
11153 
11154 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11155   assert(isa<ObjCContainerDecl>(IDecl) &&
11156          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11157   DeclContext *OCD = cast<DeclContext>(IDecl);
11158   assert(getContainingDC(OCD) == CurContext &&
11159       "The next DeclContext should be lexically contained in the current one.");
11160   CurContext = OCD;
11161   return IDecl;
11162 }
11163 
11164 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11165                                            SourceLocation FinalLoc,
11166                                            bool IsFinalSpelledSealed,
11167                                            SourceLocation LBraceLoc) {
11168   AdjustDeclIfTemplate(TagD);
11169   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11170 
11171   FieldCollector->StartClass();
11172 
11173   if (!Record->getIdentifier())
11174     return;
11175 
11176   if (FinalLoc.isValid())
11177     Record->addAttr(new (Context)
11178                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11179 
11180   // C++ [class]p2:
11181   //   [...] The class-name is also inserted into the scope of the
11182   //   class itself; this is known as the injected-class-name. For
11183   //   purposes of access checking, the injected-class-name is treated
11184   //   as if it were a public member name.
11185   CXXRecordDecl *InjectedClassName
11186     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11187                             Record->getLocStart(), Record->getLocation(),
11188                             Record->getIdentifier(),
11189                             /*PrevDecl=*/0,
11190                             /*DelayTypeCreation=*/true);
11191   Context.getTypeDeclType(InjectedClassName, Record);
11192   InjectedClassName->setImplicit();
11193   InjectedClassName->setAccess(AS_public);
11194   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11195       InjectedClassName->setDescribedClassTemplate(Template);
11196   PushOnScopeChains(InjectedClassName, S);
11197   assert(InjectedClassName->isInjectedClassName() &&
11198          "Broken injected-class-name");
11199 }
11200 
11201 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11202                                     SourceLocation RBraceLoc) {
11203   AdjustDeclIfTemplate(TagD);
11204   TagDecl *Tag = cast<TagDecl>(TagD);
11205   Tag->setRBraceLoc(RBraceLoc);
11206 
11207   // Make sure we "complete" the definition even it is invalid.
11208   if (Tag->isBeingDefined()) {
11209     assert(Tag->isInvalidDecl() && "We should already have completed it");
11210     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11211       RD->completeDefinition();
11212   }
11213 
11214   if (isa<CXXRecordDecl>(Tag))
11215     FieldCollector->FinishClass();
11216 
11217   // Exit this scope of this tag's definition.
11218   PopDeclContext();
11219 
11220   if (getCurLexicalContext()->isObjCContainer() &&
11221       Tag->getDeclContext()->isFileContext())
11222     Tag->setTopLevelDeclInObjCContainer();
11223 
11224   // Notify the consumer that we've defined a tag.
11225   if (!Tag->isInvalidDecl())
11226     Consumer.HandleTagDeclDefinition(Tag);
11227 }
11228 
11229 void Sema::ActOnObjCContainerFinishDefinition() {
11230   // Exit this scope of this interface definition.
11231   PopDeclContext();
11232 }
11233 
11234 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11235   assert(DC == CurContext && "Mismatch of container contexts");
11236   OriginalLexicalContext = DC;
11237   ActOnObjCContainerFinishDefinition();
11238 }
11239 
11240 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11241   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11242   OriginalLexicalContext = 0;
11243 }
11244 
11245 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11246   AdjustDeclIfTemplate(TagD);
11247   TagDecl *Tag = cast<TagDecl>(TagD);
11248   Tag->setInvalidDecl();
11249 
11250   // Make sure we "complete" the definition even it is invalid.
11251   if (Tag->isBeingDefined()) {
11252     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11253       RD->completeDefinition();
11254   }
11255 
11256   // We're undoing ActOnTagStartDefinition here, not
11257   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11258   // the FieldCollector.
11259 
11260   PopDeclContext();
11261 }
11262 
11263 // Note that FieldName may be null for anonymous bitfields.
11264 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11265                                 IdentifierInfo *FieldName,
11266                                 QualType FieldTy, bool IsMsStruct,
11267                                 Expr *BitWidth, bool *ZeroWidth) {
11268   // Default to true; that shouldn't confuse checks for emptiness
11269   if (ZeroWidth)
11270     *ZeroWidth = true;
11271 
11272   // C99 6.7.2.1p4 - verify the field type.
11273   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11274   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11275     // Handle incomplete types with specific error.
11276     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11277       return ExprError();
11278     if (FieldName)
11279       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11280         << FieldName << FieldTy << BitWidth->getSourceRange();
11281     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11282       << FieldTy << BitWidth->getSourceRange();
11283   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11284                                              UPPC_BitFieldWidth))
11285     return ExprError();
11286 
11287   // If the bit-width is type- or value-dependent, don't try to check
11288   // it now.
11289   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11290     return Owned(BitWidth);
11291 
11292   llvm::APSInt Value;
11293   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11294   if (ICE.isInvalid())
11295     return ICE;
11296   BitWidth = ICE.take();
11297 
11298   if (Value != 0 && ZeroWidth)
11299     *ZeroWidth = false;
11300 
11301   // Zero-width bitfield is ok for anonymous field.
11302   if (Value == 0 && FieldName)
11303     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11304 
11305   if (Value.isSigned() && Value.isNegative()) {
11306     if (FieldName)
11307       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11308                << FieldName << Value.toString(10);
11309     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11310       << Value.toString(10);
11311   }
11312 
11313   if (!FieldTy->isDependentType()) {
11314     uint64_t TypeSize = Context.getTypeSize(FieldTy);
11315     if (Value.getZExtValue() > TypeSize) {
11316       if (!getLangOpts().CPlusPlus || IsMsStruct ||
11317           Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11318         if (FieldName)
11319           return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11320             << FieldName << (unsigned)Value.getZExtValue()
11321             << (unsigned)TypeSize;
11322 
11323         return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11324           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11325       }
11326 
11327       if (FieldName)
11328         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11329           << FieldName << (unsigned)Value.getZExtValue()
11330           << (unsigned)TypeSize;
11331       else
11332         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11333           << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11334     }
11335   }
11336 
11337   return Owned(BitWidth);
11338 }
11339 
11340 /// ActOnField - Each field of a C struct/union is passed into this in order
11341 /// to create a FieldDecl object for it.
11342 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11343                        Declarator &D, Expr *BitfieldWidth) {
11344   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11345                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11346                                /*InitStyle=*/ICIS_NoInit, AS_public);
11347   return Res;
11348 }
11349 
11350 /// HandleField - Analyze a field of a C struct or a C++ data member.
11351 ///
11352 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11353                              SourceLocation DeclStart,
11354                              Declarator &D, Expr *BitWidth,
11355                              InClassInitStyle InitStyle,
11356                              AccessSpecifier AS) {
11357   IdentifierInfo *II = D.getIdentifier();
11358   SourceLocation Loc = DeclStart;
11359   if (II) Loc = D.getIdentifierLoc();
11360 
11361   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11362   QualType T = TInfo->getType();
11363   if (getLangOpts().CPlusPlus) {
11364     CheckExtraCXXDefaultArguments(D);
11365 
11366     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11367                                         UPPC_DataMemberType)) {
11368       D.setInvalidType();
11369       T = Context.IntTy;
11370       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11371     }
11372   }
11373 
11374   // TR 18037 does not allow fields to be declared with address spaces.
11375   if (T.getQualifiers().hasAddressSpace()) {
11376     Diag(Loc, diag::err_field_with_address_space);
11377     D.setInvalidType();
11378   }
11379 
11380   // OpenCL 1.2 spec, s6.9 r:
11381   // The event type cannot be used to declare a structure or union field.
11382   if (LangOpts.OpenCL && T->isEventT()) {
11383     Diag(Loc, diag::err_event_t_struct_field);
11384     D.setInvalidType();
11385   }
11386 
11387   DiagnoseFunctionSpecifiers(D.getDeclSpec());
11388 
11389   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11390     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11391          diag::err_invalid_thread)
11392       << DeclSpec::getSpecifierName(TSCS);
11393 
11394   // Check to see if this name was declared as a member previously
11395   NamedDecl *PrevDecl = 0;
11396   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11397   LookupName(Previous, S);
11398   switch (Previous.getResultKind()) {
11399     case LookupResult::Found:
11400     case LookupResult::FoundUnresolvedValue:
11401       PrevDecl = Previous.getAsSingle<NamedDecl>();
11402       break;
11403 
11404     case LookupResult::FoundOverloaded:
11405       PrevDecl = Previous.getRepresentativeDecl();
11406       break;
11407 
11408     case LookupResult::NotFound:
11409     case LookupResult::NotFoundInCurrentInstantiation:
11410     case LookupResult::Ambiguous:
11411       break;
11412   }
11413   Previous.suppressDiagnostics();
11414 
11415   if (PrevDecl && PrevDecl->isTemplateParameter()) {
11416     // Maybe we will complain about the shadowed template parameter.
11417     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11418     // Just pretend that we didn't see the previous declaration.
11419     PrevDecl = 0;
11420   }
11421 
11422   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11423     PrevDecl = 0;
11424 
11425   bool Mutable
11426     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11427   SourceLocation TSSL = D.getLocStart();
11428   FieldDecl *NewFD
11429     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11430                      TSSL, AS, PrevDecl, &D);
11431 
11432   if (NewFD->isInvalidDecl())
11433     Record->setInvalidDecl();
11434 
11435   if (D.getDeclSpec().isModulePrivateSpecified())
11436     NewFD->setModulePrivate();
11437 
11438   if (NewFD->isInvalidDecl() && PrevDecl) {
11439     // Don't introduce NewFD into scope; there's already something
11440     // with the same name in the same scope.
11441   } else if (II) {
11442     PushOnScopeChains(NewFD, S);
11443   } else
11444     Record->addDecl(NewFD);
11445 
11446   return NewFD;
11447 }
11448 
11449 /// \brief Build a new FieldDecl and check its well-formedness.
11450 ///
11451 /// This routine builds a new FieldDecl given the fields name, type,
11452 /// record, etc. \p PrevDecl should refer to any previous declaration
11453 /// with the same name and in the same scope as the field to be
11454 /// created.
11455 ///
11456 /// \returns a new FieldDecl.
11457 ///
11458 /// \todo The Declarator argument is a hack. It will be removed once
11459 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11460                                 TypeSourceInfo *TInfo,
11461                                 RecordDecl *Record, SourceLocation Loc,
11462                                 bool Mutable, Expr *BitWidth,
11463                                 InClassInitStyle InitStyle,
11464                                 SourceLocation TSSL,
11465                                 AccessSpecifier AS, NamedDecl *PrevDecl,
11466                                 Declarator *D) {
11467   IdentifierInfo *II = Name.getAsIdentifierInfo();
11468   bool InvalidDecl = false;
11469   if (D) InvalidDecl = D->isInvalidType();
11470 
11471   // If we receive a broken type, recover by assuming 'int' and
11472   // marking this declaration as invalid.
11473   if (T.isNull()) {
11474     InvalidDecl = true;
11475     T = Context.IntTy;
11476   }
11477 
11478   QualType EltTy = Context.getBaseElementType(T);
11479   if (!EltTy->isDependentType()) {
11480     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11481       // Fields of incomplete type force their record to be invalid.
11482       Record->setInvalidDecl();
11483       InvalidDecl = true;
11484     } else {
11485       NamedDecl *Def;
11486       EltTy->isIncompleteType(&Def);
11487       if (Def && Def->isInvalidDecl()) {
11488         Record->setInvalidDecl();
11489         InvalidDecl = true;
11490       }
11491     }
11492   }
11493 
11494   // OpenCL v1.2 s6.9.c: bitfields are not supported.
11495   if (BitWidth && getLangOpts().OpenCL) {
11496     Diag(Loc, diag::err_opencl_bitfields);
11497     InvalidDecl = true;
11498   }
11499 
11500   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11501   // than a variably modified type.
11502   if (!InvalidDecl && T->isVariablyModifiedType()) {
11503     bool SizeIsNegative;
11504     llvm::APSInt Oversized;
11505 
11506     TypeSourceInfo *FixedTInfo =
11507       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11508                                                     SizeIsNegative,
11509                                                     Oversized);
11510     if (FixedTInfo) {
11511       Diag(Loc, diag::warn_illegal_constant_array_size);
11512       TInfo = FixedTInfo;
11513       T = FixedTInfo->getType();
11514     } else {
11515       if (SizeIsNegative)
11516         Diag(Loc, diag::err_typecheck_negative_array_size);
11517       else if (Oversized.getBoolValue())
11518         Diag(Loc, diag::err_array_too_large)
11519           << Oversized.toString(10);
11520       else
11521         Diag(Loc, diag::err_typecheck_field_variable_size);
11522       InvalidDecl = true;
11523     }
11524   }
11525 
11526   // Fields can not have abstract class types
11527   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11528                                              diag::err_abstract_type_in_decl,
11529                                              AbstractFieldType))
11530     InvalidDecl = true;
11531 
11532   bool ZeroWidth = false;
11533   // If this is declared as a bit-field, check the bit-field.
11534   if (!InvalidDecl && BitWidth) {
11535     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11536                               &ZeroWidth).take();
11537     if (!BitWidth) {
11538       InvalidDecl = true;
11539       BitWidth = 0;
11540       ZeroWidth = false;
11541     }
11542   }
11543 
11544   // Check that 'mutable' is consistent with the type of the declaration.
11545   if (!InvalidDecl && Mutable) {
11546     unsigned DiagID = 0;
11547     if (T->isReferenceType())
11548       DiagID = diag::err_mutable_reference;
11549     else if (T.isConstQualified())
11550       DiagID = diag::err_mutable_const;
11551 
11552     if (DiagID) {
11553       SourceLocation ErrLoc = Loc;
11554       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11555         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11556       Diag(ErrLoc, DiagID);
11557       Mutable = false;
11558       InvalidDecl = true;
11559     }
11560   }
11561 
11562   // C++11 [class.union]p8 (DR1460):
11563   //   At most one variant member of a union may have a
11564   //   brace-or-equal-initializer.
11565   if (InitStyle != ICIS_NoInit)
11566     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
11567 
11568   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11569                                        BitWidth, Mutable, InitStyle);
11570   if (InvalidDecl)
11571     NewFD->setInvalidDecl();
11572 
11573   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11574     Diag(Loc, diag::err_duplicate_member) << II;
11575     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11576     NewFD->setInvalidDecl();
11577   }
11578 
11579   if (!InvalidDecl && getLangOpts().CPlusPlus) {
11580     if (Record->isUnion()) {
11581       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11582         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11583         if (RDecl->getDefinition()) {
11584           // C++ [class.union]p1: An object of a class with a non-trivial
11585           // constructor, a non-trivial copy constructor, a non-trivial
11586           // destructor, or a non-trivial copy assignment operator
11587           // cannot be a member of a union, nor can an array of such
11588           // objects.
11589           if (CheckNontrivialField(NewFD))
11590             NewFD->setInvalidDecl();
11591         }
11592       }
11593 
11594       // C++ [class.union]p1: If a union contains a member of reference type,
11595       // the program is ill-formed, except when compiling with MSVC extensions
11596       // enabled.
11597       if (EltTy->isReferenceType()) {
11598         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11599                                     diag::ext_union_member_of_reference_type :
11600                                     diag::err_union_member_of_reference_type)
11601           << NewFD->getDeclName() << EltTy;
11602         if (!getLangOpts().MicrosoftExt)
11603           NewFD->setInvalidDecl();
11604       }
11605     }
11606   }
11607 
11608   // FIXME: We need to pass in the attributes given an AST
11609   // representation, not a parser representation.
11610   if (D) {
11611     // FIXME: The current scope is almost... but not entirely... correct here.
11612     ProcessDeclAttributes(getCurScope(), NewFD, *D);
11613 
11614     if (NewFD->hasAttrs())
11615       CheckAlignasUnderalignment(NewFD);
11616   }
11617 
11618   // In auto-retain/release, infer strong retension for fields of
11619   // retainable type.
11620   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11621     NewFD->setInvalidDecl();
11622 
11623   if (T.isObjCGCWeak())
11624     Diag(Loc, diag::warn_attribute_weak_on_field);
11625 
11626   NewFD->setAccess(AS);
11627   return NewFD;
11628 }
11629 
11630 bool Sema::CheckNontrivialField(FieldDecl *FD) {
11631   assert(FD);
11632   assert(getLangOpts().CPlusPlus && "valid check only for C++");
11633 
11634   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11635     return false;
11636 
11637   QualType EltTy = Context.getBaseElementType(FD->getType());
11638   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11639     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11640     if (RDecl->getDefinition()) {
11641       // We check for copy constructors before constructors
11642       // because otherwise we'll never get complaints about
11643       // copy constructors.
11644 
11645       CXXSpecialMember member = CXXInvalid;
11646       // We're required to check for any non-trivial constructors. Since the
11647       // implicit default constructor is suppressed if there are any
11648       // user-declared constructors, we just need to check that there is a
11649       // trivial default constructor and a trivial copy constructor. (We don't
11650       // worry about move constructors here, since this is a C++98 check.)
11651       if (RDecl->hasNonTrivialCopyConstructor())
11652         member = CXXCopyConstructor;
11653       else if (!RDecl->hasTrivialDefaultConstructor())
11654         member = CXXDefaultConstructor;
11655       else if (RDecl->hasNonTrivialCopyAssignment())
11656         member = CXXCopyAssignment;
11657       else if (RDecl->hasNonTrivialDestructor())
11658         member = CXXDestructor;
11659 
11660       if (member != CXXInvalid) {
11661         if (!getLangOpts().CPlusPlus11 &&
11662             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11663           // Objective-C++ ARC: it is an error to have a non-trivial field of
11664           // a union. However, system headers in Objective-C programs
11665           // occasionally have Objective-C lifetime objects within unions,
11666           // and rather than cause the program to fail, we make those
11667           // members unavailable.
11668           SourceLocation Loc = FD->getLocation();
11669           if (getSourceManager().isInSystemHeader(Loc)) {
11670             if (!FD->hasAttr<UnavailableAttr>())
11671               FD->addAttr(UnavailableAttr::CreateImplicit(Context,
11672                                   "this system field has retaining ownership",
11673                                   Loc));
11674             return false;
11675           }
11676         }
11677 
11678         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11679                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11680                diag::err_illegal_union_or_anon_struct_member)
11681           << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11682         DiagnoseNontrivial(RDecl, member);
11683         return !getLangOpts().CPlusPlus11;
11684       }
11685     }
11686   }
11687 
11688   return false;
11689 }
11690 
11691 /// TranslateIvarVisibility - Translate visibility from a token ID to an
11692 ///  AST enum value.
11693 static ObjCIvarDecl::AccessControl
11694 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11695   switch (ivarVisibility) {
11696   default: llvm_unreachable("Unknown visitibility kind");
11697   case tok::objc_private: return ObjCIvarDecl::Private;
11698   case tok::objc_public: return ObjCIvarDecl::Public;
11699   case tok::objc_protected: return ObjCIvarDecl::Protected;
11700   case tok::objc_package: return ObjCIvarDecl::Package;
11701   }
11702 }
11703 
11704 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
11705 /// in order to create an IvarDecl object for it.
11706 Decl *Sema::ActOnIvar(Scope *S,
11707                                 SourceLocation DeclStart,
11708                                 Declarator &D, Expr *BitfieldWidth,
11709                                 tok::ObjCKeywordKind Visibility) {
11710 
11711   IdentifierInfo *II = D.getIdentifier();
11712   Expr *BitWidth = (Expr*)BitfieldWidth;
11713   SourceLocation Loc = DeclStart;
11714   if (II) Loc = D.getIdentifierLoc();
11715 
11716   // FIXME: Unnamed fields can be handled in various different ways, for
11717   // example, unnamed unions inject all members into the struct namespace!
11718 
11719   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11720   QualType T = TInfo->getType();
11721 
11722   if (BitWidth) {
11723     // 6.7.2.1p3, 6.7.2.1p4
11724     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
11725     if (!BitWidth)
11726       D.setInvalidType();
11727   } else {
11728     // Not a bitfield.
11729 
11730     // validate II.
11731 
11732   }
11733   if (T->isReferenceType()) {
11734     Diag(Loc, diag::err_ivar_reference_type);
11735     D.setInvalidType();
11736   }
11737   // C99 6.7.2.1p8: A member of a structure or union may have any type other
11738   // than a variably modified type.
11739   else if (T->isVariablyModifiedType()) {
11740     Diag(Loc, diag::err_typecheck_ivar_variable_size);
11741     D.setInvalidType();
11742   }
11743 
11744   // Get the visibility (access control) for this ivar.
11745   ObjCIvarDecl::AccessControl ac =
11746     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11747                                         : ObjCIvarDecl::None;
11748   // Must set ivar's DeclContext to its enclosing interface.
11749   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
11750   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11751     return 0;
11752   ObjCContainerDecl *EnclosingContext;
11753   if (ObjCImplementationDecl *IMPDecl =
11754       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11755     if (LangOpts.ObjCRuntime.isFragile()) {
11756     // Case of ivar declared in an implementation. Context is that of its class.
11757       EnclosingContext = IMPDecl->getClassInterface();
11758       assert(EnclosingContext && "Implementation has no class interface!");
11759     }
11760     else
11761       EnclosingContext = EnclosingDecl;
11762   } else {
11763     if (ObjCCategoryDecl *CDecl =
11764         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11765       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
11766         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
11767         return 0;
11768       }
11769     }
11770     EnclosingContext = EnclosingDecl;
11771   }
11772 
11773   // Construct the decl.
11774   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11775                                              DeclStart, Loc, II, T,
11776                                              TInfo, ac, (Expr *)BitfieldWidth);
11777 
11778   if (II) {
11779     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
11780                                            ForRedeclaration);
11781     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
11782         && !isa<TagDecl>(PrevDecl)) {
11783       Diag(Loc, diag::err_duplicate_member) << II;
11784       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11785       NewID->setInvalidDecl();
11786     }
11787   }
11788 
11789   // Process attributes attached to the ivar.
11790   ProcessDeclAttributes(S, NewID, D);
11791 
11792   if (D.isInvalidType())
11793     NewID->setInvalidDecl();
11794 
11795   // In ARC, infer 'retaining' for ivars of retainable type.
11796   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
11797     NewID->setInvalidDecl();
11798 
11799   if (D.getDeclSpec().isModulePrivateSpecified())
11800     NewID->setModulePrivate();
11801 
11802   if (II) {
11803     // FIXME: When interfaces are DeclContexts, we'll need to add
11804     // these to the interface.
11805     S->AddDecl(NewID);
11806     IdResolver.AddDecl(NewID);
11807   }
11808 
11809   if (LangOpts.ObjCRuntime.isNonFragile() &&
11810       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
11811     Diag(Loc, diag::warn_ivars_in_interface);
11812 
11813   return NewID;
11814 }
11815 
11816 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
11817 /// class and class extensions. For every class \@interface and class
11818 /// extension \@interface, if the last ivar is a bitfield of any type,
11819 /// then add an implicit `char :0` ivar to the end of that interface.
11820 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
11821                              SmallVectorImpl<Decl *> &AllIvarDecls) {
11822   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
11823     return;
11824 
11825   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11826   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11827 
11828   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
11829     return;
11830   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
11831   if (!ID) {
11832     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
11833       if (!CD->IsClassExtension())
11834         return;
11835     }
11836     // No need to add this to end of @implementation.
11837     else
11838       return;
11839   }
11840   // All conditions are met. Add a new bitfield to the tail end of ivars.
11841   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11842   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
11843 
11844   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
11845                               DeclLoc, DeclLoc, 0,
11846                               Context.CharTy,
11847                               Context.getTrivialTypeSourceInfo(Context.CharTy,
11848                                                                DeclLoc),
11849                               ObjCIvarDecl::Private, BW,
11850                               true);
11851   AllIvarDecls.push_back(Ivar);
11852 }
11853 
11854 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11855                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
11856                        SourceLocation RBrac, AttributeList *Attr) {
11857   assert(EnclosingDecl && "missing record or interface decl");
11858 
11859   // If this is an Objective-C @implementation or category and we have
11860   // new fields here we should reset the layout of the interface since
11861   // it will now change.
11862   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11863     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11864     switch (DC->getKind()) {
11865     default: break;
11866     case Decl::ObjCCategory:
11867       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11868       break;
11869     case Decl::ObjCImplementation:
11870       Context.
11871         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11872       break;
11873     }
11874   }
11875 
11876   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11877 
11878   // Start counting up the number of named members; make sure to include
11879   // members of anonymous structs and unions in the total.
11880   unsigned NumNamedMembers = 0;
11881   if (Record) {
11882     for (RecordDecl::decl_iterator i = Record->decls_begin(),
11883                                    e = Record->decls_end(); i != e; i++) {
11884       if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11885         if (IFD->getDeclName())
11886           ++NumNamedMembers;
11887     }
11888   }
11889 
11890   // Verify that all the fields are okay.
11891   SmallVector<FieldDecl*, 32> RecFields;
11892 
11893   bool ARCErrReported = false;
11894   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
11895        i != end; ++i) {
11896     FieldDecl *FD = cast<FieldDecl>(*i);
11897 
11898     // Get the type for the field.
11899     const Type *FDTy = FD->getType().getTypePtr();
11900 
11901     if (!FD->isAnonymousStructOrUnion()) {
11902       // Remember all fields written by the user.
11903       RecFields.push_back(FD);
11904     }
11905 
11906     // If the field is already invalid for some reason, don't emit more
11907     // diagnostics about it.
11908     if (FD->isInvalidDecl()) {
11909       EnclosingDecl->setInvalidDecl();
11910       continue;
11911     }
11912 
11913     // C99 6.7.2.1p2:
11914     //   A structure or union shall not contain a member with
11915     //   incomplete or function type (hence, a structure shall not
11916     //   contain an instance of itself, but may contain a pointer to
11917     //   an instance of itself), except that the last member of a
11918     //   structure with more than one named member may have incomplete
11919     //   array type; such a structure (and any union containing,
11920     //   possibly recursively, a member that is such a structure)
11921     //   shall not be a member of a structure or an element of an
11922     //   array.
11923     if (FDTy->isFunctionType()) {
11924       // Field declared as a function.
11925       Diag(FD->getLocation(), diag::err_field_declared_as_function)
11926         << FD->getDeclName();
11927       FD->setInvalidDecl();
11928       EnclosingDecl->setInvalidDecl();
11929       continue;
11930     } else if (FDTy->isIncompleteArrayType() && Record &&
11931                ((i + 1 == Fields.end() && !Record->isUnion()) ||
11932                 ((getLangOpts().MicrosoftExt ||
11933                   getLangOpts().CPlusPlus) &&
11934                  (i + 1 == Fields.end() || Record->isUnion())))) {
11935       // Flexible array member.
11936       // Microsoft and g++ is more permissive regarding flexible array.
11937       // It will accept flexible array in union and also
11938       // as the sole element of a struct/class.
11939       unsigned DiagID = 0;
11940       if (Record->isUnion())
11941         DiagID = getLangOpts().MicrosoftExt
11942                      ? diag::ext_flexible_array_union_ms
11943                      : getLangOpts().CPlusPlus
11944                            ? diag::ext_flexible_array_union_gnu
11945                            : diag::err_flexible_array_union;
11946       else if (Fields.size() == 1)
11947         DiagID = getLangOpts().MicrosoftExt
11948                      ? diag::ext_flexible_array_empty_aggregate_ms
11949                      : getLangOpts().CPlusPlus
11950                            ? diag::ext_flexible_array_empty_aggregate_gnu
11951                            : NumNamedMembers < 1
11952                                  ? diag::err_flexible_array_empty_aggregate
11953                                  : 0;
11954 
11955       if (DiagID)
11956         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11957                                         << Record->getTagKind();
11958       // While the layout of types that contain virtual bases is not specified
11959       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11960       // virtual bases after the derived members.  This would make a flexible
11961       // array member declared at the end of an object not adjacent to the end
11962       // of the type.
11963       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11964         if (RD->getNumVBases() != 0)
11965           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11966             << FD->getDeclName() << Record->getTagKind();
11967       if (!getLangOpts().C99)
11968         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11969           << FD->getDeclName() << Record->getTagKind();
11970 
11971       // If the element type has a non-trivial destructor, we would not
11972       // implicitly destroy the elements, so disallow it for now.
11973       //
11974       // FIXME: GCC allows this. We should probably either implicitly delete
11975       // the destructor of the containing class, or just allow this.
11976       QualType BaseElem = Context.getBaseElementType(FD->getType());
11977       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
11978         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
11979           << FD->getDeclName() << FD->getType();
11980         FD->setInvalidDecl();
11981         EnclosingDecl->setInvalidDecl();
11982         continue;
11983       }
11984       // Okay, we have a legal flexible array member at the end of the struct.
11985       if (Record)
11986         Record->setHasFlexibleArrayMember(true);
11987     } else if (!FDTy->isDependentType() &&
11988                RequireCompleteType(FD->getLocation(), FD->getType(),
11989                                    diag::err_field_incomplete)) {
11990       // Incomplete type
11991       FD->setInvalidDecl();
11992       EnclosingDecl->setInvalidDecl();
11993       continue;
11994     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
11995       if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11996         // If this is a member of a union, then entire union becomes "flexible".
11997         if (Record && Record->isUnion()) {
11998           Record->setHasFlexibleArrayMember(true);
11999         } else {
12000           // If this is a struct/class and this is not the last element, reject
12001           // it.  Note that GCC supports variable sized arrays in the middle of
12002           // structures.
12003           if (i + 1 != Fields.end())
12004             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
12005               << FD->getDeclName() << FD->getType();
12006           else {
12007             // We support flexible arrays at the end of structs in
12008             // other structs as an extension.
12009             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
12010               << FD->getDeclName();
12011             if (Record)
12012               Record->setHasFlexibleArrayMember(true);
12013           }
12014         }
12015       }
12016       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
12017           RequireNonAbstractType(FD->getLocation(), FD->getType(),
12018                                  diag::err_abstract_type_in_decl,
12019                                  AbstractIvarType)) {
12020         // Ivars can not have abstract class types
12021         FD->setInvalidDecl();
12022       }
12023       if (Record && FDTTy->getDecl()->hasObjectMember())
12024         Record->setHasObjectMember(true);
12025       if (Record && FDTTy->getDecl()->hasVolatileMember())
12026         Record->setHasVolatileMember(true);
12027     } else if (FDTy->isObjCObjectType()) {
12028       /// A field cannot be an Objective-c object
12029       Diag(FD->getLocation(), diag::err_statically_allocated_object)
12030         << FixItHint::CreateInsertion(FD->getLocation(), "*");
12031       QualType T = Context.getObjCObjectPointerType(FD->getType());
12032       FD->setType(T);
12033     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
12034                (!getLangOpts().CPlusPlus || Record->isUnion())) {
12035       // It's an error in ARC if a field has lifetime.
12036       // We don't want to report this in a system header, though,
12037       // so we just make the field unavailable.
12038       // FIXME: that's really not sufficient; we need to make the type
12039       // itself invalid to, say, initialize or copy.
12040       QualType T = FD->getType();
12041       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
12042       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
12043         SourceLocation loc = FD->getLocation();
12044         if (getSourceManager().isInSystemHeader(loc)) {
12045           if (!FD->hasAttr<UnavailableAttr>()) {
12046             FD->addAttr(UnavailableAttr::CreateImplicit(Context,
12047                               "this system field has retaining ownership",
12048                               loc));
12049           }
12050         } else {
12051           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
12052             << T->isBlockPointerType() << Record->getTagKind();
12053         }
12054         ARCErrReported = true;
12055       }
12056     } else if (getLangOpts().ObjC1 &&
12057                getLangOpts().getGC() != LangOptions::NonGC &&
12058                Record && !Record->hasObjectMember()) {
12059       if (FD->getType()->isObjCObjectPointerType() ||
12060           FD->getType().isObjCGCStrong())
12061         Record->setHasObjectMember(true);
12062       else if (Context.getAsArrayType(FD->getType())) {
12063         QualType BaseType = Context.getBaseElementType(FD->getType());
12064         if (BaseType->isRecordType() &&
12065             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
12066           Record->setHasObjectMember(true);
12067         else if (BaseType->isObjCObjectPointerType() ||
12068                  BaseType.isObjCGCStrong())
12069                Record->setHasObjectMember(true);
12070       }
12071     }
12072     if (Record && FD->getType().isVolatileQualified())
12073       Record->setHasVolatileMember(true);
12074     // Keep track of the number of named members.
12075     if (FD->getIdentifier())
12076       ++NumNamedMembers;
12077   }
12078 
12079   // Okay, we successfully defined 'Record'.
12080   if (Record) {
12081     bool Completed = false;
12082     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
12083       if (!CXXRecord->isInvalidDecl()) {
12084         // Set access bits correctly on the directly-declared conversions.
12085         for (CXXRecordDecl::conversion_iterator
12086                I = CXXRecord->conversion_begin(),
12087                E = CXXRecord->conversion_end(); I != E; ++I)
12088           I.setAccess((*I)->getAccess());
12089 
12090         if (!CXXRecord->isDependentType()) {
12091           if (CXXRecord->hasUserDeclaredDestructor()) {
12092             // Adjust user-defined destructor exception spec.
12093             if (getLangOpts().CPlusPlus11)
12094               AdjustDestructorExceptionSpec(CXXRecord,
12095                                             CXXRecord->getDestructor());
12096           }
12097 
12098           // Add any implicitly-declared members to this class.
12099           AddImplicitlyDeclaredMembersToClass(CXXRecord);
12100 
12101           // If we have virtual base classes, we may end up finding multiple
12102           // final overriders for a given virtual function. Check for this
12103           // problem now.
12104           if (CXXRecord->getNumVBases()) {
12105             CXXFinalOverriderMap FinalOverriders;
12106             CXXRecord->getFinalOverriders(FinalOverriders);
12107 
12108             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12109                                              MEnd = FinalOverriders.end();
12110                  M != MEnd; ++M) {
12111               for (OverridingMethods::iterator SO = M->second.begin(),
12112                                             SOEnd = M->second.end();
12113                    SO != SOEnd; ++SO) {
12114                 assert(SO->second.size() > 0 &&
12115                        "Virtual function without overridding functions?");
12116                 if (SO->second.size() == 1)
12117                   continue;
12118 
12119                 // C++ [class.virtual]p2:
12120                 //   In a derived class, if a virtual member function of a base
12121                 //   class subobject has more than one final overrider the
12122                 //   program is ill-formed.
12123                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12124                   << (const NamedDecl *)M->first << Record;
12125                 Diag(M->first->getLocation(),
12126                      diag::note_overridden_virtual_function);
12127                 for (OverridingMethods::overriding_iterator
12128                           OM = SO->second.begin(),
12129                        OMEnd = SO->second.end();
12130                      OM != OMEnd; ++OM)
12131                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
12132                     << (const NamedDecl *)M->first << OM->Method->getParent();
12133 
12134                 Record->setInvalidDecl();
12135               }
12136             }
12137             CXXRecord->completeDefinition(&FinalOverriders);
12138             Completed = true;
12139           }
12140         }
12141       }
12142     }
12143 
12144     if (!Completed)
12145       Record->completeDefinition();
12146 
12147     if (Record->hasAttrs())
12148       CheckAlignasUnderalignment(Record);
12149 
12150     // Check if the structure/union declaration is a type that can have zero
12151     // size in C. For C this is a language extension, for C++ it may cause
12152     // compatibility problems.
12153     bool CheckForZeroSize;
12154     if (!getLangOpts().CPlusPlus) {
12155       CheckForZeroSize = true;
12156     } else {
12157       // For C++ filter out types that cannot be referenced in C code.
12158       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
12159       CheckForZeroSize =
12160           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
12161           !CXXRecord->isDependentType() &&
12162           CXXRecord->isCLike();
12163     }
12164     if (CheckForZeroSize) {
12165       bool ZeroSize = true;
12166       bool IsEmpty = true;
12167       unsigned NonBitFields = 0;
12168       for (RecordDecl::field_iterator I = Record->field_begin(),
12169                                       E = Record->field_end();
12170            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12171         IsEmpty = false;
12172         if (I->isUnnamedBitfield()) {
12173           if (I->getBitWidthValue(Context) > 0)
12174             ZeroSize = false;
12175         } else {
12176           ++NonBitFields;
12177           QualType FieldType = I->getType();
12178           if (FieldType->isIncompleteType() ||
12179               !Context.getTypeSizeInChars(FieldType).isZero())
12180             ZeroSize = false;
12181         }
12182       }
12183 
12184       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
12185       // allowed in C++, but warn if its declaration is inside
12186       // extern "C" block.
12187       if (ZeroSize) {
12188         Diag(RecLoc, getLangOpts().CPlusPlus ?
12189                          diag::warn_zero_size_struct_union_in_extern_c :
12190                          diag::warn_zero_size_struct_union_compat)
12191           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
12192       }
12193 
12194       // Structs without named members are extension in C (C99 6.7.2.1p7),
12195       // but are accepted by GCC.
12196       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
12197         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
12198                                diag::ext_no_named_members_in_struct_union)
12199           << Record->isUnion();
12200       }
12201     }
12202   } else {
12203     ObjCIvarDecl **ClsFields =
12204       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12205     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12206       ID->setEndOfDefinitionLoc(RBrac);
12207       // Add ivar's to class's DeclContext.
12208       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12209         ClsFields[i]->setLexicalDeclContext(ID);
12210         ID->addDecl(ClsFields[i]);
12211       }
12212       // Must enforce the rule that ivars in the base classes may not be
12213       // duplicates.
12214       if (ID->getSuperClass())
12215         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12216     } else if (ObjCImplementationDecl *IMPDecl =
12217                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12218       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12219       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12220         // Ivar declared in @implementation never belongs to the implementation.
12221         // Only it is in implementation's lexical context.
12222         ClsFields[I]->setLexicalDeclContext(IMPDecl);
12223       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12224       IMPDecl->setIvarLBraceLoc(LBrac);
12225       IMPDecl->setIvarRBraceLoc(RBrac);
12226     } else if (ObjCCategoryDecl *CDecl =
12227                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12228       // case of ivars in class extension; all other cases have been
12229       // reported as errors elsewhere.
12230       // FIXME. Class extension does not have a LocEnd field.
12231       // CDecl->setLocEnd(RBrac);
12232       // Add ivar's to class extension's DeclContext.
12233       // Diagnose redeclaration of private ivars.
12234       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12235       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12236         if (IDecl) {
12237           if (const ObjCIvarDecl *ClsIvar =
12238               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12239             Diag(ClsFields[i]->getLocation(),
12240                  diag::err_duplicate_ivar_declaration);
12241             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12242             continue;
12243           }
12244           for (ObjCInterfaceDecl::known_extensions_iterator
12245                  Ext = IDecl->known_extensions_begin(),
12246                  ExtEnd = IDecl->known_extensions_end();
12247                Ext != ExtEnd; ++Ext) {
12248             if (const ObjCIvarDecl *ClsExtIvar
12249                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12250               Diag(ClsFields[i]->getLocation(),
12251                    diag::err_duplicate_ivar_declaration);
12252               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12253               continue;
12254             }
12255           }
12256         }
12257         ClsFields[i]->setLexicalDeclContext(CDecl);
12258         CDecl->addDecl(ClsFields[i]);
12259       }
12260       CDecl->setIvarLBraceLoc(LBrac);
12261       CDecl->setIvarRBraceLoc(RBrac);
12262     }
12263   }
12264 
12265   if (Attr)
12266     ProcessDeclAttributeList(S, Record, Attr);
12267 }
12268 
12269 /// \brief Determine whether the given integral value is representable within
12270 /// the given type T.
12271 static bool isRepresentableIntegerValue(ASTContext &Context,
12272                                         llvm::APSInt &Value,
12273                                         QualType T) {
12274   assert(T->isIntegralType(Context) && "Integral type required!");
12275   unsigned BitWidth = Context.getIntWidth(T);
12276 
12277   if (Value.isUnsigned() || Value.isNonNegative()) {
12278     if (T->isSignedIntegerOrEnumerationType())
12279       --BitWidth;
12280     return Value.getActiveBits() <= BitWidth;
12281   }
12282   return Value.getMinSignedBits() <= BitWidth;
12283 }
12284 
12285 // \brief Given an integral type, return the next larger integral type
12286 // (or a NULL type of no such type exists).
12287 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12288   // FIXME: Int128/UInt128 support, which also needs to be introduced into
12289   // enum checking below.
12290   assert(T->isIntegralType(Context) && "Integral type required!");
12291   const unsigned NumTypes = 4;
12292   QualType SignedIntegralTypes[NumTypes] = {
12293     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12294   };
12295   QualType UnsignedIntegralTypes[NumTypes] = {
12296     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12297     Context.UnsignedLongLongTy
12298   };
12299 
12300   unsigned BitWidth = Context.getTypeSize(T);
12301   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12302                                                         : UnsignedIntegralTypes;
12303   for (unsigned I = 0; I != NumTypes; ++I)
12304     if (Context.getTypeSize(Types[I]) > BitWidth)
12305       return Types[I];
12306 
12307   return QualType();
12308 }
12309 
12310 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12311                                           EnumConstantDecl *LastEnumConst,
12312                                           SourceLocation IdLoc,
12313                                           IdentifierInfo *Id,
12314                                           Expr *Val) {
12315   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12316   llvm::APSInt EnumVal(IntWidth);
12317   QualType EltTy;
12318 
12319   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12320     Val = 0;
12321 
12322   if (Val)
12323     Val = DefaultLvalueConversion(Val).take();
12324 
12325   if (Val) {
12326     if (Enum->isDependentType() || Val->isTypeDependent())
12327       EltTy = Context.DependentTy;
12328     else {
12329       SourceLocation ExpLoc;
12330       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12331           !getLangOpts().MSVCCompat) {
12332         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12333         // constant-expression in the enumerator-definition shall be a converted
12334         // constant expression of the underlying type.
12335         EltTy = Enum->getIntegerType();
12336         ExprResult Converted =
12337           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12338                                            CCEK_Enumerator);
12339         if (Converted.isInvalid())
12340           Val = 0;
12341         else
12342           Val = Converted.take();
12343       } else if (!Val->isValueDependent() &&
12344                  !(Val = VerifyIntegerConstantExpression(Val,
12345                                                          &EnumVal).take())) {
12346         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12347       } else {
12348         if (Enum->isFixed()) {
12349           EltTy = Enum->getIntegerType();
12350 
12351           // In Obj-C and Microsoft mode, require the enumeration value to be
12352           // representable in the underlying type of the enumeration. In C++11,
12353           // we perform a non-narrowing conversion as part of converted constant
12354           // expression checking.
12355           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12356             if (getLangOpts().MSVCCompat) {
12357               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12358               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12359             } else
12360               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12361           } else
12362             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12363         } else if (getLangOpts().CPlusPlus) {
12364           // C++11 [dcl.enum]p5:
12365           //   If the underlying type is not fixed, the type of each enumerator
12366           //   is the type of its initializing value:
12367           //     - If an initializer is specified for an enumerator, the
12368           //       initializing value has the same type as the expression.
12369           EltTy = Val->getType();
12370         } else {
12371           // C99 6.7.2.2p2:
12372           //   The expression that defines the value of an enumeration constant
12373           //   shall be an integer constant expression that has a value
12374           //   representable as an int.
12375 
12376           // Complain if the value is not representable in an int.
12377           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12378             Diag(IdLoc, diag::ext_enum_value_not_int)
12379               << EnumVal.toString(10) << Val->getSourceRange()
12380               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12381           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12382             // Force the type of the expression to 'int'.
12383             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12384           }
12385           EltTy = Val->getType();
12386         }
12387       }
12388     }
12389   }
12390 
12391   if (!Val) {
12392     if (Enum->isDependentType())
12393       EltTy = Context.DependentTy;
12394     else if (!LastEnumConst) {
12395       // C++0x [dcl.enum]p5:
12396       //   If the underlying type is not fixed, the type of each enumerator
12397       //   is the type of its initializing value:
12398       //     - If no initializer is specified for the first enumerator, the
12399       //       initializing value has an unspecified integral type.
12400       //
12401       // GCC uses 'int' for its unspecified integral type, as does
12402       // C99 6.7.2.2p3.
12403       if (Enum->isFixed()) {
12404         EltTy = Enum->getIntegerType();
12405       }
12406       else {
12407         EltTy = Context.IntTy;
12408       }
12409     } else {
12410       // Assign the last value + 1.
12411       EnumVal = LastEnumConst->getInitVal();
12412       ++EnumVal;
12413       EltTy = LastEnumConst->getType();
12414 
12415       // Check for overflow on increment.
12416       if (EnumVal < LastEnumConst->getInitVal()) {
12417         // C++0x [dcl.enum]p5:
12418         //   If the underlying type is not fixed, the type of each enumerator
12419         //   is the type of its initializing value:
12420         //
12421         //     - Otherwise the type of the initializing value is the same as
12422         //       the type of the initializing value of the preceding enumerator
12423         //       unless the incremented value is not representable in that type,
12424         //       in which case the type is an unspecified integral type
12425         //       sufficient to contain the incremented value. If no such type
12426         //       exists, the program is ill-formed.
12427         QualType T = getNextLargerIntegralType(Context, EltTy);
12428         if (T.isNull() || Enum->isFixed()) {
12429           // There is no integral type larger enough to represent this
12430           // value. Complain, then allow the value to wrap around.
12431           EnumVal = LastEnumConst->getInitVal();
12432           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12433           ++EnumVal;
12434           if (Enum->isFixed())
12435             // When the underlying type is fixed, this is ill-formed.
12436             Diag(IdLoc, diag::err_enumerator_wrapped)
12437               << EnumVal.toString(10)
12438               << EltTy;
12439           else
12440             Diag(IdLoc, diag::warn_enumerator_too_large)
12441               << EnumVal.toString(10);
12442         } else {
12443           EltTy = T;
12444         }
12445 
12446         // Retrieve the last enumerator's value, extent that type to the
12447         // type that is supposed to be large enough to represent the incremented
12448         // value, then increment.
12449         EnumVal = LastEnumConst->getInitVal();
12450         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12451         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12452         ++EnumVal;
12453 
12454         // If we're not in C++, diagnose the overflow of enumerator values,
12455         // which in C99 means that the enumerator value is not representable in
12456         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12457         // permits enumerator values that are representable in some larger
12458         // integral type.
12459         if (!getLangOpts().CPlusPlus && !T.isNull())
12460           Diag(IdLoc, diag::warn_enum_value_overflow);
12461       } else if (!getLangOpts().CPlusPlus &&
12462                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12463         // Enforce C99 6.7.2.2p2 even when we compute the next value.
12464         Diag(IdLoc, diag::ext_enum_value_not_int)
12465           << EnumVal.toString(10) << 1;
12466       }
12467     }
12468   }
12469 
12470   if (!EltTy->isDependentType()) {
12471     // Make the enumerator value match the signedness and size of the
12472     // enumerator's type.
12473     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12474     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12475   }
12476 
12477   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12478                                   Val, EnumVal);
12479 }
12480 
12481 
12482 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12483                               SourceLocation IdLoc, IdentifierInfo *Id,
12484                               AttributeList *Attr,
12485                               SourceLocation EqualLoc, Expr *Val) {
12486   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12487   EnumConstantDecl *LastEnumConst =
12488     cast_or_null<EnumConstantDecl>(lastEnumConst);
12489 
12490   // The scope passed in may not be a decl scope.  Zip up the scope tree until
12491   // we find one that is.
12492   S = getNonFieldDeclScope(S);
12493 
12494   // Verify that there isn't already something declared with this name in this
12495   // scope.
12496   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12497                                          ForRedeclaration);
12498   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12499     // Maybe we will complain about the shadowed template parameter.
12500     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12501     // Just pretend that we didn't see the previous declaration.
12502     PrevDecl = 0;
12503   }
12504 
12505   if (PrevDecl) {
12506     // When in C++, we may get a TagDecl with the same name; in this case the
12507     // enum constant will 'hide' the tag.
12508     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12509            "Received TagDecl when not in C++!");
12510     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12511       if (isa<EnumConstantDecl>(PrevDecl))
12512         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12513       else
12514         Diag(IdLoc, diag::err_redefinition) << Id;
12515       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12516       return 0;
12517     }
12518   }
12519 
12520   // C++ [class.mem]p15:
12521   // If T is the name of a class, then each of the following shall have a name
12522   // different from T:
12523   // - every enumerator of every member of class T that is an unscoped
12524   // enumerated type
12525   if (CXXRecordDecl *Record
12526                       = dyn_cast<CXXRecordDecl>(
12527                              TheEnumDecl->getDeclContext()->getRedeclContext()))
12528     if (!TheEnumDecl->isScoped() &&
12529         Record->getIdentifier() && Record->getIdentifier() == Id)
12530       Diag(IdLoc, diag::err_member_name_of_class) << Id;
12531 
12532   EnumConstantDecl *New =
12533     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12534 
12535   if (New) {
12536     // Process attributes.
12537     if (Attr) ProcessDeclAttributeList(S, New, Attr);
12538 
12539     // Register this decl in the current scope stack.
12540     New->setAccess(TheEnumDecl->getAccess());
12541     PushOnScopeChains(New, S);
12542   }
12543 
12544   ActOnDocumentableDecl(New);
12545 
12546   return New;
12547 }
12548 
12549 // Returns true when the enum initial expression does not trigger the
12550 // duplicate enum warning.  A few common cases are exempted as follows:
12551 // Element2 = Element1
12552 // Element2 = Element1 + 1
12553 // Element2 = Element1 - 1
12554 // Where Element2 and Element1 are from the same enum.
12555 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12556   Expr *InitExpr = ECD->getInitExpr();
12557   if (!InitExpr)
12558     return true;
12559   InitExpr = InitExpr->IgnoreImpCasts();
12560 
12561   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12562     if (!BO->isAdditiveOp())
12563       return true;
12564     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12565     if (!IL)
12566       return true;
12567     if (IL->getValue() != 1)
12568       return true;
12569 
12570     InitExpr = BO->getLHS();
12571   }
12572 
12573   // This checks if the elements are from the same enum.
12574   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12575   if (!DRE)
12576     return true;
12577 
12578   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12579   if (!EnumConstant)
12580     return true;
12581 
12582   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12583       Enum)
12584     return true;
12585 
12586   return false;
12587 }
12588 
12589 struct DupKey {
12590   int64_t val;
12591   bool isTombstoneOrEmptyKey;
12592   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12593     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12594 };
12595 
12596 static DupKey GetDupKey(const llvm::APSInt& Val) {
12597   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12598                 false);
12599 }
12600 
12601 struct DenseMapInfoDupKey {
12602   static DupKey getEmptyKey() { return DupKey(0, true); }
12603   static DupKey getTombstoneKey() { return DupKey(1, true); }
12604   static unsigned getHashValue(const DupKey Key) {
12605     return (unsigned)(Key.val * 37);
12606   }
12607   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12608     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12609            LHS.val == RHS.val;
12610   }
12611 };
12612 
12613 // Emits a warning when an element is implicitly set a value that
12614 // a previous element has already been set to.
12615 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12616                                         EnumDecl *Enum,
12617                                         QualType EnumType) {
12618   if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12619                                  Enum->getLocation()) ==
12620       DiagnosticsEngine::Ignored)
12621     return;
12622   // Avoid anonymous enums
12623   if (!Enum->getIdentifier())
12624     return;
12625 
12626   // Only check for small enums.
12627   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12628     return;
12629 
12630   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12631   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12632 
12633   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12634   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12635           ValueToVectorMap;
12636 
12637   DuplicatesVector DupVector;
12638   ValueToVectorMap EnumMap;
12639 
12640   // Populate the EnumMap with all values represented by enum constants without
12641   // an initialier.
12642   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12643     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12644 
12645     // Null EnumConstantDecl means a previous diagnostic has been emitted for
12646     // this constant.  Skip this enum since it may be ill-formed.
12647     if (!ECD) {
12648       return;
12649     }
12650 
12651     if (ECD->getInitExpr())
12652       continue;
12653 
12654     DupKey Key = GetDupKey(ECD->getInitVal());
12655     DeclOrVector &Entry = EnumMap[Key];
12656 
12657     // First time encountering this value.
12658     if (Entry.isNull())
12659       Entry = ECD;
12660   }
12661 
12662   // Create vectors for any values that has duplicates.
12663   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12664     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12665     if (!ValidDuplicateEnum(ECD, Enum))
12666       continue;
12667 
12668     DupKey Key = GetDupKey(ECD->getInitVal());
12669 
12670     DeclOrVector& Entry = EnumMap[Key];
12671     if (Entry.isNull())
12672       continue;
12673 
12674     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12675       // Ensure constants are different.
12676       if (D == ECD)
12677         continue;
12678 
12679       // Create new vector and push values onto it.
12680       ECDVector *Vec = new ECDVector();
12681       Vec->push_back(D);
12682       Vec->push_back(ECD);
12683 
12684       // Update entry to point to the duplicates vector.
12685       Entry = Vec;
12686 
12687       // Store the vector somewhere we can consult later for quick emission of
12688       // diagnostics.
12689       DupVector.push_back(Vec);
12690       continue;
12691     }
12692 
12693     ECDVector *Vec = Entry.get<ECDVector*>();
12694     // Make sure constants are not added more than once.
12695     if (*Vec->begin() == ECD)
12696       continue;
12697 
12698     Vec->push_back(ECD);
12699   }
12700 
12701   // Emit diagnostics.
12702   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12703                                   DupVectorEnd = DupVector.end();
12704        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12705     ECDVector *Vec = *DupVectorIter;
12706     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12707 
12708     // Emit warning for one enum constant.
12709     ECDVector::iterator I = Vec->begin();
12710     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12711       << (*I)->getName() << (*I)->getInitVal().toString(10)
12712       << (*I)->getSourceRange();
12713     ++I;
12714 
12715     // Emit one note for each of the remaining enum constants with
12716     // the same value.
12717     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12718       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12719         << (*I)->getName() << (*I)->getInitVal().toString(10)
12720         << (*I)->getSourceRange();
12721     delete Vec;
12722   }
12723 }
12724 
12725 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
12726                          SourceLocation RBraceLoc, Decl *EnumDeclX,
12727                          ArrayRef<Decl *> Elements,
12728                          Scope *S, AttributeList *Attr) {
12729   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
12730   QualType EnumType = Context.getTypeDeclType(Enum);
12731 
12732   if (Attr)
12733     ProcessDeclAttributeList(S, Enum, Attr);
12734 
12735   if (Enum->isDependentType()) {
12736     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12737       EnumConstantDecl *ECD =
12738         cast_or_null<EnumConstantDecl>(Elements[i]);
12739       if (!ECD) continue;
12740 
12741       ECD->setType(EnumType);
12742     }
12743 
12744     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
12745     return;
12746   }
12747 
12748   // TODO: If the result value doesn't fit in an int, it must be a long or long
12749   // long value.  ISO C does not support this, but GCC does as an extension,
12750   // emit a warning.
12751   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12752   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12753   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
12754 
12755   // Verify that all the values are okay, compute the size of the values, and
12756   // reverse the list.
12757   unsigned NumNegativeBits = 0;
12758   unsigned NumPositiveBits = 0;
12759 
12760   // Keep track of whether all elements have type int.
12761   bool AllElementsInt = true;
12762 
12763   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12764     EnumConstantDecl *ECD =
12765       cast_or_null<EnumConstantDecl>(Elements[i]);
12766     if (!ECD) continue;  // Already issued a diagnostic.
12767 
12768     const llvm::APSInt &InitVal = ECD->getInitVal();
12769 
12770     // Keep track of the size of positive and negative values.
12771     if (InitVal.isUnsigned() || InitVal.isNonNegative())
12772       NumPositiveBits = std::max(NumPositiveBits,
12773                                  (unsigned)InitVal.getActiveBits());
12774     else
12775       NumNegativeBits = std::max(NumNegativeBits,
12776                                  (unsigned)InitVal.getMinSignedBits());
12777 
12778     // Keep track of whether every enum element has type int (very commmon).
12779     if (AllElementsInt)
12780       AllElementsInt = ECD->getType() == Context.IntTy;
12781   }
12782 
12783   // Figure out the type that should be used for this enum.
12784   QualType BestType;
12785   unsigned BestWidth;
12786 
12787   // C++0x N3000 [conv.prom]p3:
12788   //   An rvalue of an unscoped enumeration type whose underlying
12789   //   type is not fixed can be converted to an rvalue of the first
12790   //   of the following types that can represent all the values of
12791   //   the enumeration: int, unsigned int, long int, unsigned long
12792   //   int, long long int, or unsigned long long int.
12793   // C99 6.4.4.3p2:
12794   //   An identifier declared as an enumeration constant has type int.
12795   // The C99 rule is modified by a gcc extension
12796   QualType BestPromotionType;
12797 
12798   bool Packed = Enum->hasAttr<PackedAttr>();
12799   // -fshort-enums is the equivalent to specifying the packed attribute on all
12800   // enum definitions.
12801   if (LangOpts.ShortEnums)
12802     Packed = true;
12803 
12804   if (Enum->isFixed()) {
12805     BestType = Enum->getIntegerType();
12806     if (BestType->isPromotableIntegerType())
12807       BestPromotionType = Context.getPromotedIntegerType(BestType);
12808     else
12809       BestPromotionType = BestType;
12810     // We don't need to set BestWidth, because BestType is going to be the type
12811     // of the enumerators, but we do anyway because otherwise some compilers
12812     // warn that it might be used uninitialized.
12813     BestWidth = CharWidth;
12814   }
12815   else if (NumNegativeBits) {
12816     // If there is a negative value, figure out the smallest integer type (of
12817     // int/long/longlong) that fits.
12818     // If it's packed, check also if it fits a char or a short.
12819     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
12820       BestType = Context.SignedCharTy;
12821       BestWidth = CharWidth;
12822     } else if (Packed && NumNegativeBits <= ShortWidth &&
12823                NumPositiveBits < ShortWidth) {
12824       BestType = Context.ShortTy;
12825       BestWidth = ShortWidth;
12826     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
12827       BestType = Context.IntTy;
12828       BestWidth = IntWidth;
12829     } else {
12830       BestWidth = Context.getTargetInfo().getLongWidth();
12831 
12832       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
12833         BestType = Context.LongTy;
12834       } else {
12835         BestWidth = Context.getTargetInfo().getLongLongWidth();
12836 
12837         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
12838           Diag(Enum->getLocation(), diag::warn_enum_too_large);
12839         BestType = Context.LongLongTy;
12840       }
12841     }
12842     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
12843   } else {
12844     // If there is no negative value, figure out the smallest type that fits
12845     // all of the enumerator values.
12846     // If it's packed, check also if it fits a char or a short.
12847     if (Packed && NumPositiveBits <= CharWidth) {
12848       BestType = Context.UnsignedCharTy;
12849       BestPromotionType = Context.IntTy;
12850       BestWidth = CharWidth;
12851     } else if (Packed && NumPositiveBits <= ShortWidth) {
12852       BestType = Context.UnsignedShortTy;
12853       BestPromotionType = Context.IntTy;
12854       BestWidth = ShortWidth;
12855     } else if (NumPositiveBits <= IntWidth) {
12856       BestType = Context.UnsignedIntTy;
12857       BestWidth = IntWidth;
12858       BestPromotionType
12859         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12860                            ? Context.UnsignedIntTy : Context.IntTy;
12861     } else if (NumPositiveBits <=
12862                (BestWidth = Context.getTargetInfo().getLongWidth())) {
12863       BestType = Context.UnsignedLongTy;
12864       BestPromotionType
12865         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12866                            ? Context.UnsignedLongTy : Context.LongTy;
12867     } else {
12868       BestWidth = Context.getTargetInfo().getLongLongWidth();
12869       assert(NumPositiveBits <= BestWidth &&
12870              "How could an initializer get larger than ULL?");
12871       BestType = Context.UnsignedLongLongTy;
12872       BestPromotionType
12873         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12874                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
12875     }
12876   }
12877 
12878   // Loop over all of the enumerator constants, changing their types to match
12879   // the type of the enum if needed.
12880   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12881     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12882     if (!ECD) continue;  // Already issued a diagnostic.
12883 
12884     // Standard C says the enumerators have int type, but we allow, as an
12885     // extension, the enumerators to be larger than int size.  If each
12886     // enumerator value fits in an int, type it as an int, otherwise type it the
12887     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
12888     // that X has type 'int', not 'unsigned'.
12889 
12890     // Determine whether the value fits into an int.
12891     llvm::APSInt InitVal = ECD->getInitVal();
12892 
12893     // If it fits into an integer type, force it.  Otherwise force it to match
12894     // the enum decl type.
12895     QualType NewTy;
12896     unsigned NewWidth;
12897     bool NewSign;
12898     if (!getLangOpts().CPlusPlus &&
12899         !Enum->isFixed() &&
12900         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
12901       NewTy = Context.IntTy;
12902       NewWidth = IntWidth;
12903       NewSign = true;
12904     } else if (ECD->getType() == BestType) {
12905       // Already the right type!
12906       if (getLangOpts().CPlusPlus)
12907         // C++ [dcl.enum]p4: Following the closing brace of an
12908         // enum-specifier, each enumerator has the type of its
12909         // enumeration.
12910         ECD->setType(EnumType);
12911       continue;
12912     } else {
12913       NewTy = BestType;
12914       NewWidth = BestWidth;
12915       NewSign = BestType->isSignedIntegerOrEnumerationType();
12916     }
12917 
12918     // Adjust the APSInt value.
12919     InitVal = InitVal.extOrTrunc(NewWidth);
12920     InitVal.setIsSigned(NewSign);
12921     ECD->setInitVal(InitVal);
12922 
12923     // Adjust the Expr initializer and type.
12924     if (ECD->getInitExpr() &&
12925         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
12926       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
12927                                                 CK_IntegralCast,
12928                                                 ECD->getInitExpr(),
12929                                                 /*base paths*/ 0,
12930                                                 VK_RValue));
12931     if (getLangOpts().CPlusPlus)
12932       // C++ [dcl.enum]p4: Following the closing brace of an
12933       // enum-specifier, each enumerator has the type of its
12934       // enumeration.
12935       ECD->setType(EnumType);
12936     else
12937       ECD->setType(NewTy);
12938   }
12939 
12940   Enum->completeDefinition(BestType, BestPromotionType,
12941                            NumPositiveBits, NumNegativeBits);
12942 
12943   // If we're declaring a function, ensure this decl isn't forgotten about -
12944   // it needs to go into the function scope.
12945   if (InFunctionDeclarator)
12946     DeclsInPrototypeScope.push_back(Enum);
12947 
12948   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
12949 
12950   // Now that the enum type is defined, ensure it's not been underaligned.
12951   if (Enum->hasAttrs())
12952     CheckAlignasUnderalignment(Enum);
12953 }
12954 
12955 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12956                                   SourceLocation StartLoc,
12957                                   SourceLocation EndLoc) {
12958   StringLiteral *AsmString = cast<StringLiteral>(expr);
12959 
12960   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
12961                                                    AsmString, StartLoc,
12962                                                    EndLoc);
12963   CurContext->addDecl(New);
12964   return New;
12965 }
12966 
12967 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12968                                    SourceLocation ImportLoc,
12969                                    ModuleIdPath Path) {
12970   Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
12971                                                 Module::AllVisible,
12972                                                 /*IsIncludeDirective=*/false);
12973   if (!Mod)
12974     return true;
12975 
12976   SmallVector<SourceLocation, 2> IdentifierLocs;
12977   Module *ModCheck = Mod;
12978   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12979     // If we've run out of module parents, just drop the remaining identifiers.
12980     // We need the length to be consistent.
12981     if (!ModCheck)
12982       break;
12983     ModCheck = ModCheck->Parent;
12984 
12985     IdentifierLocs.push_back(Path[I].second);
12986   }
12987 
12988   ImportDecl *Import = ImportDecl::Create(Context,
12989                                           Context.getTranslationUnitDecl(),
12990                                           AtLoc.isValid()? AtLoc : ImportLoc,
12991                                           Mod, IdentifierLocs);
12992   Context.getTranslationUnitDecl()->addDecl(Import);
12993   return Import;
12994 }
12995 
12996 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
12997   // FIXME: Should we synthesize an ImportDecl here?
12998   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc,
12999                                          /*Complain=*/true);
13000 }
13001 
13002 void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
13003   // Create the implicit import declaration.
13004   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
13005   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
13006                                                    Loc, Mod, Loc);
13007   TU->addDecl(ImportD);
13008   Consumer.HandleImplicitImportDecl(ImportD);
13009 
13010   // Make the module visible.
13011   PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
13012                                          /*Complain=*/false);
13013 }
13014 
13015 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
13016                                       IdentifierInfo* AliasName,
13017                                       SourceLocation PragmaLoc,
13018                                       SourceLocation NameLoc,
13019                                       SourceLocation AliasNameLoc) {
13020   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
13021                                     LookupOrdinaryName);
13022   AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context,
13023                                                     AliasName->getName(), 0);
13024 
13025   if (PrevDecl)
13026     PrevDecl->addAttr(Attr);
13027   else
13028     (void)ExtnameUndeclaredIdentifiers.insert(
13029       std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
13030 }
13031 
13032 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
13033                              SourceLocation PragmaLoc,
13034                              SourceLocation NameLoc) {
13035   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
13036 
13037   if (PrevDecl) {
13038     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
13039   } else {
13040     (void)WeakUndeclaredIdentifiers.insert(
13041       std::pair<IdentifierInfo*,WeakInfo>
13042         (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
13043   }
13044 }
13045 
13046 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
13047                                 IdentifierInfo* AliasName,
13048                                 SourceLocation PragmaLoc,
13049                                 SourceLocation NameLoc,
13050                                 SourceLocation AliasNameLoc) {
13051   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
13052                                     LookupOrdinaryName);
13053   WeakInfo W = WeakInfo(Name, NameLoc);
13054 
13055   if (PrevDecl) {
13056     if (!PrevDecl->hasAttr<AliasAttr>())
13057       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
13058         DeclApplyPragmaWeak(TUScope, ND, W);
13059   } else {
13060     (void)WeakUndeclaredIdentifiers.insert(
13061       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
13062   }
13063 }
13064 
13065 Decl *Sema::getObjCDeclContext() const {
13066   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
13067 }
13068 
13069 AvailabilityResult Sema::getCurContextAvailability() const {
13070   const Decl *D = cast<Decl>(getCurObjCLexicalContext());
13071   // If we are within an Objective-C method, we should consult
13072   // both the availability of the method as well as the
13073   // enclosing class.  If the class is (say) deprecated,
13074   // the entire method is considered deprecated from the
13075   // purpose of checking if the current context is deprecated.
13076   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
13077     AvailabilityResult R = MD->getAvailability();
13078     if (R != AR_Available)
13079       return R;
13080     D = MD->getClassInterface();
13081   }
13082   // If we are within an Objective-c @implementation, it
13083   // gets the same availability context as the @interface.
13084   else if (const ObjCImplementationDecl *ID =
13085             dyn_cast<ObjCImplementationDecl>(D)) {
13086     D = ID->getClassInterface();
13087   }
13088   return D->getAvailability();
13089 }
13090