SemaDecl.cpp revision c879fe57330faa87ac22f39ec6f37d992db9790f
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 "llvm/ADT/SmallString.h"
44#include "llvm/ADT/Triple.h"
45#include <algorithm>
46#include <cstring>
47#include <functional>
48using namespace clang;
49using namespace sema;
50
51Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
52  if (OwnedType) {
53    Decl *Group[2] = { OwnedType, Ptr };
54    return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
55  }
56
57  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
58}
59
60namespace {
61
62class TypeNameValidatorCCC : public CorrectionCandidateCallback {
63 public:
64  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false)
65      : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass) {
66    WantExpressionKeywords = false;
67    WantCXXNamedCasts = false;
68    WantRemainingKeywords = false;
69  }
70
71  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
72    if (NamedDecl *ND = candidate.getCorrectionDecl())
73      return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
74          (AllowInvalidDecl || !ND->isInvalidDecl());
75    else
76      return !WantClassName && candidate.isKeyword();
77  }
78
79 private:
80  bool AllowInvalidDecl;
81  bool WantClassName;
82};
83
84}
85
86/// \brief Determine whether the token kind starts a simple-type-specifier.
87bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
88  switch (Kind) {
89  // FIXME: Take into account the current language when deciding whether a
90  // token kind is a valid type specifier
91  case tok::kw_short:
92  case tok::kw_long:
93  case tok::kw___int64:
94  case tok::kw___int128:
95  case tok::kw_signed:
96  case tok::kw_unsigned:
97  case tok::kw_void:
98  case tok::kw_char:
99  case tok::kw_int:
100  case tok::kw_half:
101  case tok::kw_float:
102  case tok::kw_double:
103  case tok::kw_wchar_t:
104  case tok::kw_bool:
105  case tok::kw___underlying_type:
106    return true;
107
108  case tok::annot_typename:
109  case tok::kw_char16_t:
110  case tok::kw_char32_t:
111  case tok::kw_typeof:
112  case tok::annot_decltype:
113  case tok::kw_decltype:
114    return getLangOpts().CPlusPlus;
115
116  default:
117    break;
118  }
119
120  return false;
121}
122
123/// \brief If the identifier refers to a type name within this scope,
124/// return the declaration of that type.
125///
126/// This routine performs ordinary name lookup of the identifier II
127/// within the given scope, with optional C++ scope specifier SS, to
128/// determine whether the name refers to a type. If so, returns an
129/// opaque pointer (actually a QualType) corresponding to that
130/// type. Otherwise, returns NULL.
131ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
132                             Scope *S, CXXScopeSpec *SS,
133                             bool isClassName, bool HasTrailingDot,
134                             ParsedType ObjectTypePtr,
135                             bool IsCtorOrDtorName,
136                             bool WantNontrivialTypeSourceInfo,
137                             IdentifierInfo **CorrectedII) {
138  // Determine where we will perform name lookup.
139  DeclContext *LookupCtx = 0;
140  if (ObjectTypePtr) {
141    QualType ObjectType = ObjectTypePtr.get();
142    if (ObjectType->isRecordType())
143      LookupCtx = computeDeclContext(ObjectType);
144  } else if (SS && SS->isNotEmpty()) {
145    LookupCtx = computeDeclContext(*SS, false);
146
147    if (!LookupCtx) {
148      if (isDependentScopeSpecifier(*SS)) {
149        // C++ [temp.res]p3:
150        //   A qualified-id that refers to a type and in which the
151        //   nested-name-specifier depends on a template-parameter (14.6.2)
152        //   shall be prefixed by the keyword typename to indicate that the
153        //   qualified-id denotes a type, forming an
154        //   elaborated-type-specifier (7.1.5.3).
155        //
156        // We therefore do not perform any name lookup if the result would
157        // refer to a member of an unknown specialization.
158        if (!isClassName && !IsCtorOrDtorName)
159          return ParsedType();
160
161        // We know from the grammar that this name refers to a type,
162        // so build a dependent node to describe the type.
163        if (WantNontrivialTypeSourceInfo)
164          return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
165
166        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
167        QualType T =
168          CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
169                            II, NameLoc);
170
171          return ParsedType::make(T);
172      }
173
174      return ParsedType();
175    }
176
177    if (!LookupCtx->isDependentContext() &&
178        RequireCompleteDeclContext(*SS, LookupCtx))
179      return ParsedType();
180  }
181
182  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
183  // lookup for class-names.
184  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
185                                      LookupOrdinaryName;
186  LookupResult Result(*this, &II, NameLoc, Kind);
187  if (LookupCtx) {
188    // Perform "qualified" name lookup into the declaration context we
189    // computed, which is either the type of the base of a member access
190    // expression or the declaration context associated with a prior
191    // nested-name-specifier.
192    LookupQualifiedName(Result, LookupCtx);
193
194    if (ObjectTypePtr && Result.empty()) {
195      // C++ [basic.lookup.classref]p3:
196      //   If the unqualified-id is ~type-name, the type-name is looked up
197      //   in the context of the entire postfix-expression. If the type T of
198      //   the object expression is of a class type C, the type-name is also
199      //   looked up in the scope of class C. At least one of the lookups shall
200      //   find a name that refers to (possibly cv-qualified) T.
201      LookupName(Result, S);
202    }
203  } else {
204    // Perform unqualified name lookup.
205    LookupName(Result, S);
206  }
207
208  NamedDecl *IIDecl = 0;
209  switch (Result.getResultKind()) {
210  case LookupResult::NotFound:
211  case LookupResult::NotFoundInCurrentInstantiation:
212    if (CorrectedII) {
213      TypeNameValidatorCCC Validator(true, isClassName);
214      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(),
215                                              Kind, S, SS, Validator);
216      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
217      TemplateTy Template;
218      bool MemberOfUnknownSpecialization;
219      UnqualifiedId TemplateName;
220      TemplateName.setIdentifier(NewII, NameLoc);
221      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
222      CXXScopeSpec NewSS, *NewSSPtr = SS;
223      if (SS && NNS) {
224        NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
225        NewSSPtr = &NewSS;
226      }
227      if (Correction && (NNS || NewII != &II) &&
228          // Ignore a correction to a template type as the to-be-corrected
229          // identifier is not a template (typo correction for template names
230          // is handled elsewhere).
231          !(getLangOpts().CPlusPlus && NewSSPtr &&
232            isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
233                           false, Template, MemberOfUnknownSpecialization))) {
234        ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
235                                    isClassName, HasTrailingDot, ObjectTypePtr,
236                                    IsCtorOrDtorName,
237                                    WantNontrivialTypeSourceInfo);
238        if (Ty) {
239          diagnoseTypo(Correction,
240                       PDiag(diag::err_unknown_type_or_class_name_suggest)
241                         << Result.getLookupName() << isClassName);
242          if (SS && NNS)
243            SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
244          *CorrectedII = NewII;
245          return Ty;
246        }
247      }
248    }
249    // If typo correction failed or was not performed, fall through
250  case LookupResult::FoundOverloaded:
251  case LookupResult::FoundUnresolvedValue:
252    Result.suppressDiagnostics();
253    return ParsedType();
254
255  case LookupResult::Ambiguous:
256    // Recover from type-hiding ambiguities by hiding the type.  We'll
257    // do the lookup again when looking for an object, and we can
258    // diagnose the error then.  If we don't do this, then the error
259    // about hiding the type will be immediately followed by an error
260    // that only makes sense if the identifier was treated like a type.
261    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
262      Result.suppressDiagnostics();
263      return ParsedType();
264    }
265
266    // Look to see if we have a type anywhere in the list of results.
267    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
268         Res != ResEnd; ++Res) {
269      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
270        if (!IIDecl ||
271            (*Res)->getLocation().getRawEncoding() <
272              IIDecl->getLocation().getRawEncoding())
273          IIDecl = *Res;
274      }
275    }
276
277    if (!IIDecl) {
278      // None of the entities we found is a type, so there is no way
279      // to even assume that the result is a type. In this case, don't
280      // complain about the ambiguity. The parser will either try to
281      // perform this lookup again (e.g., as an object name), which
282      // will produce the ambiguity, or will complain that it expected
283      // a type name.
284      Result.suppressDiagnostics();
285      return ParsedType();
286    }
287
288    // We found a type within the ambiguous lookup; diagnose the
289    // ambiguity and then return that type. This might be the right
290    // answer, or it might not be, but it suppresses any attempt to
291    // perform the name lookup again.
292    break;
293
294  case LookupResult::Found:
295    IIDecl = Result.getFoundDecl();
296    break;
297  }
298
299  assert(IIDecl && "Didn't find decl");
300
301  QualType T;
302  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
303    DiagnoseUseOfDecl(IIDecl, NameLoc);
304
305    if (T.isNull())
306      T = Context.getTypeDeclType(TD);
307
308    // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
309    // constructor or destructor name (in such a case, the scope specifier
310    // will be attached to the enclosing Expr or Decl node).
311    if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
312      if (WantNontrivialTypeSourceInfo) {
313        // Construct a type with type-source information.
314        TypeLocBuilder Builder;
315        Builder.pushTypeSpec(T).setNameLoc(NameLoc);
316
317        T = getElaboratedType(ETK_None, *SS, T);
318        ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
319        ElabTL.setElaboratedKeywordLoc(SourceLocation());
320        ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
321        return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
322      } else {
323        T = getElaboratedType(ETK_None, *SS, T);
324      }
325    }
326  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
327    (void)DiagnoseUseOfDecl(IDecl, NameLoc);
328    if (!HasTrailingDot)
329      T = Context.getObjCInterfaceType(IDecl);
330  }
331
332  if (T.isNull()) {
333    // If it's not plausibly a type, suppress diagnostics.
334    Result.suppressDiagnostics();
335    return ParsedType();
336  }
337  return ParsedType::make(T);
338}
339
340/// isTagName() - This method is called *for error recovery purposes only*
341/// to determine if the specified name is a valid tag name ("struct foo").  If
342/// so, this returns the TST for the tag corresponding to it (TST_enum,
343/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
344/// cases in C where the user forgot to specify the tag.
345DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
346  // Do a tag name lookup in this scope.
347  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
348  LookupName(R, S, false);
349  R.suppressDiagnostics();
350  if (R.getResultKind() == LookupResult::Found)
351    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
352      switch (TD->getTagKind()) {
353      case TTK_Struct: return DeclSpec::TST_struct;
354      case TTK_Interface: return DeclSpec::TST_interface;
355      case TTK_Union:  return DeclSpec::TST_union;
356      case TTK_Class:  return DeclSpec::TST_class;
357      case TTK_Enum:   return DeclSpec::TST_enum;
358      }
359    }
360
361  return DeclSpec::TST_unspecified;
362}
363
364/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
365/// if a CXXScopeSpec's type is equal to the type of one of the base classes
366/// then downgrade the missing typename error to a warning.
367/// This is needed for MSVC compatibility; Example:
368/// @code
369/// template<class T> class A {
370/// public:
371///   typedef int TYPE;
372/// };
373/// template<class T> class B : public A<T> {
374/// public:
375///   A<T>::TYPE a; // no typename required because A<T> is a base class.
376/// };
377/// @endcode
378bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
379  if (CurContext->isRecord()) {
380    const Type *Ty = SS->getScopeRep()->getAsType();
381
382    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
383    for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
384          BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base)
385      if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType()))
386        return true;
387    return S->isFunctionPrototypeScope();
388  }
389  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
390}
391
392bool Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
393                                   SourceLocation IILoc,
394                                   Scope *S,
395                                   CXXScopeSpec *SS,
396                                   ParsedType &SuggestedType) {
397  // We don't have anything to suggest (yet).
398  SuggestedType = ParsedType();
399
400  // There may have been a typo in the name of the type. Look up typo
401  // results, in case we have something that we can suggest.
402  TypeNameValidatorCCC Validator(false);
403  if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc),
404                                             LookupOrdinaryName, S, SS,
405                                             Validator)) {
406    if (Corrected.isKeyword()) {
407      // We corrected to a keyword.
408      diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
409      II = Corrected.getCorrectionAsIdentifierInfo();
410    } else {
411      // We found a similarly-named type or interface; suggest that.
412      if (!SS || !SS->isSet()) {
413        diagnoseTypo(Corrected,
414                     PDiag(diag::err_unknown_typename_suggest) << II);
415      } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
416        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
417        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
418                                II->getName().equals(CorrectedStr);
419        diagnoseTypo(Corrected,
420                     PDiag(diag::err_unknown_nested_typename_suggest)
421                       << II << DC << DroppedSpecifier << SS->getRange());
422      } else {
423        llvm_unreachable("could not have corrected a typo here");
424      }
425
426      CXXScopeSpec tmpSS;
427      if (Corrected.getCorrectionSpecifier())
428        tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
429                          SourceRange(IILoc));
430      SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
431                                  IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
432                                  false, ParsedType(),
433                                  /*IsCtorOrDtorName=*/false,
434                                  /*NonTrivialTypeSourceInfo=*/true);
435    }
436    return true;
437  }
438
439  if (getLangOpts().CPlusPlus) {
440    // See if II is a class template that the user forgot to pass arguments to.
441    UnqualifiedId Name;
442    Name.setIdentifier(II, IILoc);
443    CXXScopeSpec EmptySS;
444    TemplateTy TemplateResult;
445    bool MemberOfUnknownSpecialization;
446    if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
447                       Name, ParsedType(), true, TemplateResult,
448                       MemberOfUnknownSpecialization) == TNK_Type_template) {
449      TemplateName TplName = TemplateResult.get();
450      Diag(IILoc, diag::err_template_missing_args) << TplName;
451      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
452        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
453          << TplDecl->getTemplateParameters()->getSourceRange();
454      }
455      return true;
456    }
457  }
458
459  // FIXME: Should we move the logic that tries to recover from a missing tag
460  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
461
462  if (!SS || (!SS->isSet() && !SS->isInvalid()))
463    Diag(IILoc, diag::err_unknown_typename) << II;
464  else if (DeclContext *DC = computeDeclContext(*SS, false))
465    Diag(IILoc, diag::err_typename_nested_not_found)
466      << II << DC << SS->getRange();
467  else if (isDependentScopeSpecifier(*SS)) {
468    unsigned DiagID = diag::err_typename_missing;
469    if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S))
470      DiagID = diag::warn_typename_missing;
471
472    Diag(SS->getRange().getBegin(), DiagID)
473      << (NestedNameSpecifier *)SS->getScopeRep() << II->getName()
474      << SourceRange(SS->getRange().getBegin(), IILoc)
475      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
476    SuggestedType = ActOnTypenameType(S, SourceLocation(),
477                                      *SS, *II, IILoc).get();
478  } else {
479    assert(SS && SS->isInvalid() &&
480           "Invalid scope specifier has already been diagnosed");
481  }
482
483  return true;
484}
485
486/// \brief Determine whether the given result set contains either a type name
487/// or
488static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
489  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
490                       NextToken.is(tok::less);
491
492  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
493    if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
494      return true;
495
496    if (CheckTemplate && isa<TemplateDecl>(*I))
497      return true;
498  }
499
500  return false;
501}
502
503static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
504                                    Scope *S, CXXScopeSpec &SS,
505                                    IdentifierInfo *&Name,
506                                    SourceLocation NameLoc) {
507  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
508  SemaRef.LookupParsedName(R, S, &SS);
509  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
510    const char *TagName = 0;
511    const char *FixItTagName = 0;
512    switch (Tag->getTagKind()) {
513      case TTK_Class:
514        TagName = "class";
515        FixItTagName = "class ";
516        break;
517
518      case TTK_Enum:
519        TagName = "enum";
520        FixItTagName = "enum ";
521        break;
522
523      case TTK_Struct:
524        TagName = "struct";
525        FixItTagName = "struct ";
526        break;
527
528      case TTK_Interface:
529        TagName = "__interface";
530        FixItTagName = "__interface ";
531        break;
532
533      case TTK_Union:
534        TagName = "union";
535        FixItTagName = "union ";
536        break;
537    }
538
539    SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
540      << Name << TagName << SemaRef.getLangOpts().CPlusPlus
541      << FixItHint::CreateInsertion(NameLoc, FixItTagName);
542
543    for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
544         I != IEnd; ++I)
545      SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
546        << Name << TagName;
547
548    // Replace lookup results with just the tag decl.
549    Result.clear(Sema::LookupTagName);
550    SemaRef.LookupParsedName(Result, S, &SS);
551    return true;
552  }
553
554  return false;
555}
556
557/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
558static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
559                                  QualType T, SourceLocation NameLoc) {
560  ASTContext &Context = S.Context;
561
562  TypeLocBuilder Builder;
563  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
564
565  T = S.getElaboratedType(ETK_None, SS, T);
566  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
567  ElabTL.setElaboratedKeywordLoc(SourceLocation());
568  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
569  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
570}
571
572Sema::NameClassification Sema::ClassifyName(Scope *S,
573                                            CXXScopeSpec &SS,
574                                            IdentifierInfo *&Name,
575                                            SourceLocation NameLoc,
576                                            const Token &NextToken,
577                                            bool IsAddressOfOperand,
578                                            CorrectionCandidateCallback *CCC) {
579  DeclarationNameInfo NameInfo(Name, NameLoc);
580  ObjCMethodDecl *CurMethod = getCurMethodDecl();
581
582  if (NextToken.is(tok::coloncolon)) {
583    BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
584                                QualType(), false, SS, 0, false);
585
586  }
587
588  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
589  LookupParsedName(Result, S, &SS, !CurMethod);
590
591  // Perform lookup for Objective-C instance variables (including automatically
592  // synthesized instance variables), if we're in an Objective-C method.
593  // FIXME: This lookup really, really needs to be folded in to the normal
594  // unqualified lookup mechanism.
595  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
596    ExprResult E = LookupInObjCMethod(Result, S, Name, true);
597    if (E.get() || E.isInvalid())
598      return E;
599  }
600
601  bool SecondTry = false;
602  bool IsFilteredTemplateName = false;
603
604Corrected:
605  switch (Result.getResultKind()) {
606  case LookupResult::NotFound:
607    // If an unqualified-id is followed by a '(', then we have a function
608    // call.
609    if (!SS.isSet() && NextToken.is(tok::l_paren)) {
610      // In C++, this is an ADL-only call.
611      // FIXME: Reference?
612      if (getLangOpts().CPlusPlus)
613        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
614
615      // C90 6.3.2.2:
616      //   If the expression that precedes the parenthesized argument list in a
617      //   function call consists solely of an identifier, and if no
618      //   declaration is visible for this identifier, the identifier is
619      //   implicitly declared exactly as if, in the innermost block containing
620      //   the function call, the declaration
621      //
622      //     extern int identifier ();
623      //
624      //   appeared.
625      //
626      // We also allow this in C99 as an extension.
627      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
628        Result.addDecl(D);
629        Result.resolveKind();
630        return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
631      }
632    }
633
634    // In C, we first see whether there is a tag type by the same name, in
635    // which case it's likely that the user just forget to write "enum",
636    // "struct", or "union".
637    if (!getLangOpts().CPlusPlus && !SecondTry &&
638        isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
639      break;
640    }
641
642    // Perform typo correction to determine if there is another name that is
643    // close to this name.
644    if (!SecondTry && CCC) {
645      SecondTry = true;
646      if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
647                                                 Result.getLookupKind(), S,
648                                                 &SS, *CCC)) {
649        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
650        unsigned QualifiedDiag = diag::err_no_member_suggest;
651
652        NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
653        NamedDecl *UnderlyingFirstDecl
654          = FirstDecl? FirstDecl->getUnderlyingDecl() : 0;
655        if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
656            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
657          UnqualifiedDiag = diag::err_no_template_suggest;
658          QualifiedDiag = diag::err_no_member_template_suggest;
659        } else if (UnderlyingFirstDecl &&
660                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
661                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
662                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
663          UnqualifiedDiag = diag::err_unknown_typename_suggest;
664          QualifiedDiag = diag::err_unknown_nested_typename_suggest;
665        }
666
667        if (SS.isEmpty()) {
668          diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
669        } else {// FIXME: is this even reachable? Test it.
670          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
671          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
672                                  Name->getName().equals(CorrectedStr);
673          diagnoseTypo(Corrected, PDiag(QualifiedDiag)
674                                    << Name << computeDeclContext(SS, false)
675                                    << DroppedSpecifier << SS.getRange());
676        }
677
678        // Update the name, so that the caller has the new name.
679        Name = Corrected.getCorrectionAsIdentifierInfo();
680
681        // Typo correction corrected to a keyword.
682        if (Corrected.isKeyword())
683          return Name;
684
685        // Also update the LookupResult...
686        // FIXME: This should probably go away at some point
687        Result.clear();
688        Result.setLookupName(Corrected.getCorrection());
689        if (FirstDecl)
690          Result.addDecl(FirstDecl);
691
692        // If we found an Objective-C instance variable, let
693        // LookupInObjCMethod build the appropriate expression to
694        // reference the ivar.
695        // FIXME: This is a gross hack.
696        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
697          Result.clear();
698          ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
699          return E;
700        }
701
702        goto Corrected;
703      }
704    }
705
706    // We failed to correct; just fall through and let the parser deal with it.
707    Result.suppressDiagnostics();
708    return NameClassification::Unknown();
709
710  case LookupResult::NotFoundInCurrentInstantiation: {
711    // We performed name lookup into the current instantiation, and there were
712    // dependent bases, so we treat this result the same way as any other
713    // dependent nested-name-specifier.
714
715    // C++ [temp.res]p2:
716    //   A name used in a template declaration or definition and that is
717    //   dependent on a template-parameter is assumed not to name a type
718    //   unless the applicable name lookup finds a type name or the name is
719    //   qualified by the keyword typename.
720    //
721    // FIXME: If the next token is '<', we might want to ask the parser to
722    // perform some heroics to see if we actually have a
723    // template-argument-list, which would indicate a missing 'template'
724    // keyword here.
725    return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
726                                      NameInfo, IsAddressOfOperand,
727                                      /*TemplateArgs=*/0);
728  }
729
730  case LookupResult::Found:
731  case LookupResult::FoundOverloaded:
732  case LookupResult::FoundUnresolvedValue:
733    break;
734
735  case LookupResult::Ambiguous:
736    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
737        hasAnyAcceptableTemplateNames(Result)) {
738      // C++ [temp.local]p3:
739      //   A lookup that finds an injected-class-name (10.2) can result in an
740      //   ambiguity in certain cases (for example, if it is found in more than
741      //   one base class). If all of the injected-class-names that are found
742      //   refer to specializations of the same class template, and if the name
743      //   is followed by a template-argument-list, the reference refers to the
744      //   class template itself and not a specialization thereof, and is not
745      //   ambiguous.
746      //
747      // This filtering can make an ambiguous result into an unambiguous one,
748      // so try again after filtering out template names.
749      FilterAcceptableTemplateNames(Result);
750      if (!Result.isAmbiguous()) {
751        IsFilteredTemplateName = true;
752        break;
753      }
754    }
755
756    // Diagnose the ambiguity and return an error.
757    return NameClassification::Error();
758  }
759
760  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
761      (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
762    // C++ [temp.names]p3:
763    //   After name lookup (3.4) finds that a name is a template-name or that
764    //   an operator-function-id or a literal- operator-id refers to a set of
765    //   overloaded functions any member of which is a function template if
766    //   this is followed by a <, the < is always taken as the delimiter of a
767    //   template-argument-list and never as the less-than operator.
768    if (!IsFilteredTemplateName)
769      FilterAcceptableTemplateNames(Result);
770
771    if (!Result.empty()) {
772      bool IsFunctionTemplate;
773      bool IsVarTemplate;
774      TemplateName Template;
775      if (Result.end() - Result.begin() > 1) {
776        IsFunctionTemplate = true;
777        Template = Context.getOverloadedTemplateName(Result.begin(),
778                                                     Result.end());
779      } else {
780        TemplateDecl *TD
781          = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
782        IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
783        IsVarTemplate = isa<VarTemplateDecl>(TD);
784
785        if (SS.isSet() && !SS.isInvalid())
786          Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
787                                                    /*TemplateKeyword=*/false,
788                                                      TD);
789        else
790          Template = TemplateName(TD);
791      }
792
793      if (IsFunctionTemplate) {
794        // Function templates always go through overload resolution, at which
795        // point we'll perform the various checks (e.g., accessibility) we need
796        // to based on which function we selected.
797        Result.suppressDiagnostics();
798
799        return NameClassification::FunctionTemplate(Template);
800      }
801
802      return IsVarTemplate ? NameClassification::VarTemplate(Template)
803                           : NameClassification::TypeTemplate(Template);
804    }
805  }
806
807  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
808  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
809    DiagnoseUseOfDecl(Type, NameLoc);
810    QualType T = Context.getTypeDeclType(Type);
811    if (SS.isNotEmpty())
812      return buildNestedType(*this, SS, T, NameLoc);
813    return ParsedType::make(T);
814  }
815
816  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
817  if (!Class) {
818    // FIXME: It's unfortunate that we don't have a Type node for handling this.
819    if (ObjCCompatibleAliasDecl *Alias
820                                = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
821      Class = Alias->getClassInterface();
822  }
823
824  if (Class) {
825    DiagnoseUseOfDecl(Class, NameLoc);
826
827    if (NextToken.is(tok::period)) {
828      // Interface. <something> is parsed as a property reference expression.
829      // Just return "unknown" as a fall-through for now.
830      Result.suppressDiagnostics();
831      return NameClassification::Unknown();
832    }
833
834    QualType T = Context.getObjCInterfaceType(Class);
835    return ParsedType::make(T);
836  }
837
838  // We can have a type template here if we're classifying a template argument.
839  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
840    return NameClassification::TypeTemplate(
841        TemplateName(cast<TemplateDecl>(FirstDecl)));
842
843  // Check for a tag type hidden by a non-type decl in a few cases where it
844  // seems likely a type is wanted instead of the non-type that was found.
845  bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star);
846  if ((NextToken.is(tok::identifier) ||
847       (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) &&
848      isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
849    TypeDecl *Type = Result.getAsSingle<TypeDecl>();
850    DiagnoseUseOfDecl(Type, NameLoc);
851    QualType T = Context.getTypeDeclType(Type);
852    if (SS.isNotEmpty())
853      return buildNestedType(*this, SS, T, NameLoc);
854    return ParsedType::make(T);
855  }
856
857  if (FirstDecl->isCXXClassMember())
858    return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0);
859
860  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
861  return BuildDeclarationNameExpr(SS, Result, ADL);
862}
863
864// Determines the context to return to after temporarily entering a
865// context.  This depends in an unnecessarily complicated way on the
866// exact ordering of callbacks from the parser.
867DeclContext *Sema::getContainingDC(DeclContext *DC) {
868
869  // Functions defined inline within classes aren't parsed until we've
870  // finished parsing the top-level class, so the top-level class is
871  // the context we'll need to return to.
872  if (isa<FunctionDecl>(DC)) {
873    DC = DC->getLexicalParent();
874
875    // A function not defined within a class will always return to its
876    // lexical context.
877    if (!isa<CXXRecordDecl>(DC))
878      return DC;
879
880    // A C++ inline method/friend is parsed *after* the topmost class
881    // it was declared in is fully parsed ("complete");  the topmost
882    // class is the context we need to return to.
883    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
884      DC = RD;
885
886    // Return the declaration context of the topmost class the inline method is
887    // declared in.
888    return DC;
889  }
890
891  return DC->getLexicalParent();
892}
893
894void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
895  assert(getContainingDC(DC) == CurContext &&
896      "The next DeclContext should be lexically contained in the current one.");
897  CurContext = DC;
898  S->setEntity(DC);
899}
900
901void Sema::PopDeclContext() {
902  assert(CurContext && "DeclContext imbalance!");
903
904  CurContext = getContainingDC(CurContext);
905  assert(CurContext && "Popped translation unit!");
906}
907
908/// EnterDeclaratorContext - Used when we must lookup names in the context
909/// of a declarator's nested name specifier.
910///
911void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
912  // C++0x [basic.lookup.unqual]p13:
913  //   A name used in the definition of a static data member of class
914  //   X (after the qualified-id of the static member) is looked up as
915  //   if the name was used in a member function of X.
916  // C++0x [basic.lookup.unqual]p14:
917  //   If a variable member of a namespace is defined outside of the
918  //   scope of its namespace then any name used in the definition of
919  //   the variable member (after the declarator-id) is looked up as
920  //   if the definition of the variable member occurred in its
921  //   namespace.
922  // Both of these imply that we should push a scope whose context
923  // is the semantic context of the declaration.  We can't use
924  // PushDeclContext here because that context is not necessarily
925  // lexically contained in the current context.  Fortunately,
926  // the containing scope should have the appropriate information.
927
928  assert(!S->getEntity() && "scope already has entity");
929
930#ifndef NDEBUG
931  Scope *Ancestor = S->getParent();
932  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
933  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
934#endif
935
936  CurContext = DC;
937  S->setEntity(DC);
938}
939
940void Sema::ExitDeclaratorContext(Scope *S) {
941  assert(S->getEntity() == CurContext && "Context imbalance!");
942
943  // Switch back to the lexical context.  The safety of this is
944  // enforced by an assert in EnterDeclaratorContext.
945  Scope *Ancestor = S->getParent();
946  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
947  CurContext = Ancestor->getEntity();
948
949  // We don't need to do anything with the scope, which is going to
950  // disappear.
951}
952
953
954void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
955  FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
956  if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) {
957    // We assume that the caller has already called
958    // ActOnReenterTemplateScope
959    FD = TFD->getTemplatedDecl();
960  }
961  if (!FD)
962    return;
963
964  // Same implementation as PushDeclContext, but enters the context
965  // from the lexical parent, rather than the top-level class.
966  assert(CurContext == FD->getLexicalParent() &&
967    "The next DeclContext should be lexically contained in the current one.");
968  CurContext = FD;
969  S->setEntity(CurContext);
970
971  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
972    ParmVarDecl *Param = FD->getParamDecl(P);
973    // If the parameter has an identifier, then add it to the scope
974    if (Param->getIdentifier()) {
975      S->AddDecl(Param);
976      IdResolver.AddDecl(Param);
977    }
978  }
979}
980
981
982void Sema::ActOnExitFunctionContext() {
983  // Same implementation as PopDeclContext, but returns to the lexical parent,
984  // rather than the top-level class.
985  assert(CurContext && "DeclContext imbalance!");
986  CurContext = CurContext->getLexicalParent();
987  assert(CurContext && "Popped translation unit!");
988}
989
990
991/// \brief Determine whether we allow overloading of the function
992/// PrevDecl with another declaration.
993///
994/// This routine determines whether overloading is possible, not
995/// whether some new function is actually an overload. It will return
996/// true in C++ (where we can always provide overloads) or, as an
997/// extension, in C when the previous function is already an
998/// overloaded function declaration or has the "overloadable"
999/// attribute.
1000static bool AllowOverloadingOfFunction(LookupResult &Previous,
1001                                       ASTContext &Context) {
1002  if (Context.getLangOpts().CPlusPlus)
1003    return true;
1004
1005  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1006    return true;
1007
1008  return (Previous.getResultKind() == LookupResult::Found
1009          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1010}
1011
1012/// Add this decl to the scope shadowed decl chains.
1013void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1014  // Move up the scope chain until we find the nearest enclosing
1015  // non-transparent context. The declaration will be introduced into this
1016  // scope.
1017  while (S->getEntity() && S->getEntity()->isTransparentContext())
1018    S = S->getParent();
1019
1020  // Add scoped declarations into their context, so that they can be
1021  // found later. Declarations without a context won't be inserted
1022  // into any context.
1023  if (AddToContext)
1024    CurContext->addDecl(D);
1025
1026  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1027  // are function-local declarations.
1028  if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1029      !D->getDeclContext()->getRedeclContext()->Equals(
1030        D->getLexicalDeclContext()->getRedeclContext()) &&
1031      !D->getLexicalDeclContext()->isFunctionOrMethod())
1032    return;
1033
1034  // Template instantiations should also not be pushed into scope.
1035  if (isa<FunctionDecl>(D) &&
1036      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1037    return;
1038
1039  // If this replaces anything in the current scope,
1040  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1041                               IEnd = IdResolver.end();
1042  for (; I != IEnd; ++I) {
1043    if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1044      S->RemoveDecl(*I);
1045      IdResolver.RemoveDecl(*I);
1046
1047      // Should only need to replace one decl.
1048      break;
1049    }
1050  }
1051
1052  S->AddDecl(D);
1053
1054  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1055    // Implicitly-generated labels may end up getting generated in an order that
1056    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1057    // the label at the appropriate place in the identifier chain.
1058    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1059      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1060      if (IDC == CurContext) {
1061        if (!S->isDeclScope(*I))
1062          continue;
1063      } else if (IDC->Encloses(CurContext))
1064        break;
1065    }
1066
1067    IdResolver.InsertDeclAfter(I, D);
1068  } else {
1069    IdResolver.AddDecl(D);
1070  }
1071}
1072
1073void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1074  if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1075    TUScope->AddDecl(D);
1076}
1077
1078bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1079                         bool ExplicitInstantiationOrSpecialization) {
1080  return IdResolver.isDeclInScope(D, Ctx, S,
1081                                  ExplicitInstantiationOrSpecialization);
1082}
1083
1084Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1085  DeclContext *TargetDC = DC->getPrimaryContext();
1086  do {
1087    if (DeclContext *ScopeDC = S->getEntity())
1088      if (ScopeDC->getPrimaryContext() == TargetDC)
1089        return S;
1090  } while ((S = S->getParent()));
1091
1092  return 0;
1093}
1094
1095static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1096                                            DeclContext*,
1097                                            ASTContext&);
1098
1099/// Filters out lookup results that don't fall within the given scope
1100/// as determined by isDeclInScope.
1101void Sema::FilterLookupForScope(LookupResult &R,
1102                                DeclContext *Ctx, Scope *S,
1103                                bool ConsiderLinkage,
1104                                bool ExplicitInstantiationOrSpecialization) {
1105  LookupResult::Filter F = R.makeFilter();
1106  while (F.hasNext()) {
1107    NamedDecl *D = F.next();
1108
1109    if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization))
1110      continue;
1111
1112    if (ConsiderLinkage &&
1113        isOutOfScopePreviousDeclaration(D, Ctx, Context))
1114      continue;
1115
1116    F.erase();
1117  }
1118
1119  F.done();
1120}
1121
1122static bool isUsingDecl(NamedDecl *D) {
1123  return isa<UsingShadowDecl>(D) ||
1124         isa<UnresolvedUsingTypenameDecl>(D) ||
1125         isa<UnresolvedUsingValueDecl>(D);
1126}
1127
1128/// Removes using shadow declarations from the lookup results.
1129static void RemoveUsingDecls(LookupResult &R) {
1130  LookupResult::Filter F = R.makeFilter();
1131  while (F.hasNext())
1132    if (isUsingDecl(F.next()))
1133      F.erase();
1134
1135  F.done();
1136}
1137
1138/// \brief Check for this common pattern:
1139/// @code
1140/// class S {
1141///   S(const S&); // DO NOT IMPLEMENT
1142///   void operator=(const S&); // DO NOT IMPLEMENT
1143/// };
1144/// @endcode
1145static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1146  // FIXME: Should check for private access too but access is set after we get
1147  // the decl here.
1148  if (D->doesThisDeclarationHaveABody())
1149    return false;
1150
1151  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1152    return CD->isCopyConstructor();
1153  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1154    return Method->isCopyAssignmentOperator();
1155  return false;
1156}
1157
1158// We need this to handle
1159//
1160// typedef struct {
1161//   void *foo() { return 0; }
1162// } A;
1163//
1164// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1165// for example. If 'A', foo will have external linkage. If we have '*A',
1166// foo will have no linkage. Since we can't know untill we get to the end
1167// of the typedef, this function finds out if D might have non external linkage.
1168// Callers should verify at the end of the TU if it D has external linkage or
1169// not.
1170bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1171  const DeclContext *DC = D->getDeclContext();
1172  while (!DC->isTranslationUnit()) {
1173    if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1174      if (!RD->hasNameForLinkage())
1175        return true;
1176    }
1177    DC = DC->getParent();
1178  }
1179
1180  return !D->isExternallyVisible();
1181}
1182
1183// FIXME: This needs to be refactored; some other isInMainFile users want
1184// these semantics.
1185static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1186  if (S.TUKind != TU_Complete)
1187    return false;
1188  return S.SourceMgr.isInMainFile(Loc);
1189}
1190
1191bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1192  assert(D);
1193
1194  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1195    return false;
1196
1197  // Ignore class templates.
1198  if (D->getDeclContext()->isDependentContext() ||
1199      D->getLexicalDeclContext()->isDependentContext())
1200    return false;
1201
1202  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1203    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1204      return false;
1205
1206    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1207      if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1208        return false;
1209    } else {
1210      // 'static inline' functions are defined in headers; don't warn.
1211      if (FD->isInlineSpecified() &&
1212          !isMainFileLoc(*this, FD->getLocation()))
1213        return false;
1214    }
1215
1216    if (FD->doesThisDeclarationHaveABody() &&
1217        Context.DeclMustBeEmitted(FD))
1218      return false;
1219  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1220    // Constants and utility variables are defined in headers with internal
1221    // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1222    // like "inline".)
1223    if (!isMainFileLoc(*this, VD->getLocation()))
1224      return false;
1225
1226    if (Context.DeclMustBeEmitted(VD))
1227      return false;
1228
1229    if (VD->isStaticDataMember() &&
1230        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1231      return false;
1232  } else {
1233    return false;
1234  }
1235
1236  // Only warn for unused decls internal to the translation unit.
1237  return mightHaveNonExternalLinkage(D);
1238}
1239
1240void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1241  if (!D)
1242    return;
1243
1244  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1245    const FunctionDecl *First = FD->getFirstDecl();
1246    if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1247      return; // First should already be in the vector.
1248  }
1249
1250  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1251    const VarDecl *First = VD->getFirstDecl();
1252    if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1253      return; // First should already be in the vector.
1254  }
1255
1256  if (ShouldWarnIfUnusedFileScopedDecl(D))
1257    UnusedFileScopedDecls.push_back(D);
1258}
1259
1260static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1261  if (D->isInvalidDecl())
1262    return false;
1263
1264  if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>())
1265    return false;
1266
1267  if (isa<LabelDecl>(D))
1268    return true;
1269
1270  // White-list anything that isn't a local variable.
1271  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
1272      !D->getDeclContext()->isFunctionOrMethod())
1273    return false;
1274
1275  // Types of valid local variables should be complete, so this should succeed.
1276  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1277
1278    // White-list anything with an __attribute__((unused)) type.
1279    QualType Ty = VD->getType();
1280
1281    // Only look at the outermost level of typedef.
1282    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1283      if (TT->getDecl()->hasAttr<UnusedAttr>())
1284        return false;
1285    }
1286
1287    // If we failed to complete the type for some reason, or if the type is
1288    // dependent, don't diagnose the variable.
1289    if (Ty->isIncompleteType() || Ty->isDependentType())
1290      return false;
1291
1292    if (const TagType *TT = Ty->getAs<TagType>()) {
1293      const TagDecl *Tag = TT->getDecl();
1294      if (Tag->hasAttr<UnusedAttr>())
1295        return false;
1296
1297      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1298        if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1299          return false;
1300
1301        if (const Expr *Init = VD->getInit()) {
1302          if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(Init))
1303            Init = Cleanups->getSubExpr();
1304          const CXXConstructExpr *Construct =
1305            dyn_cast<CXXConstructExpr>(Init);
1306          if (Construct && !Construct->isElidable()) {
1307            CXXConstructorDecl *CD = Construct->getConstructor();
1308            if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1309              return false;
1310          }
1311        }
1312      }
1313    }
1314
1315    // TODO: __attribute__((unused)) templates?
1316  }
1317
1318  return true;
1319}
1320
1321static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1322                                     FixItHint &Hint) {
1323  if (isa<LabelDecl>(D)) {
1324    SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1325                tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1326    if (AfterColon.isInvalid())
1327      return;
1328    Hint = FixItHint::CreateRemoval(CharSourceRange::
1329                                    getCharRange(D->getLocStart(), AfterColon));
1330  }
1331  return;
1332}
1333
1334/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1335/// unless they are marked attr(unused).
1336void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1337  FixItHint Hint;
1338  if (!ShouldDiagnoseUnusedDecl(D))
1339    return;
1340
1341  GenerateFixForUnusedDecl(D, Context, Hint);
1342
1343  unsigned DiagID;
1344  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1345    DiagID = diag::warn_unused_exception_param;
1346  else if (isa<LabelDecl>(D))
1347    DiagID = diag::warn_unused_label;
1348  else
1349    DiagID = diag::warn_unused_variable;
1350
1351  Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1352}
1353
1354static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1355  // Verify that we have no forward references left.  If so, there was a goto
1356  // or address of a label taken, but no definition of it.  Label fwd
1357  // definitions are indicated with a null substmt.
1358  if (L->getStmt() == 0)
1359    S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1360}
1361
1362void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1363  if (S->decl_empty()) return;
1364  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1365         "Scope shouldn't contain decls!");
1366
1367  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
1368       I != E; ++I) {
1369    Decl *TmpD = (*I);
1370    assert(TmpD && "This decl didn't get pushed??");
1371
1372    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1373    NamedDecl *D = cast<NamedDecl>(TmpD);
1374
1375    if (!D->getDeclName()) continue;
1376
1377    // Diagnose unused variables in this scope.
1378    if (!S->hasUnrecoverableErrorOccurred())
1379      DiagnoseUnusedDecl(D);
1380
1381    // If this was a forward reference to a label, verify it was defined.
1382    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1383      CheckPoppedLabel(LD, *this);
1384
1385    // Remove this name from our lexical scope.
1386    IdResolver.RemoveDecl(D);
1387  }
1388  DiagnoseUnusedBackingIvarInAccessor(S);
1389}
1390
1391void Sema::ActOnStartFunctionDeclarator() {
1392  ++InFunctionDeclarator;
1393}
1394
1395void Sema::ActOnEndFunctionDeclarator() {
1396  assert(InFunctionDeclarator);
1397  --InFunctionDeclarator;
1398}
1399
1400/// \brief Look for an Objective-C class in the translation unit.
1401///
1402/// \param Id The name of the Objective-C class we're looking for. If
1403/// typo-correction fixes this name, the Id will be updated
1404/// to the fixed name.
1405///
1406/// \param IdLoc The location of the name in the translation unit.
1407///
1408/// \param DoTypoCorrection If true, this routine will attempt typo correction
1409/// if there is no class with the given name.
1410///
1411/// \returns The declaration of the named Objective-C class, or NULL if the
1412/// class could not be found.
1413ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1414                                              SourceLocation IdLoc,
1415                                              bool DoTypoCorrection) {
1416  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1417  // creation from this context.
1418  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1419
1420  if (!IDecl && DoTypoCorrection) {
1421    // Perform typo correction at the given location, but only if we
1422    // find an Objective-C class name.
1423    DeclFilterCCC<ObjCInterfaceDecl> Validator;
1424    if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc),
1425                                       LookupOrdinaryName, TUScope, NULL,
1426                                       Validator)) {
1427      diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1428      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1429      Id = IDecl->getIdentifier();
1430    }
1431  }
1432  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1433  // This routine must always return a class definition, if any.
1434  if (Def && Def->getDefinition())
1435      Def = Def->getDefinition();
1436  return Def;
1437}
1438
1439/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1440/// from S, where a non-field would be declared. This routine copes
1441/// with the difference between C and C++ scoping rules in structs and
1442/// unions. For example, the following code is well-formed in C but
1443/// ill-formed in C++:
1444/// @code
1445/// struct S6 {
1446///   enum { BAR } e;
1447/// };
1448///
1449/// void test_S6() {
1450///   struct S6 a;
1451///   a.e = BAR;
1452/// }
1453/// @endcode
1454/// For the declaration of BAR, this routine will return a different
1455/// scope. The scope S will be the scope of the unnamed enumeration
1456/// within S6. In C++, this routine will return the scope associated
1457/// with S6, because the enumeration's scope is a transparent
1458/// context but structures can contain non-field names. In C, this
1459/// routine will return the translation unit scope, since the
1460/// enumeration's scope is a transparent context and structures cannot
1461/// contain non-field names.
1462Scope *Sema::getNonFieldDeclScope(Scope *S) {
1463  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1464         (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1465         (S->isClassScope() && !getLangOpts().CPlusPlus))
1466    S = S->getParent();
1467  return S;
1468}
1469
1470/// \brief Looks up the declaration of "struct objc_super" and
1471/// saves it for later use in building builtin declaration of
1472/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1473/// pre-existing declaration exists no action takes place.
1474static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1475                                        IdentifierInfo *II) {
1476  if (!II->isStr("objc_msgSendSuper"))
1477    return;
1478  ASTContext &Context = ThisSema.Context;
1479
1480  LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1481                      SourceLocation(), Sema::LookupTagName);
1482  ThisSema.LookupName(Result, S);
1483  if (Result.getResultKind() == LookupResult::Found)
1484    if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1485      Context.setObjCSuperType(Context.getTagDeclType(TD));
1486}
1487
1488/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1489/// file scope.  lazily create a decl for it. ForRedeclaration is true
1490/// if we're creating this built-in in anticipation of redeclaring the
1491/// built-in.
1492NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
1493                                     Scope *S, bool ForRedeclaration,
1494                                     SourceLocation Loc) {
1495  LookupPredefedObjCSuperType(*this, S, II);
1496
1497  Builtin::ID BID = (Builtin::ID)bid;
1498
1499  ASTContext::GetBuiltinTypeError Error;
1500  QualType R = Context.GetBuiltinType(BID, Error);
1501  switch (Error) {
1502  case ASTContext::GE_None:
1503    // Okay
1504    break;
1505
1506  case ASTContext::GE_Missing_stdio:
1507    if (ForRedeclaration)
1508      Diag(Loc, diag::warn_implicit_decl_requires_stdio)
1509        << Context.BuiltinInfo.GetName(BID);
1510    return 0;
1511
1512  case ASTContext::GE_Missing_setjmp:
1513    if (ForRedeclaration)
1514      Diag(Loc, diag::warn_implicit_decl_requires_setjmp)
1515        << Context.BuiltinInfo.GetName(BID);
1516    return 0;
1517
1518  case ASTContext::GE_Missing_ucontext:
1519    if (ForRedeclaration)
1520      Diag(Loc, diag::warn_implicit_decl_requires_ucontext)
1521        << Context.BuiltinInfo.GetName(BID);
1522    return 0;
1523  }
1524
1525  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
1526    Diag(Loc, diag::ext_implicit_lib_function_decl)
1527      << Context.BuiltinInfo.GetName(BID)
1528      << R;
1529    if (Context.BuiltinInfo.getHeaderName(BID) &&
1530        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc)
1531          != DiagnosticsEngine::Ignored)
1532      Diag(Loc, diag::note_please_include_header)
1533        << Context.BuiltinInfo.getHeaderName(BID)
1534        << Context.BuiltinInfo.GetName(BID);
1535  }
1536
1537  DeclContext *Parent = Context.getTranslationUnitDecl();
1538  if (getLangOpts().CPlusPlus) {
1539    LinkageSpecDecl *CLinkageDecl =
1540        LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1541                                LinkageSpecDecl::lang_c, false);
1542    Parent->addDecl(CLinkageDecl);
1543    Parent = CLinkageDecl;
1544  }
1545
1546  FunctionDecl *New = FunctionDecl::Create(Context,
1547                                           Parent,
1548                                           Loc, Loc, II, R, /*TInfo=*/0,
1549                                           SC_Extern,
1550                                           false,
1551                                           /*hasPrototype=*/true);
1552  New->setImplicit();
1553
1554  // Create Decl objects for each parameter, adding them to the
1555  // FunctionDecl.
1556  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1557    SmallVector<ParmVarDecl*, 16> Params;
1558    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1559      ParmVarDecl *parm =
1560        ParmVarDecl::Create(Context, New, SourceLocation(),
1561                            SourceLocation(), 0,
1562                            FT->getArgType(i), /*TInfo=*/0,
1563                            SC_None, 0);
1564      parm->setScopeInfo(0, i);
1565      Params.push_back(parm);
1566    }
1567    New->setParams(Params);
1568  }
1569
1570  AddKnownFunctionAttributes(New);
1571  RegisterLocallyScopedExternCDecl(New, S);
1572
1573  // TUScope is the translation-unit scope to insert this function into.
1574  // FIXME: This is hideous. We need to teach PushOnScopeChains to
1575  // relate Scopes to DeclContexts, and probably eliminate CurContext
1576  // entirely, but we're not there yet.
1577  DeclContext *SavedContext = CurContext;
1578  CurContext = Parent;
1579  PushOnScopeChains(New, TUScope);
1580  CurContext = SavedContext;
1581  return New;
1582}
1583
1584/// \brief Filter out any previous declarations that the given declaration
1585/// should not consider because they are not permitted to conflict, e.g.,
1586/// because they come from hidden sub-modules and do not refer to the same
1587/// entity.
1588static void filterNonConflictingPreviousDecls(ASTContext &context,
1589                                              NamedDecl *decl,
1590                                              LookupResult &previous){
1591  // This is only interesting when modules are enabled.
1592  if (!context.getLangOpts().Modules)
1593    return;
1594
1595  // Empty sets are uninteresting.
1596  if (previous.empty())
1597    return;
1598
1599  LookupResult::Filter filter = previous.makeFilter();
1600  while (filter.hasNext()) {
1601    NamedDecl *old = filter.next();
1602
1603    // Non-hidden declarations are never ignored.
1604    if (!old->isHidden())
1605      continue;
1606
1607    if (!old->isExternallyVisible())
1608      filter.erase();
1609  }
1610
1611  filter.done();
1612}
1613
1614bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1615  QualType OldType;
1616  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1617    OldType = OldTypedef->getUnderlyingType();
1618  else
1619    OldType = Context.getTypeDeclType(Old);
1620  QualType NewType = New->getUnderlyingType();
1621
1622  if (NewType->isVariablyModifiedType()) {
1623    // Must not redefine a typedef with a variably-modified type.
1624    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1625    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1626      << Kind << NewType;
1627    if (Old->getLocation().isValid())
1628      Diag(Old->getLocation(), diag::note_previous_definition);
1629    New->setInvalidDecl();
1630    return true;
1631  }
1632
1633  if (OldType != NewType &&
1634      !OldType->isDependentType() &&
1635      !NewType->isDependentType() &&
1636      !Context.hasSameType(OldType, NewType)) {
1637    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1638    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1639      << Kind << NewType << OldType;
1640    if (Old->getLocation().isValid())
1641      Diag(Old->getLocation(), diag::note_previous_definition);
1642    New->setInvalidDecl();
1643    return true;
1644  }
1645  return false;
1646}
1647
1648/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1649/// same name and scope as a previous declaration 'Old'.  Figure out
1650/// how to resolve this situation, merging decls or emitting
1651/// diagnostics as appropriate. If there was an error, set New to be invalid.
1652///
1653void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) {
1654  // If the new decl is known invalid already, don't bother doing any
1655  // merging checks.
1656  if (New->isInvalidDecl()) return;
1657
1658  // Allow multiple definitions for ObjC built-in typedefs.
1659  // FIXME: Verify the underlying types are equivalent!
1660  if (getLangOpts().ObjC1) {
1661    const IdentifierInfo *TypeID = New->getIdentifier();
1662    switch (TypeID->getLength()) {
1663    default: break;
1664    case 2:
1665      {
1666        if (!TypeID->isStr("id"))
1667          break;
1668        QualType T = New->getUnderlyingType();
1669        if (!T->isPointerType())
1670          break;
1671        if (!T->isVoidPointerType()) {
1672          QualType PT = T->getAs<PointerType>()->getPointeeType();
1673          if (!PT->isStructureType())
1674            break;
1675        }
1676        Context.setObjCIdRedefinitionType(T);
1677        // Install the built-in type for 'id', ignoring the current definition.
1678        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1679        return;
1680      }
1681    case 5:
1682      if (!TypeID->isStr("Class"))
1683        break;
1684      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1685      // Install the built-in type for 'Class', ignoring the current definition.
1686      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1687      return;
1688    case 3:
1689      if (!TypeID->isStr("SEL"))
1690        break;
1691      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1692      // Install the built-in type for 'SEL', ignoring the current definition.
1693      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1694      return;
1695    }
1696    // Fall through - the typedef name was not a builtin type.
1697  }
1698
1699  // Verify the old decl was also a type.
1700  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1701  if (!Old) {
1702    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1703      << New->getDeclName();
1704
1705    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1706    if (OldD->getLocation().isValid())
1707      Diag(OldD->getLocation(), diag::note_previous_definition);
1708
1709    return New->setInvalidDecl();
1710  }
1711
1712  // If the old declaration is invalid, just give up here.
1713  if (Old->isInvalidDecl())
1714    return New->setInvalidDecl();
1715
1716  // If the typedef types are not identical, reject them in all languages and
1717  // with any extensions enabled.
1718  if (isIncompatibleTypedef(Old, New))
1719    return;
1720
1721  // The types match.  Link up the redeclaration chain and merge attributes if
1722  // the old declaration was a typedef.
1723  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1724    New->setPreviousDecl(Typedef);
1725    mergeDeclAttributes(New, Old);
1726  }
1727
1728  if (getLangOpts().MicrosoftExt)
1729    return;
1730
1731  if (getLangOpts().CPlusPlus) {
1732    // C++ [dcl.typedef]p2:
1733    //   In a given non-class scope, a typedef specifier can be used to
1734    //   redefine the name of any type declared in that scope to refer
1735    //   to the type to which it already refers.
1736    if (!isa<CXXRecordDecl>(CurContext))
1737      return;
1738
1739    // C++0x [dcl.typedef]p4:
1740    //   In a given class scope, a typedef specifier can be used to redefine
1741    //   any class-name declared in that scope that is not also a typedef-name
1742    //   to refer to the type to which it already refers.
1743    //
1744    // This wording came in via DR424, which was a correction to the
1745    // wording in DR56, which accidentally banned code like:
1746    //
1747    //   struct S {
1748    //     typedef struct A { } A;
1749    //   };
1750    //
1751    // in the C++03 standard. We implement the C++0x semantics, which
1752    // allow the above but disallow
1753    //
1754    //   struct S {
1755    //     typedef int I;
1756    //     typedef int I;
1757    //   };
1758    //
1759    // since that was the intent of DR56.
1760    if (!isa<TypedefNameDecl>(Old))
1761      return;
1762
1763    Diag(New->getLocation(), diag::err_redefinition)
1764      << New->getDeclName();
1765    Diag(Old->getLocation(), diag::note_previous_definition);
1766    return New->setInvalidDecl();
1767  }
1768
1769  // Modules always permit redefinition of typedefs, as does C11.
1770  if (getLangOpts().Modules || getLangOpts().C11)
1771    return;
1772
1773  // If we have a redefinition of a typedef in C, emit a warning.  This warning
1774  // is normally mapped to an error, but can be controlled with
1775  // -Wtypedef-redefinition.  If either the original or the redefinition is
1776  // in a system header, don't emit this for compatibility with GCC.
1777  if (getDiagnostics().getSuppressSystemWarnings() &&
1778      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
1779       Context.getSourceManager().isInSystemHeader(New->getLocation())))
1780    return;
1781
1782  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
1783    << New->getDeclName();
1784  Diag(Old->getLocation(), diag::note_previous_definition);
1785  return;
1786}
1787
1788/// DeclhasAttr - returns true if decl Declaration already has the target
1789/// attribute.
1790static bool
1791DeclHasAttr(const Decl *D, const Attr *A) {
1792  // There can be multiple AvailabilityAttr in a Decl. Make sure we copy
1793  // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is
1794  // responsible for making sure they are consistent.
1795  const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A);
1796  if (AA)
1797    return false;
1798
1799  // The following thread safety attributes can also be duplicated.
1800  switch (A->getKind()) {
1801    case attr::ExclusiveLocksRequired:
1802    case attr::SharedLocksRequired:
1803    case attr::LocksExcluded:
1804    case attr::ExclusiveLockFunction:
1805    case attr::SharedLockFunction:
1806    case attr::UnlockFunction:
1807    case attr::ExclusiveTrylockFunction:
1808    case attr::SharedTrylockFunction:
1809    case attr::GuardedBy:
1810    case attr::PtGuardedBy:
1811    case attr::AcquiredBefore:
1812    case attr::AcquiredAfter:
1813      return false;
1814    default:
1815      ;
1816  }
1817
1818  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
1819  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
1820  for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i)
1821    if ((*i)->getKind() == A->getKind()) {
1822      if (Ann) {
1823        if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation())
1824          return true;
1825        continue;
1826      }
1827      // FIXME: Don't hardcode this check
1828      if (OA && isa<OwnershipAttr>(*i))
1829        return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind();
1830      return true;
1831    }
1832
1833  return false;
1834}
1835
1836static bool isAttributeTargetADefinition(Decl *D) {
1837  if (VarDecl *VD = dyn_cast<VarDecl>(D))
1838    return VD->isThisDeclarationADefinition();
1839  if (TagDecl *TD = dyn_cast<TagDecl>(D))
1840    return TD->isCompleteDefinition() || TD->isBeingDefined();
1841  return true;
1842}
1843
1844/// Merge alignment attributes from \p Old to \p New, taking into account the
1845/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
1846///
1847/// \return \c true if any attributes were added to \p New.
1848static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
1849  // Look for alignas attributes on Old, and pick out whichever attribute
1850  // specifies the strictest alignment requirement.
1851  AlignedAttr *OldAlignasAttr = 0;
1852  AlignedAttr *OldStrictestAlignAttr = 0;
1853  unsigned OldAlign = 0;
1854  for (specific_attr_iterator<AlignedAttr>
1855         I = Old->specific_attr_begin<AlignedAttr>(),
1856         E = Old->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1857    // FIXME: We have no way of representing inherited dependent alignments
1858    // in a case like:
1859    //   template<int A, int B> struct alignas(A) X;
1860    //   template<int A, int B> struct alignas(B) X {};
1861    // For now, we just ignore any alignas attributes which are not on the
1862    // definition in such a case.
1863    if (I->isAlignmentDependent())
1864      return false;
1865
1866    if (I->isAlignas())
1867      OldAlignasAttr = *I;
1868
1869    unsigned Align = I->getAlignment(S.Context);
1870    if (Align > OldAlign) {
1871      OldAlign = Align;
1872      OldStrictestAlignAttr = *I;
1873    }
1874  }
1875
1876  // Look for alignas attributes on New.
1877  AlignedAttr *NewAlignasAttr = 0;
1878  unsigned NewAlign = 0;
1879  for (specific_attr_iterator<AlignedAttr>
1880         I = New->specific_attr_begin<AlignedAttr>(),
1881         E = New->specific_attr_end<AlignedAttr>(); I != E; ++I) {
1882    if (I->isAlignmentDependent())
1883      return false;
1884
1885    if (I->isAlignas())
1886      NewAlignasAttr = *I;
1887
1888    unsigned Align = I->getAlignment(S.Context);
1889    if (Align > NewAlign)
1890      NewAlign = Align;
1891  }
1892
1893  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
1894    // Both declarations have 'alignas' attributes. We require them to match.
1895    // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
1896    // fall short. (If two declarations both have alignas, they must both match
1897    // every definition, and so must match each other if there is a definition.)
1898
1899    // If either declaration only contains 'alignas(0)' specifiers, then it
1900    // specifies the natural alignment for the type.
1901    if (OldAlign == 0 || NewAlign == 0) {
1902      QualType Ty;
1903      if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
1904        Ty = VD->getType();
1905      else
1906        Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
1907
1908      if (OldAlign == 0)
1909        OldAlign = S.Context.getTypeAlign(Ty);
1910      if (NewAlign == 0)
1911        NewAlign = S.Context.getTypeAlign(Ty);
1912    }
1913
1914    if (OldAlign != NewAlign) {
1915      S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
1916        << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
1917        << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
1918      S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
1919    }
1920  }
1921
1922  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
1923    // C++11 [dcl.align]p6:
1924    //   if any declaration of an entity has an alignment-specifier,
1925    //   every defining declaration of that entity shall specify an
1926    //   equivalent alignment.
1927    // C11 6.7.5/7:
1928    //   If the definition of an object does not have an alignment
1929    //   specifier, any other declaration of that object shall also
1930    //   have no alignment specifier.
1931    S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
1932      << OldAlignasAttr->isC11();
1933    S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
1934      << OldAlignasAttr->isC11();
1935  }
1936
1937  bool AnyAdded = false;
1938
1939  // Ensure we have an attribute representing the strictest alignment.
1940  if (OldAlign > NewAlign) {
1941    AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
1942    Clone->setInherited(true);
1943    New->addAttr(Clone);
1944    AnyAdded = true;
1945  }
1946
1947  // Ensure we have an alignas attribute if the old declaration had one.
1948  if (OldAlignasAttr && !NewAlignasAttr &&
1949      !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
1950    AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
1951    Clone->setInherited(true);
1952    New->addAttr(Clone);
1953    AnyAdded = true;
1954  }
1955
1956  return AnyAdded;
1957}
1958
1959static bool mergeDeclAttribute(Sema &S, NamedDecl *D, InheritableAttr *Attr,
1960                               bool Override) {
1961  InheritableAttr *NewAttr = NULL;
1962  unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
1963  if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr))
1964    NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
1965                                      AA->getIntroduced(), AA->getDeprecated(),
1966                                      AA->getObsoleted(), AA->getUnavailable(),
1967                                      AA->getMessage(), Override,
1968                                      AttrSpellingListIndex);
1969  else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr))
1970    NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1971                                    AttrSpellingListIndex);
1972  else if (TypeVisibilityAttr *VA = dyn_cast<TypeVisibilityAttr>(Attr))
1973    NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
1974                                        AttrSpellingListIndex);
1975  else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr))
1976    NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
1977                                   AttrSpellingListIndex);
1978  else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr))
1979    NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
1980                                   AttrSpellingListIndex);
1981  else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr))
1982    NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
1983                                FA->getFormatIdx(), FA->getFirstArg(),
1984                                AttrSpellingListIndex);
1985  else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr))
1986    NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
1987                                 AttrSpellingListIndex);
1988  else if (isa<AlignedAttr>(Attr))
1989    // AlignedAttrs are handled separately, because we need to handle all
1990    // such attributes on a declaration at the same time.
1991    NewAttr = 0;
1992  else if (!DeclHasAttr(D, Attr))
1993    NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
1994
1995  if (NewAttr) {
1996    NewAttr->setInherited(true);
1997    D->addAttr(NewAttr);
1998    return true;
1999  }
2000
2001  return false;
2002}
2003
2004static const Decl *getDefinition(const Decl *D) {
2005  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2006    return TD->getDefinition();
2007  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2008    const VarDecl *Def = VD->getDefinition();
2009    if (Def)
2010      return Def;
2011    return VD->getActingDefinition();
2012  }
2013  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2014    const FunctionDecl* Def;
2015    if (FD->isDefined(Def))
2016      return Def;
2017  }
2018  return NULL;
2019}
2020
2021static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2022  for (Decl::attr_iterator I = D->attr_begin(), E = D->attr_end();
2023       I != E; ++I) {
2024    Attr *Attribute = *I;
2025    if (Attribute->getKind() == Kind)
2026      return true;
2027  }
2028  return false;
2029}
2030
2031/// checkNewAttributesAfterDef - If we already have a definition, check that
2032/// there are no new attributes in this declaration.
2033static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2034  if (!New->hasAttrs())
2035    return;
2036
2037  const Decl *Def = getDefinition(Old);
2038  if (!Def || Def == New)
2039    return;
2040
2041  AttrVec &NewAttributes = New->getAttrs();
2042  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2043    const Attr *NewAttribute = NewAttributes[I];
2044
2045    if (isa<AliasAttr>(NewAttribute)) {
2046      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New))
2047        S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def));
2048      else {
2049        VarDecl *VD = cast<VarDecl>(New);
2050        unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2051                                VarDecl::TentativeDefinition
2052                            ? diag::err_alias_after_tentative
2053                            : diag::err_redefinition;
2054        S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2055        S.Diag(Def->getLocation(), diag::note_previous_definition);
2056        VD->setInvalidDecl();
2057      }
2058      ++I;
2059      continue;
2060    }
2061
2062    if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2063      // Tentative definitions are only interesting for the alias check above.
2064      if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2065        ++I;
2066        continue;
2067      }
2068    }
2069
2070    if (hasAttribute(Def, NewAttribute->getKind())) {
2071      ++I;
2072      continue; // regular attr merging will take care of validating this.
2073    }
2074
2075    if (isa<C11NoReturnAttr>(NewAttribute)) {
2076      // C's _Noreturn is allowed to be added to a function after it is defined.
2077      ++I;
2078      continue;
2079    } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2080      if (AA->isAlignas()) {
2081        // C++11 [dcl.align]p6:
2082        //   if any declaration of an entity has an alignment-specifier,
2083        //   every defining declaration of that entity shall specify an
2084        //   equivalent alignment.
2085        // C11 6.7.5/7:
2086        //   If the definition of an object does not have an alignment
2087        //   specifier, any other declaration of that object shall also
2088        //   have no alignment specifier.
2089        S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2090          << AA->isC11();
2091        S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2092          << AA->isC11();
2093        NewAttributes.erase(NewAttributes.begin() + I);
2094        --E;
2095        continue;
2096      }
2097    }
2098
2099    S.Diag(NewAttribute->getLocation(),
2100           diag::warn_attribute_precede_definition);
2101    S.Diag(Def->getLocation(), diag::note_previous_definition);
2102    NewAttributes.erase(NewAttributes.begin() + I);
2103    --E;
2104  }
2105}
2106
2107/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2108void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2109                               AvailabilityMergeKind AMK) {
2110  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2111    UsedAttr *NewAttr = OldAttr->clone(Context);
2112    NewAttr->setInherited(true);
2113    New->addAttr(NewAttr);
2114  }
2115
2116  if (!Old->hasAttrs() && !New->hasAttrs())
2117    return;
2118
2119  // attributes declared post-definition are currently ignored
2120  checkNewAttributesAfterDef(*this, New, Old);
2121
2122  if (!Old->hasAttrs())
2123    return;
2124
2125  bool foundAny = New->hasAttrs();
2126
2127  // Ensure that any moving of objects within the allocated map is done before
2128  // we process them.
2129  if (!foundAny) New->setAttrs(AttrVec());
2130
2131  for (specific_attr_iterator<InheritableAttr>
2132         i = Old->specific_attr_begin<InheritableAttr>(),
2133         e = Old->specific_attr_end<InheritableAttr>();
2134       i != e; ++i) {
2135    bool Override = false;
2136    // Ignore deprecated/unavailable/availability attributes if requested.
2137    if (isa<DeprecatedAttr>(*i) ||
2138        isa<UnavailableAttr>(*i) ||
2139        isa<AvailabilityAttr>(*i)) {
2140      switch (AMK) {
2141      case AMK_None:
2142        continue;
2143
2144      case AMK_Redeclaration:
2145        break;
2146
2147      case AMK_Override:
2148        Override = true;
2149        break;
2150      }
2151    }
2152
2153    // Already handled.
2154    if (isa<UsedAttr>(*i))
2155      continue;
2156
2157    if (mergeDeclAttribute(*this, New, *i, Override))
2158      foundAny = true;
2159  }
2160
2161  if (mergeAlignedAttrs(*this, New, Old))
2162    foundAny = true;
2163
2164  if (!foundAny) New->dropAttrs();
2165}
2166
2167/// mergeParamDeclAttributes - Copy attributes from the old parameter
2168/// to the new one.
2169static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2170                                     const ParmVarDecl *oldDecl,
2171                                     Sema &S) {
2172  // C++11 [dcl.attr.depend]p2:
2173  //   The first declaration of a function shall specify the
2174  //   carries_dependency attribute for its declarator-id if any declaration
2175  //   of the function specifies the carries_dependency attribute.
2176  if (newDecl->hasAttr<CarriesDependencyAttr>() &&
2177      !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2178    S.Diag(newDecl->getAttr<CarriesDependencyAttr>()->getLocation(),
2179           diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2180    // Find the first declaration of the parameter.
2181    // FIXME: Should we build redeclaration chains for function parameters?
2182    const FunctionDecl *FirstFD =
2183      cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2184    const ParmVarDecl *FirstVD =
2185      FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2186    S.Diag(FirstVD->getLocation(),
2187           diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2188  }
2189
2190  if (!oldDecl->hasAttrs())
2191    return;
2192
2193  bool foundAny = newDecl->hasAttrs();
2194
2195  // Ensure that any moving of objects within the allocated map is
2196  // done before we process them.
2197  if (!foundAny) newDecl->setAttrs(AttrVec());
2198
2199  for (specific_attr_iterator<InheritableParamAttr>
2200       i = oldDecl->specific_attr_begin<InheritableParamAttr>(),
2201       e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) {
2202    if (!DeclHasAttr(newDecl, *i)) {
2203      InheritableAttr *newAttr =
2204        cast<InheritableParamAttr>((*i)->clone(S.Context));
2205      newAttr->setInherited(true);
2206      newDecl->addAttr(newAttr);
2207      foundAny = true;
2208    }
2209  }
2210
2211  if (!foundAny) newDecl->dropAttrs();
2212}
2213
2214namespace {
2215
2216/// Used in MergeFunctionDecl to keep track of function parameters in
2217/// C.
2218struct GNUCompatibleParamWarning {
2219  ParmVarDecl *OldParm;
2220  ParmVarDecl *NewParm;
2221  QualType PromotedType;
2222};
2223
2224}
2225
2226/// getSpecialMember - get the special member enum for a method.
2227Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2228  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2229    if (Ctor->isDefaultConstructor())
2230      return Sema::CXXDefaultConstructor;
2231
2232    if (Ctor->isCopyConstructor())
2233      return Sema::CXXCopyConstructor;
2234
2235    if (Ctor->isMoveConstructor())
2236      return Sema::CXXMoveConstructor;
2237  } else if (isa<CXXDestructorDecl>(MD)) {
2238    return Sema::CXXDestructor;
2239  } else if (MD->isCopyAssignmentOperator()) {
2240    return Sema::CXXCopyAssignment;
2241  } else if (MD->isMoveAssignmentOperator()) {
2242    return Sema::CXXMoveAssignment;
2243  }
2244
2245  return Sema::CXXInvalid;
2246}
2247
2248/// canRedefineFunction - checks if a function can be redefined. Currently,
2249/// only extern inline functions can be redefined, and even then only in
2250/// GNU89 mode.
2251static bool canRedefineFunction(const FunctionDecl *FD,
2252                                const LangOptions& LangOpts) {
2253  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2254          !LangOpts.CPlusPlus &&
2255          FD->isInlineSpecified() &&
2256          FD->getStorageClass() == SC_Extern);
2257}
2258
2259const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2260  const AttributedType *AT = T->getAs<AttributedType>();
2261  while (AT && !AT->isCallingConv())
2262    AT = AT->getModifiedType()->getAs<AttributedType>();
2263  return AT;
2264}
2265
2266template <typename T>
2267static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2268  const DeclContext *DC = Old->getDeclContext();
2269  if (DC->isRecord())
2270    return false;
2271
2272  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2273  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2274    return true;
2275  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2276    return true;
2277  return false;
2278}
2279
2280/// MergeFunctionDecl - We just parsed a function 'New' from
2281/// declarator D which has the same name and scope as a previous
2282/// declaration 'Old'.  Figure out how to resolve this situation,
2283/// merging decls or emitting diagnostics as appropriate.
2284///
2285/// In C++, New and Old must be declarations that are not
2286/// overloaded. Use IsOverload to determine whether New and Old are
2287/// overloaded, and to select the Old declaration that New should be
2288/// merged with.
2289///
2290/// Returns true if there was an error, false otherwise.
2291bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S,
2292                             bool MergeTypeWithOld) {
2293  // Verify the old decl was also a function.
2294  FunctionDecl *Old = 0;
2295  if (FunctionTemplateDecl *OldFunctionTemplate
2296        = dyn_cast<FunctionTemplateDecl>(OldD))
2297    Old = OldFunctionTemplate->getTemplatedDecl();
2298  else
2299    Old = dyn_cast<FunctionDecl>(OldD);
2300  if (!Old) {
2301    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2302      if (New->getFriendObjectKind()) {
2303        Diag(New->getLocation(), diag::err_using_decl_friend);
2304        Diag(Shadow->getTargetDecl()->getLocation(),
2305             diag::note_using_decl_target);
2306        Diag(Shadow->getUsingDecl()->getLocation(),
2307             diag::note_using_decl) << 0;
2308        return true;
2309      }
2310
2311      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
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_redefinition_different_kind)
2320      << New->getDeclName();
2321    Diag(OldD->getLocation(), diag::note_previous_definition);
2322    return true;
2323  }
2324
2325  // If the old declaration is invalid, just give up here.
2326  if (Old->isInvalidDecl())
2327    return true;
2328
2329  // Determine whether the previous declaration was a definition,
2330  // implicit declaration, or a declaration.
2331  diag::kind PrevDiag;
2332  if (Old->isThisDeclarationADefinition())
2333    PrevDiag = diag::note_previous_definition;
2334  else if (Old->isImplicit())
2335    PrevDiag = diag::note_previous_implicit_declaration;
2336  else
2337    PrevDiag = diag::note_previous_declaration;
2338
2339  // Don't complain about this if we're in GNU89 mode and the old function
2340  // is an extern inline function.
2341  // Don't complain about specializations. They are not supposed to have
2342  // storage classes.
2343  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2344      New->getStorageClass() == SC_Static &&
2345      Old->hasExternalFormalLinkage() &&
2346      !New->getTemplateSpecializationInfo() &&
2347      !canRedefineFunction(Old, getLangOpts())) {
2348    if (getLangOpts().MicrosoftExt) {
2349      Diag(New->getLocation(), diag::warn_static_non_static) << New;
2350      Diag(Old->getLocation(), PrevDiag);
2351    } else {
2352      Diag(New->getLocation(), diag::err_static_non_static) << New;
2353      Diag(Old->getLocation(), PrevDiag);
2354      return true;
2355    }
2356  }
2357
2358
2359  // If a function is first declared with a calling convention, but is later
2360  // declared or defined without one, all following decls assume the calling
2361  // convention of the first.
2362  //
2363  // It's OK if a function is first declared without a calling convention,
2364  // but is later declared or defined with the default calling convention.
2365  //
2366  // To test if either decl has an explicit calling convention, we look for
2367  // AttributedType sugar nodes on the type as written.  If they are missing or
2368  // were canonicalized away, we assume the calling convention was implicit.
2369  //
2370  // Note also that we DO NOT return at this point, because we still have
2371  // other tests to run.
2372  QualType OldQType = Context.getCanonicalType(Old->getType());
2373  QualType NewQType = Context.getCanonicalType(New->getType());
2374  const FunctionType *OldType = cast<FunctionType>(OldQType);
2375  const FunctionType *NewType = cast<FunctionType>(NewQType);
2376  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2377  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2378  bool RequiresAdjustment = false;
2379
2380  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2381    FunctionDecl *First = Old->getFirstDecl();
2382    const FunctionType *FT =
2383        First->getType().getCanonicalType()->castAs<FunctionType>();
2384    FunctionType::ExtInfo FI = FT->getExtInfo();
2385    bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2386    if (!NewCCExplicit) {
2387      // Inherit the CC from the previous declaration if it was specified
2388      // there but not here.
2389      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2390      RequiresAdjustment = true;
2391    } else {
2392      // Calling conventions aren't compatible, so complain.
2393      bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2394      Diag(New->getLocation(), diag::err_cconv_change)
2395        << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2396        << !FirstCCExplicit
2397        << (!FirstCCExplicit ? "" :
2398            FunctionType::getNameForCallConv(FI.getCC()));
2399
2400      // Put the note on the first decl, since it is the one that matters.
2401      Diag(First->getLocation(), diag::note_previous_declaration);
2402      return true;
2403    }
2404  }
2405
2406  // FIXME: diagnose the other way around?
2407  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2408    NewTypeInfo = NewTypeInfo.withNoReturn(true);
2409    RequiresAdjustment = true;
2410  }
2411
2412  // Merge regparm attribute.
2413  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2414      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2415    if (NewTypeInfo.getHasRegParm()) {
2416      Diag(New->getLocation(), diag::err_regparm_mismatch)
2417        << NewType->getRegParmType()
2418        << OldType->getRegParmType();
2419      Diag(Old->getLocation(), diag::note_previous_declaration);
2420      return true;
2421    }
2422
2423    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2424    RequiresAdjustment = true;
2425  }
2426
2427  // Merge ns_returns_retained attribute.
2428  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2429    if (NewTypeInfo.getProducesResult()) {
2430      Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2431      Diag(Old->getLocation(), diag::note_previous_declaration);
2432      return true;
2433    }
2434
2435    NewTypeInfo = NewTypeInfo.withProducesResult(true);
2436    RequiresAdjustment = true;
2437  }
2438
2439  if (RequiresAdjustment) {
2440    const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2441    AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2442    New->setType(QualType(AdjustedType, 0));
2443    NewQType = Context.getCanonicalType(New->getType());
2444    NewType = cast<FunctionType>(NewQType);
2445  }
2446
2447  // If this redeclaration makes the function inline, we may need to add it to
2448  // UndefinedButUsed.
2449  if (!Old->isInlined() && New->isInlined() &&
2450      !New->hasAttr<GNUInlineAttr>() &&
2451      (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) &&
2452      Old->isUsed(false) &&
2453      !Old->isDefined() && !New->isThisDeclarationADefinition())
2454    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2455                                           SourceLocation()));
2456
2457  // If this redeclaration makes it newly gnu_inline, we don't want to warn
2458  // about it.
2459  if (New->hasAttr<GNUInlineAttr>() &&
2460      Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2461    UndefinedButUsed.erase(Old->getCanonicalDecl());
2462  }
2463
2464  if (getLangOpts().CPlusPlus) {
2465    // (C++98 13.1p2):
2466    //   Certain function declarations cannot be overloaded:
2467    //     -- Function declarations that differ only in the return type
2468    //        cannot be overloaded.
2469
2470    // Go back to the type source info to compare the declared return types,
2471    // per C++1y [dcl.type.auto]p13:
2472    //   Redeclarations or specializations of a function or function template
2473    //   with a declared return type that uses a placeholder type shall also
2474    //   use that placeholder, not a deduced type.
2475    QualType OldDeclaredReturnType = (Old->getTypeSourceInfo()
2476      ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2477      : OldType)->getResultType();
2478    QualType NewDeclaredReturnType = (New->getTypeSourceInfo()
2479      ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2480      : NewType)->getResultType();
2481    QualType ResQT;
2482    if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2483        !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2484          New->isLocalExternDecl())) {
2485      if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2486          OldDeclaredReturnType->isObjCObjectPointerType())
2487        ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2488      if (ResQT.isNull()) {
2489        if (New->isCXXClassMember() && New->isOutOfLine())
2490          Diag(New->getLocation(),
2491               diag::err_member_def_does_not_match_ret_type) << New;
2492        else
2493          Diag(New->getLocation(), diag::err_ovl_diff_return_type);
2494        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2495        return true;
2496      }
2497      else
2498        NewQType = ResQT;
2499    }
2500
2501    QualType OldReturnType = OldType->getResultType();
2502    QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType();
2503    if (OldReturnType != NewReturnType) {
2504      // If this function has a deduced return type and has already been
2505      // defined, copy the deduced value from the old declaration.
2506      AutoType *OldAT = Old->getResultType()->getContainedAutoType();
2507      if (OldAT && OldAT->isDeduced()) {
2508        New->setType(
2509            SubstAutoType(New->getType(),
2510                          OldAT->isDependentType() ? Context.DependentTy
2511                                                   : OldAT->getDeducedType()));
2512        NewQType = Context.getCanonicalType(
2513            SubstAutoType(NewQType,
2514                          OldAT->isDependentType() ? Context.DependentTy
2515                                                   : OldAT->getDeducedType()));
2516      }
2517    }
2518
2519    const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2520    CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2521    if (OldMethod && NewMethod) {
2522      // Preserve triviality.
2523      NewMethod->setTrivial(OldMethod->isTrivial());
2524
2525      // MSVC allows explicit template specialization at class scope:
2526      // 2 CXMethodDecls referring to the same function will be injected.
2527      // We don't want a redeclartion error.
2528      bool IsClassScopeExplicitSpecialization =
2529                              OldMethod->isFunctionTemplateSpecialization() &&
2530                              NewMethod->isFunctionTemplateSpecialization();
2531      bool isFriend = NewMethod->getFriendObjectKind();
2532
2533      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2534          !IsClassScopeExplicitSpecialization) {
2535        //    -- Member function declarations with the same name and the
2536        //       same parameter types cannot be overloaded if any of them
2537        //       is a static member function declaration.
2538        if (OldMethod->isStatic() != NewMethod->isStatic()) {
2539          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2540          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2541          return true;
2542        }
2543
2544        // C++ [class.mem]p1:
2545        //   [...] A member shall not be declared twice in the
2546        //   member-specification, except that a nested class or member
2547        //   class template can be declared and then later defined.
2548        if (ActiveTemplateInstantiations.empty()) {
2549          unsigned NewDiag;
2550          if (isa<CXXConstructorDecl>(OldMethod))
2551            NewDiag = diag::err_constructor_redeclared;
2552          else if (isa<CXXDestructorDecl>(NewMethod))
2553            NewDiag = diag::err_destructor_redeclared;
2554          else if (isa<CXXConversionDecl>(NewMethod))
2555            NewDiag = diag::err_conv_function_redeclared;
2556          else
2557            NewDiag = diag::err_member_redeclared;
2558
2559          Diag(New->getLocation(), NewDiag);
2560        } else {
2561          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2562            << New << New->getType();
2563        }
2564        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2565
2566      // Complain if this is an explicit declaration of a special
2567      // member that was initially declared implicitly.
2568      //
2569      // As an exception, it's okay to befriend such methods in order
2570      // to permit the implicit constructor/destructor/operator calls.
2571      } else if (OldMethod->isImplicit()) {
2572        if (isFriend) {
2573          NewMethod->setImplicit();
2574        } else {
2575          Diag(NewMethod->getLocation(),
2576               diag::err_definition_of_implicitly_declared_member)
2577            << New << getSpecialMember(OldMethod);
2578          return true;
2579        }
2580      } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2581        Diag(NewMethod->getLocation(),
2582             diag::err_definition_of_explicitly_defaulted_member)
2583          << getSpecialMember(OldMethod);
2584        return true;
2585      }
2586    }
2587
2588    // C++11 [dcl.attr.noreturn]p1:
2589    //   The first declaration of a function shall specify the noreturn
2590    //   attribute if any declaration of that function specifies the noreturn
2591    //   attribute.
2592    if (New->hasAttr<CXX11NoReturnAttr>() &&
2593        !Old->hasAttr<CXX11NoReturnAttr>()) {
2594      Diag(New->getAttr<CXX11NoReturnAttr>()->getLocation(),
2595           diag::err_noreturn_missing_on_first_decl);
2596      Diag(Old->getFirstDecl()->getLocation(),
2597           diag::note_noreturn_missing_first_decl);
2598    }
2599
2600    // C++11 [dcl.attr.depend]p2:
2601    //   The first declaration of a function shall specify the
2602    //   carries_dependency attribute for its declarator-id if any declaration
2603    //   of the function specifies the carries_dependency attribute.
2604    if (New->hasAttr<CarriesDependencyAttr>() &&
2605        !Old->hasAttr<CarriesDependencyAttr>()) {
2606      Diag(New->getAttr<CarriesDependencyAttr>()->getLocation(),
2607           diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2608      Diag(Old->getFirstDecl()->getLocation(),
2609           diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2610    }
2611
2612    // (C++98 8.3.5p3):
2613    //   All declarations for a function shall agree exactly in both the
2614    //   return type and the parameter-type-list.
2615    // We also want to respect all the extended bits except noreturn.
2616
2617    // noreturn should now match unless the old type info didn't have it.
2618    QualType OldQTypeForComparison = OldQType;
2619    if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2620      assert(OldQType == QualType(OldType, 0));
2621      const FunctionType *OldTypeForComparison
2622        = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2623      OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2624      assert(OldQTypeForComparison.isCanonical());
2625    }
2626
2627    if (haveIncompatibleLanguageLinkages(Old, New)) {
2628      // As a special case, retain the language linkage from previous
2629      // declarations of a friend function as an extension.
2630      //
2631      // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2632      // and is useful because there's otherwise no way to specify language
2633      // linkage within class scope.
2634      //
2635      // Check cautiously as the friend object kind isn't yet complete.
2636      if (New->getFriendObjectKind() != Decl::FOK_None) {
2637        Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2638        Diag(Old->getLocation(), PrevDiag);
2639      } else {
2640        Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2641        Diag(Old->getLocation(), PrevDiag);
2642        return true;
2643      }
2644    }
2645
2646    if (OldQTypeForComparison == NewQType)
2647      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2648
2649    if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2650        New->isLocalExternDecl()) {
2651      // It's OK if we couldn't merge types for a local function declaraton
2652      // if either the old or new type is dependent. We'll merge the types
2653      // when we instantiate the function.
2654      return false;
2655    }
2656
2657    // Fall through for conflicting redeclarations and redefinitions.
2658  }
2659
2660  // C: Function types need to be compatible, not identical. This handles
2661  // duplicate function decls like "void f(int); void f(enum X);" properly.
2662  if (!getLangOpts().CPlusPlus &&
2663      Context.typesAreCompatible(OldQType, NewQType)) {
2664    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
2665    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
2666    const FunctionProtoType *OldProto = 0;
2667    if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
2668        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
2669      // The old declaration provided a function prototype, but the
2670      // new declaration does not. Merge in the prototype.
2671      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
2672      SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
2673                                                 OldProto->arg_type_end());
2674      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
2675                                         ParamTypes,
2676                                         OldProto->getExtProtoInfo());
2677      New->setType(NewQType);
2678      New->setHasInheritedPrototype();
2679
2680      // Synthesize a parameter for each argument type.
2681      SmallVector<ParmVarDecl*, 16> Params;
2682      for (FunctionProtoType::arg_type_iterator
2683             ParamType = OldProto->arg_type_begin(),
2684             ParamEnd = OldProto->arg_type_end();
2685           ParamType != ParamEnd; ++ParamType) {
2686        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
2687                                                 SourceLocation(),
2688                                                 SourceLocation(), 0,
2689                                                 *ParamType, /*TInfo=*/0,
2690                                                 SC_None,
2691                                                 0);
2692        Param->setScopeInfo(0, Params.size());
2693        Param->setImplicit();
2694        Params.push_back(Param);
2695      }
2696
2697      New->setParams(Params);
2698    }
2699
2700    return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2701  }
2702
2703  // GNU C permits a K&R definition to follow a prototype declaration
2704  // if the declared types of the parameters in the K&R definition
2705  // match the types in the prototype declaration, even when the
2706  // promoted types of the parameters from the K&R definition differ
2707  // from the types in the prototype. GCC then keeps the types from
2708  // the prototype.
2709  //
2710  // If a variadic prototype is followed by a non-variadic K&R definition,
2711  // the K&R definition becomes variadic.  This is sort of an edge case, but
2712  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
2713  // C99 6.9.1p8.
2714  if (!getLangOpts().CPlusPlus &&
2715      Old->hasPrototype() && !New->hasPrototype() &&
2716      New->getType()->getAs<FunctionProtoType>() &&
2717      Old->getNumParams() == New->getNumParams()) {
2718    SmallVector<QualType, 16> ArgTypes;
2719    SmallVector<GNUCompatibleParamWarning, 16> Warnings;
2720    const FunctionProtoType *OldProto
2721      = Old->getType()->getAs<FunctionProtoType>();
2722    const FunctionProtoType *NewProto
2723      = New->getType()->getAs<FunctionProtoType>();
2724
2725    // Determine whether this is the GNU C extension.
2726    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
2727                                               NewProto->getResultType());
2728    bool LooseCompatible = !MergedReturn.isNull();
2729    for (unsigned Idx = 0, End = Old->getNumParams();
2730         LooseCompatible && Idx != End; ++Idx) {
2731      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
2732      ParmVarDecl *NewParm = New->getParamDecl(Idx);
2733      if (Context.typesAreCompatible(OldParm->getType(),
2734                                     NewProto->getArgType(Idx))) {
2735        ArgTypes.push_back(NewParm->getType());
2736      } else if (Context.typesAreCompatible(OldParm->getType(),
2737                                            NewParm->getType(),
2738                                            /*CompareUnqualified=*/true)) {
2739        GNUCompatibleParamWarning Warn
2740          = { OldParm, NewParm, NewProto->getArgType(Idx) };
2741        Warnings.push_back(Warn);
2742        ArgTypes.push_back(NewParm->getType());
2743      } else
2744        LooseCompatible = false;
2745    }
2746
2747    if (LooseCompatible) {
2748      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
2749        Diag(Warnings[Warn].NewParm->getLocation(),
2750             diag::ext_param_promoted_not_compatible_with_prototype)
2751          << Warnings[Warn].PromotedType
2752          << Warnings[Warn].OldParm->getType();
2753        if (Warnings[Warn].OldParm->getLocation().isValid())
2754          Diag(Warnings[Warn].OldParm->getLocation(),
2755               diag::note_previous_declaration);
2756      }
2757
2758      if (MergeTypeWithOld)
2759        New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
2760                                             OldProto->getExtProtoInfo()));
2761      return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2762    }
2763
2764    // Fall through to diagnose conflicting types.
2765  }
2766
2767  // A function that has already been declared has been redeclared or
2768  // defined with a different type; show an appropriate diagnostic.
2769
2770  // If the previous declaration was an implicitly-generated builtin
2771  // declaration, then at the very least we should use a specialized note.
2772  unsigned BuiltinID;
2773  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
2774    // If it's actually a library-defined builtin function like 'malloc'
2775    // or 'printf', just warn about the incompatible redeclaration.
2776    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2777      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
2778      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
2779        << Old << Old->getType();
2780
2781      // If this is a global redeclaration, just forget hereafter
2782      // about the "builtin-ness" of the function.
2783      //
2784      // Doing this for local extern declarations is problematic.  If
2785      // the builtin declaration remains visible, a second invalid
2786      // local declaration will produce a hard error; if it doesn't
2787      // remain visible, a single bogus local redeclaration (which is
2788      // actually only a warning) could break all the downstream code.
2789      if (!New->getLexicalDeclContext()->isFunctionOrMethod())
2790        New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
2791
2792      return false;
2793    }
2794
2795    PrevDiag = diag::note_previous_builtin_declaration;
2796  }
2797
2798  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
2799  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
2800  return true;
2801}
2802
2803/// \brief Completes the merge of two function declarations that are
2804/// known to be compatible.
2805///
2806/// This routine handles the merging of attributes and other
2807/// properties of function declarations from the old declaration to
2808/// the new declaration, once we know that New is in fact a
2809/// redeclaration of Old.
2810///
2811/// \returns false
2812bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
2813                                        Scope *S, bool MergeTypeWithOld) {
2814  // Merge the attributes
2815  mergeDeclAttributes(New, Old);
2816
2817  // Merge "pure" flag.
2818  if (Old->isPure())
2819    New->setPure();
2820
2821  // Merge "used" flag.
2822  if (Old->getMostRecentDecl()->isUsed(false))
2823    New->setIsUsed();
2824
2825  // Merge attributes from the parameters.  These can mismatch with K&R
2826  // declarations.
2827  if (New->getNumParams() == Old->getNumParams())
2828    for (unsigned i = 0, e = New->getNumParams(); i != e; ++i)
2829      mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i),
2830                               *this);
2831
2832  if (getLangOpts().CPlusPlus)
2833    return MergeCXXFunctionDecl(New, Old, S);
2834
2835  // Merge the function types so the we get the composite types for the return
2836  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
2837  // was visible.
2838  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
2839  if (!Merged.isNull() && MergeTypeWithOld)
2840    New->setType(Merged);
2841
2842  return false;
2843}
2844
2845
2846void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
2847                                ObjCMethodDecl *oldMethod) {
2848
2849  // Merge the attributes, including deprecated/unavailable
2850  AvailabilityMergeKind MergeKind =
2851    isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
2852                                                   : AMK_Override;
2853  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
2854
2855  // Merge attributes from the parameters.
2856  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
2857                                       oe = oldMethod->param_end();
2858  for (ObjCMethodDecl::param_iterator
2859         ni = newMethod->param_begin(), ne = newMethod->param_end();
2860       ni != ne && oi != oe; ++ni, ++oi)
2861    mergeParamDeclAttributes(*ni, *oi, *this);
2862
2863  CheckObjCMethodOverride(newMethod, oldMethod);
2864}
2865
2866/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
2867/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
2868/// emitting diagnostics as appropriate.
2869///
2870/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
2871/// to here in AddInitializerToDecl. We can't check them before the initializer
2872/// is attached.
2873void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
2874                             bool MergeTypeWithOld) {
2875  if (New->isInvalidDecl() || Old->isInvalidDecl())
2876    return;
2877
2878  QualType MergedT;
2879  if (getLangOpts().CPlusPlus) {
2880    if (New->getType()->isUndeducedType()) {
2881      // We don't know what the new type is until the initializer is attached.
2882      return;
2883    } else if (Context.hasSameType(New->getType(), Old->getType())) {
2884      // These could still be something that needs exception specs checked.
2885      return MergeVarDeclExceptionSpecs(New, Old);
2886    }
2887    // C++ [basic.link]p10:
2888    //   [...] the types specified by all declarations referring to a given
2889    //   object or function shall be identical, except that declarations for an
2890    //   array object can specify array types that differ by the presence or
2891    //   absence of a major array bound (8.3.4).
2892    else if (Old->getType()->isIncompleteArrayType() &&
2893             New->getType()->isArrayType()) {
2894      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
2895      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
2896      if (Context.hasSameType(OldArray->getElementType(),
2897                              NewArray->getElementType()))
2898        MergedT = New->getType();
2899    } else if (Old->getType()->isArrayType() &&
2900               New->getType()->isIncompleteArrayType()) {
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 = Old->getType();
2906    } else if (New->getType()->isObjCObjectPointerType() &&
2907               Old->getType()->isObjCObjectPointerType()) {
2908      MergedT = Context.mergeObjCGCQualifiers(New->getType(),
2909                                              Old->getType());
2910    }
2911  } else {
2912    // C 6.2.7p2:
2913    //   All declarations that refer to the same object or function shall have
2914    //   compatible type.
2915    MergedT = Context.mergeTypes(New->getType(), Old->getType());
2916  }
2917  if (MergedT.isNull()) {
2918    // It's OK if we couldn't merge types if either type is dependent, for a
2919    // block-scope variable. In other cases (static data members of class
2920    // templates, variable templates, ...), we require the types to be
2921    // equivalent.
2922    // FIXME: The C++ standard doesn't say anything about this.
2923    if ((New->getType()->isDependentType() ||
2924         Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
2925      // If the old type was dependent, we can't merge with it, so the new type
2926      // becomes dependent for now. We'll reproduce the original type when we
2927      // instantiate the TypeSourceInfo for the variable.
2928      if (!New->getType()->isDependentType() && MergeTypeWithOld)
2929        New->setType(Context.DependentTy);
2930      return;
2931    }
2932
2933    // FIXME: Even if this merging succeeds, some other non-visible declaration
2934    // of this variable might have an incompatible type. For instance:
2935    //
2936    //   extern int arr[];
2937    //   void f() { extern int arr[2]; }
2938    //   void g() { extern int arr[3]; }
2939    //
2940    // Neither C nor C++ requires a diagnostic for this, but we should still try
2941    // to diagnose it.
2942    Diag(New->getLocation(), diag::err_redefinition_different_type)
2943      << New->getDeclName() << New->getType() << Old->getType();
2944    Diag(Old->getLocation(), diag::note_previous_definition);
2945    return New->setInvalidDecl();
2946  }
2947
2948  // Don't actually update the type on the new declaration if the old
2949  // declaration was an extern declaration in a different scope.
2950  if (MergeTypeWithOld)
2951    New->setType(MergedT);
2952}
2953
2954static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
2955                                  LookupResult &Previous) {
2956  // C11 6.2.7p4:
2957  //   For an identifier with internal or external linkage declared
2958  //   in a scope in which a prior declaration of that identifier is
2959  //   visible, if the prior declaration specifies internal or
2960  //   external linkage, the type of the identifier at the later
2961  //   declaration becomes the composite type.
2962  //
2963  // If the variable isn't visible, we do not merge with its type.
2964  if (Previous.isShadowed())
2965    return false;
2966
2967  if (S.getLangOpts().CPlusPlus) {
2968    // C++11 [dcl.array]p3:
2969    //   If there is a preceding declaration of the entity in the same
2970    //   scope in which the bound was specified, an omitted array bound
2971    //   is taken to be the same as in that earlier declaration.
2972    return NewVD->isPreviousDeclInSameBlockScope() ||
2973           (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
2974            !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
2975  } else {
2976    // If the old declaration was function-local, don't merge with its
2977    // type unless we're in the same function.
2978    return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
2979           OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
2980  }
2981}
2982
2983/// MergeVarDecl - We just parsed a variable 'New' which has the same name
2984/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
2985/// situation, merging decls or emitting diagnostics as appropriate.
2986///
2987/// Tentative definition rules (C99 6.9.2p2) are checked by
2988/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
2989/// definitions here, since the initializer hasn't been attached.
2990///
2991void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
2992  // If the new decl is already invalid, don't do any other checking.
2993  if (New->isInvalidDecl())
2994    return;
2995
2996  // Verify the old decl was also a variable or variable template.
2997  VarDecl *Old = 0;
2998  if (Previous.isSingleResult() &&
2999      (Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
3000    if (New->getDescribedVarTemplate())
3001      Old = Old->getDescribedVarTemplate() ? Old : 0;
3002    else
3003      Old = Old->getDescribedVarTemplate() ? 0 : Old;
3004  }
3005  if (!Old) {
3006    Diag(New->getLocation(), diag::err_redefinition_different_kind)
3007      << New->getDeclName();
3008    Diag(Previous.getRepresentativeDecl()->getLocation(),
3009         diag::note_previous_definition);
3010    return New->setInvalidDecl();
3011  }
3012
3013  if (!shouldLinkPossiblyHiddenDecl(Old, New))
3014    return;
3015
3016  // C++ [class.mem]p1:
3017  //   A member shall not be declared twice in the member-specification [...]
3018  //
3019  // Here, we need only consider static data members.
3020  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3021    Diag(New->getLocation(), diag::err_duplicate_member)
3022      << New->getIdentifier();
3023    Diag(Old->getLocation(), diag::note_previous_declaration);
3024    New->setInvalidDecl();
3025  }
3026
3027  mergeDeclAttributes(New, Old);
3028  // Warn if an already-declared variable is made a weak_import in a subsequent
3029  // declaration
3030  if (New->getAttr<WeakImportAttr>() &&
3031      Old->getStorageClass() == SC_None &&
3032      !Old->getAttr<WeakImportAttr>()) {
3033    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3034    Diag(Old->getLocation(), diag::note_previous_definition);
3035    // Remove weak_import attribute on new declaration.
3036    New->dropAttr<WeakImportAttr>();
3037  }
3038
3039  // Merge the types.
3040  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3041
3042  if (New->isInvalidDecl())
3043    return;
3044
3045  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3046  if (New->getStorageClass() == SC_Static &&
3047      !New->isStaticDataMember() &&
3048      Old->hasExternalFormalLinkage()) {
3049    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
3050    Diag(Old->getLocation(), diag::note_previous_definition);
3051    return New->setInvalidDecl();
3052  }
3053  // C99 6.2.2p4:
3054  //   For an identifier declared with the storage-class specifier
3055  //   extern in a scope in which a prior declaration of that
3056  //   identifier is visible,23) if the prior declaration specifies
3057  //   internal or external linkage, the linkage of the identifier at
3058  //   the later declaration is the same as the linkage specified at
3059  //   the prior declaration. If no prior declaration is visible, or
3060  //   if the prior declaration specifies no linkage, then the
3061  //   identifier has external linkage.
3062  if (New->hasExternalStorage() && Old->hasLinkage())
3063    /* Okay */;
3064  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3065           !New->isStaticDataMember() &&
3066           Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3067    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3068    Diag(Old->getLocation(), diag::note_previous_definition);
3069    return New->setInvalidDecl();
3070  }
3071
3072  // Check if extern is followed by non-extern and vice-versa.
3073  if (New->hasExternalStorage() &&
3074      !Old->hasLinkage() && Old->isLocalVarDecl()) {
3075    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3076    Diag(Old->getLocation(), diag::note_previous_definition);
3077    return New->setInvalidDecl();
3078  }
3079  if (Old->hasLinkage() && New->isLocalVarDecl() &&
3080      !New->hasExternalStorage()) {
3081    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3082    Diag(Old->getLocation(), diag::note_previous_definition);
3083    return New->setInvalidDecl();
3084  }
3085
3086  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3087
3088  // FIXME: The test for external storage here seems wrong? We still
3089  // need to check for mismatches.
3090  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3091      // Don't complain about out-of-line definitions of static members.
3092      !(Old->getLexicalDeclContext()->isRecord() &&
3093        !New->getLexicalDeclContext()->isRecord())) {
3094    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3095    Diag(Old->getLocation(), diag::note_previous_definition);
3096    return New->setInvalidDecl();
3097  }
3098
3099  if (New->getTLSKind() != Old->getTLSKind()) {
3100    if (!Old->getTLSKind()) {
3101      Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3102      Diag(Old->getLocation(), diag::note_previous_declaration);
3103    } else if (!New->getTLSKind()) {
3104      Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3105      Diag(Old->getLocation(), diag::note_previous_declaration);
3106    } else {
3107      // Do not allow redeclaration to change the variable between requiring
3108      // static and dynamic initialization.
3109      // FIXME: GCC allows this, but uses the TLS keyword on the first
3110      // declaration to determine the kind. Do we need to be compatible here?
3111      Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3112        << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3113      Diag(Old->getLocation(), diag::note_previous_declaration);
3114    }
3115  }
3116
3117  // C++ doesn't have tentative definitions, so go right ahead and check here.
3118  const VarDecl *Def;
3119  if (getLangOpts().CPlusPlus &&
3120      New->isThisDeclarationADefinition() == VarDecl::Definition &&
3121      (Def = Old->getDefinition())) {
3122    Diag(New->getLocation(), diag::err_redefinition) << New;
3123    Diag(Def->getLocation(), diag::note_previous_definition);
3124    New->setInvalidDecl();
3125    return;
3126  }
3127
3128  if (haveIncompatibleLanguageLinkages(Old, New)) {
3129    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3130    Diag(Old->getLocation(), diag::note_previous_definition);
3131    New->setInvalidDecl();
3132    return;
3133  }
3134
3135  // Merge "used" flag.
3136  if (Old->getMostRecentDecl()->isUsed(false))
3137    New->setIsUsed();
3138
3139  // Keep a chain of previous declarations.
3140  New->setPreviousDecl(Old);
3141
3142  // Inherit access appropriately.
3143  New->setAccess(Old->getAccess());
3144
3145  if (VarTemplateDecl *VTD = New->getDescribedVarTemplate()) {
3146    if (New->isStaticDataMember() && New->isOutOfLine())
3147      VTD->setAccess(New->getAccess());
3148  }
3149}
3150
3151/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3152/// no declarator (e.g. "struct foo;") is parsed.
3153Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3154                                       DeclSpec &DS) {
3155  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3156}
3157
3158static void HandleTagNumbering(Sema &S, const TagDecl *Tag) {
3159  if (!S.Context.getLangOpts().CPlusPlus)
3160    return;
3161
3162  if (isa<CXXRecordDecl>(Tag->getParent())) {
3163    // If this tag is the direct child of a class, number it if
3164    // it is anonymous.
3165    if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3166      return;
3167    MangleNumberingContext &MCtx =
3168        S.Context.getManglingNumberContext(Tag->getParent());
3169    S.Context.setManglingNumber(Tag, MCtx.getManglingNumber(Tag));
3170    return;
3171  }
3172
3173  // If this tag isn't a direct child of a class, number it if it is local.
3174  Decl *ManglingContextDecl;
3175  if (MangleNumberingContext *MCtx =
3176          S.getCurrentMangleNumberContext(Tag->getDeclContext(),
3177                                          ManglingContextDecl)) {
3178    S.Context.setManglingNumber(Tag, MCtx->getManglingNumber(Tag));
3179  }
3180}
3181
3182/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3183/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3184/// parameters to cope with template friend declarations.
3185Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3186                                       DeclSpec &DS,
3187                                       MultiTemplateParamsArg TemplateParams,
3188                                       bool IsExplicitInstantiation) {
3189  Decl *TagD = 0;
3190  TagDecl *Tag = 0;
3191  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3192      DS.getTypeSpecType() == DeclSpec::TST_struct ||
3193      DS.getTypeSpecType() == DeclSpec::TST_interface ||
3194      DS.getTypeSpecType() == DeclSpec::TST_union ||
3195      DS.getTypeSpecType() == DeclSpec::TST_enum) {
3196    TagD = DS.getRepAsDecl();
3197
3198    if (!TagD) // We probably had an error
3199      return 0;
3200
3201    // Note that the above type specs guarantee that the
3202    // type rep is a Decl, whereas in many of the others
3203    // it's a Type.
3204    if (isa<TagDecl>(TagD))
3205      Tag = cast<TagDecl>(TagD);
3206    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3207      Tag = CTD->getTemplatedDecl();
3208  }
3209
3210  if (Tag) {
3211    HandleTagNumbering(*this, Tag);
3212    Tag->setFreeStanding();
3213    if (Tag->isInvalidDecl())
3214      return Tag;
3215  }
3216
3217  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3218    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3219    // or incomplete types shall not be restrict-qualified."
3220    if (TypeQuals & DeclSpec::TQ_restrict)
3221      Diag(DS.getRestrictSpecLoc(),
3222           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3223           << DS.getSourceRange();
3224  }
3225
3226  if (DS.isConstexprSpecified()) {
3227    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3228    // and definitions of functions and variables.
3229    if (Tag)
3230      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3231        << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3232            DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3233            DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3234            DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4);
3235    else
3236      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3237    // Don't emit warnings after this error.
3238    return TagD;
3239  }
3240
3241  DiagnoseFunctionSpecifiers(DS);
3242
3243  if (DS.isFriendSpecified()) {
3244    // If we're dealing with a decl but not a TagDecl, assume that
3245    // whatever routines created it handled the friendship aspect.
3246    if (TagD && !Tag)
3247      return 0;
3248    return ActOnFriendTypeDecl(S, DS, TemplateParams);
3249  }
3250
3251  CXXScopeSpec &SS = DS.getTypeSpecScope();
3252  bool IsExplicitSpecialization =
3253    !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3254  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3255      !IsExplicitInstantiation && !IsExplicitSpecialization) {
3256    // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3257    // nested-name-specifier unless it is an explicit instantiation
3258    // or an explicit specialization.
3259    // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3260    Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3261      << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 :
3262          DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 :
3263          DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 :
3264          DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4)
3265      << SS.getRange();
3266    return 0;
3267  }
3268
3269  // Track whether this decl-specifier declares anything.
3270  bool DeclaresAnything = true;
3271
3272  // Handle anonymous struct definitions.
3273  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3274    if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3275        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3276      if (getLangOpts().CPlusPlus ||
3277          Record->getDeclContext()->isRecord())
3278        return BuildAnonymousStructOrUnion(S, DS, AS, Record);
3279
3280      DeclaresAnything = false;
3281    }
3282  }
3283
3284  // Check for Microsoft C extension: anonymous struct member.
3285  if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus &&
3286      CurContext->isRecord() &&
3287      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3288    // Handle 2 kinds of anonymous struct:
3289    //   struct STRUCT;
3290    // and
3291    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3292    RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag);
3293    if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) ||
3294        (DS.getTypeSpecType() == DeclSpec::TST_typename &&
3295         DS.getRepAsType().get()->isStructureType())) {
3296      Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct)
3297        << DS.getSourceRange();
3298      return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3299    }
3300  }
3301
3302  // Skip all the checks below if we have a type error.
3303  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3304      (TagD && TagD->isInvalidDecl()))
3305    return TagD;
3306
3307  if (getLangOpts().CPlusPlus &&
3308      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3309    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3310      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3311          !Enum->getIdentifier() && !Enum->isInvalidDecl())
3312        DeclaresAnything = false;
3313
3314  if (!DS.isMissingDeclaratorOk()) {
3315    // Customize diagnostic for a typedef missing a name.
3316    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3317      Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3318        << DS.getSourceRange();
3319    else
3320      DeclaresAnything = false;
3321  }
3322
3323  if (DS.isModulePrivateSpecified() &&
3324      Tag && Tag->getDeclContext()->isFunctionOrMethod())
3325    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3326      << Tag->getTagKind()
3327      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3328
3329  ActOnDocumentableDecl(TagD);
3330
3331  // C 6.7/2:
3332  //   A declaration [...] shall declare at least a declarator [...], a tag,
3333  //   or the members of an enumeration.
3334  // C++ [dcl.dcl]p3:
3335  //   [If there are no declarators], and except for the declaration of an
3336  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3337  //   names into the program, or shall redeclare a name introduced by a
3338  //   previous declaration.
3339  if (!DeclaresAnything) {
3340    // In C, we allow this as a (popular) extension / bug. Don't bother
3341    // producing further diagnostics for redundant qualifiers after this.
3342    Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3343    return TagD;
3344  }
3345
3346  // C++ [dcl.stc]p1:
3347  //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3348  //   init-declarator-list of the declaration shall not be empty.
3349  // C++ [dcl.fct.spec]p1:
3350  //   If a cv-qualifier appears in a decl-specifier-seq, the
3351  //   init-declarator-list of the declaration shall not be empty.
3352  //
3353  // Spurious qualifiers here appear to be valid in C.
3354  unsigned DiagID = diag::warn_standalone_specifier;
3355  if (getLangOpts().CPlusPlus)
3356    DiagID = diag::ext_standalone_specifier;
3357
3358  // Note that a linkage-specification sets a storage class, but
3359  // 'extern "C" struct foo;' is actually valid and not theoretically
3360  // useless.
3361  if (DeclSpec::SCS SCS = DS.getStorageClassSpec())
3362    if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3363      Diag(DS.getStorageClassSpecLoc(), DiagID)
3364        << DeclSpec::getSpecifierName(SCS);
3365
3366  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3367    Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3368      << DeclSpec::getSpecifierName(TSCS);
3369  if (DS.getTypeQualifiers()) {
3370    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3371      Diag(DS.getConstSpecLoc(), DiagID) << "const";
3372    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3373      Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3374    // Restrict is covered above.
3375    if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3376      Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3377  }
3378
3379  // Warn about ignored type attributes, for example:
3380  // __attribute__((aligned)) struct A;
3381  // Attributes should be placed after tag to apply to type declaration.
3382  if (!DS.getAttributes().empty()) {
3383    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3384    if (TypeSpecType == DeclSpec::TST_class ||
3385        TypeSpecType == DeclSpec::TST_struct ||
3386        TypeSpecType == DeclSpec::TST_interface ||
3387        TypeSpecType == DeclSpec::TST_union ||
3388        TypeSpecType == DeclSpec::TST_enum) {
3389      AttributeList* attrs = DS.getAttributes().getList();
3390      while (attrs) {
3391        Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3392        << attrs->getName()
3393        << (TypeSpecType == DeclSpec::TST_class ? 0 :
3394            TypeSpecType == DeclSpec::TST_struct ? 1 :
3395            TypeSpecType == DeclSpec::TST_union ? 2 :
3396            TypeSpecType == DeclSpec::TST_interface ? 3 : 4);
3397        attrs = attrs->getNext();
3398      }
3399    }
3400  }
3401
3402  return TagD;
3403}
3404
3405/// We are trying to inject an anonymous member into the given scope;
3406/// check if there's an existing declaration that can't be overloaded.
3407///
3408/// \return true if this is a forbidden redeclaration
3409static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3410                                         Scope *S,
3411                                         DeclContext *Owner,
3412                                         DeclarationName Name,
3413                                         SourceLocation NameLoc,
3414                                         unsigned diagnostic) {
3415  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3416                 Sema::ForRedeclaration);
3417  if (!SemaRef.LookupName(R, S)) return false;
3418
3419  if (R.getAsSingle<TagDecl>())
3420    return false;
3421
3422  // Pick a representative declaration.
3423  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3424  assert(PrevDecl && "Expected a non-null Decl");
3425
3426  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3427    return false;
3428
3429  SemaRef.Diag(NameLoc, diagnostic) << Name;
3430  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3431
3432  return true;
3433}
3434
3435/// InjectAnonymousStructOrUnionMembers - Inject the members of the
3436/// anonymous struct or union AnonRecord into the owning context Owner
3437/// and scope S. This routine will be invoked just after we realize
3438/// that an unnamed union or struct is actually an anonymous union or
3439/// struct, e.g.,
3440///
3441/// @code
3442/// union {
3443///   int i;
3444///   float f;
3445/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3446///    // f into the surrounding scope.x
3447/// @endcode
3448///
3449/// This routine is recursive, injecting the names of nested anonymous
3450/// structs/unions into the owning context and scope as well.
3451static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3452                                         DeclContext *Owner,
3453                                         RecordDecl *AnonRecord,
3454                                         AccessSpecifier AS,
3455                                         SmallVectorImpl<NamedDecl *> &Chaining,
3456                                         bool MSAnonStruct) {
3457  unsigned diagKind
3458    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
3459                            : diag::err_anonymous_struct_member_redecl;
3460
3461  bool Invalid = false;
3462
3463  // Look every FieldDecl and IndirectFieldDecl with a name.
3464  for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(),
3465                               DEnd = AnonRecord->decls_end();
3466       D != DEnd; ++D) {
3467    if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) &&
3468        cast<NamedDecl>(*D)->getDeclName()) {
3469      ValueDecl *VD = cast<ValueDecl>(*D);
3470      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3471                                       VD->getLocation(), diagKind)) {
3472        // C++ [class.union]p2:
3473        //   The names of the members of an anonymous union shall be
3474        //   distinct from the names of any other entity in the
3475        //   scope in which the anonymous union is declared.
3476        Invalid = true;
3477      } else {
3478        // C++ [class.union]p2:
3479        //   For the purpose of name lookup, after the anonymous union
3480        //   definition, the members of the anonymous union are
3481        //   considered to have been defined in the scope in which the
3482        //   anonymous union is declared.
3483        unsigned OldChainingSize = Chaining.size();
3484        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3485          for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(),
3486               PE = IF->chain_end(); PI != PE; ++PI)
3487            Chaining.push_back(*PI);
3488        else
3489          Chaining.push_back(VD);
3490
3491        assert(Chaining.size() >= 2);
3492        NamedDecl **NamedChain =
3493          new (SemaRef.Context)NamedDecl*[Chaining.size()];
3494        for (unsigned i = 0; i < Chaining.size(); i++)
3495          NamedChain[i] = Chaining[i];
3496
3497        IndirectFieldDecl* IndirectField =
3498          IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(),
3499                                    VD->getIdentifier(), VD->getType(),
3500                                    NamedChain, Chaining.size());
3501
3502        IndirectField->setAccess(AS);
3503        IndirectField->setImplicit();
3504        SemaRef.PushOnScopeChains(IndirectField, S);
3505
3506        // That includes picking up the appropriate access specifier.
3507        if (AS != AS_none) IndirectField->setAccess(AS);
3508
3509        Chaining.resize(OldChainingSize);
3510      }
3511    }
3512  }
3513
3514  return Invalid;
3515}
3516
3517/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
3518/// a VarDecl::StorageClass. Any error reporting is up to the caller:
3519/// illegal input values are mapped to SC_None.
3520static StorageClass
3521StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
3522  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
3523  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
3524         "Parser allowed 'typedef' as storage class VarDecl.");
3525  switch (StorageClassSpec) {
3526  case DeclSpec::SCS_unspecified:    return SC_None;
3527  case DeclSpec::SCS_extern:
3528    if (DS.isExternInLinkageSpec())
3529      return SC_None;
3530    return SC_Extern;
3531  case DeclSpec::SCS_static:         return SC_Static;
3532  case DeclSpec::SCS_auto:           return SC_Auto;
3533  case DeclSpec::SCS_register:       return SC_Register;
3534  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
3535    // Illegal SCSs map to None: error reporting is up to the caller.
3536  case DeclSpec::SCS_mutable:        // Fall through.
3537  case DeclSpec::SCS_typedef:        return SC_None;
3538  }
3539  llvm_unreachable("unknown storage class specifier");
3540}
3541
3542/// BuildAnonymousStructOrUnion - Handle the declaration of an
3543/// anonymous structure or union. Anonymous unions are a C++ feature
3544/// (C++ [class.union]) and a C11 feature; anonymous structures
3545/// are a C11 feature and GNU C++ extension.
3546Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3547                                             AccessSpecifier AS,
3548                                             RecordDecl *Record) {
3549  DeclContext *Owner = Record->getDeclContext();
3550
3551  // Diagnose whether this anonymous struct/union is an extension.
3552  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
3553    Diag(Record->getLocation(), diag::ext_anonymous_union);
3554  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
3555    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
3556  else if (!Record->isUnion() && !getLangOpts().C11)
3557    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
3558
3559  // C and C++ require different kinds of checks for anonymous
3560  // structs/unions.
3561  bool Invalid = false;
3562  if (getLangOpts().CPlusPlus) {
3563    const char* PrevSpec = 0;
3564    unsigned DiagID;
3565    if (Record->isUnion()) {
3566      // C++ [class.union]p6:
3567      //   Anonymous unions declared in a named namespace or in the
3568      //   global namespace shall be declared static.
3569      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
3570          (isa<TranslationUnitDecl>(Owner) ||
3571           (isa<NamespaceDecl>(Owner) &&
3572            cast<NamespaceDecl>(Owner)->getDeclName()))) {
3573        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
3574          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
3575
3576        // Recover by adding 'static'.
3577        DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
3578                               PrevSpec, DiagID);
3579      }
3580      // C++ [class.union]p6:
3581      //   A storage class is not allowed in a declaration of an
3582      //   anonymous union in a class scope.
3583      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
3584               isa<RecordDecl>(Owner)) {
3585        Diag(DS.getStorageClassSpecLoc(),
3586             diag::err_anonymous_union_with_storage_spec)
3587          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
3588
3589        // Recover by removing the storage specifier.
3590        DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
3591                               SourceLocation(),
3592                               PrevSpec, DiagID);
3593      }
3594    }
3595
3596    // Ignore const/volatile/restrict qualifiers.
3597    if (DS.getTypeQualifiers()) {
3598      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3599        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
3600          << Record->isUnion() << "const"
3601          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
3602      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3603        Diag(DS.getVolatileSpecLoc(),
3604             diag::ext_anonymous_struct_union_qualified)
3605          << Record->isUnion() << "volatile"
3606          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
3607      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
3608        Diag(DS.getRestrictSpecLoc(),
3609             diag::ext_anonymous_struct_union_qualified)
3610          << Record->isUnion() << "restrict"
3611          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
3612      if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3613        Diag(DS.getAtomicSpecLoc(),
3614             diag::ext_anonymous_struct_union_qualified)
3615          << Record->isUnion() << "_Atomic"
3616          << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
3617
3618      DS.ClearTypeQualifiers();
3619    }
3620
3621    // C++ [class.union]p2:
3622    //   The member-specification of an anonymous union shall only
3623    //   define non-static data members. [Note: nested types and
3624    //   functions cannot be declared within an anonymous union. ]
3625    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
3626                                 MemEnd = Record->decls_end();
3627         Mem != MemEnd; ++Mem) {
3628      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
3629        // C++ [class.union]p3:
3630        //   An anonymous union shall not have private or protected
3631        //   members (clause 11).
3632        assert(FD->getAccess() != AS_none);
3633        if (FD->getAccess() != AS_public) {
3634          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
3635            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
3636          Invalid = true;
3637        }
3638
3639        // C++ [class.union]p1
3640        //   An object of a class with a non-trivial constructor, a non-trivial
3641        //   copy constructor, a non-trivial destructor, or a non-trivial copy
3642        //   assignment operator cannot be a member of a union, nor can an
3643        //   array of such objects.
3644        if (CheckNontrivialField(FD))
3645          Invalid = true;
3646      } else if ((*Mem)->isImplicit()) {
3647        // Any implicit members are fine.
3648      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
3649        // This is a type that showed up in an
3650        // elaborated-type-specifier inside the anonymous struct or
3651        // union, but which actually declares a type outside of the
3652        // anonymous struct or union. It's okay.
3653      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
3654        if (!MemRecord->isAnonymousStructOrUnion() &&
3655            MemRecord->getDeclName()) {
3656          // Visual C++ allows type definition in anonymous struct or union.
3657          if (getLangOpts().MicrosoftExt)
3658            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
3659              << (int)Record->isUnion();
3660          else {
3661            // This is a nested type declaration.
3662            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
3663              << (int)Record->isUnion();
3664            Invalid = true;
3665          }
3666        } else {
3667          // This is an anonymous type definition within another anonymous type.
3668          // This is a popular extension, provided by Plan9, MSVC and GCC, but
3669          // not part of standard C++.
3670          Diag(MemRecord->getLocation(),
3671               diag::ext_anonymous_record_with_anonymous_type)
3672            << (int)Record->isUnion();
3673        }
3674      } else if (isa<AccessSpecDecl>(*Mem)) {
3675        // Any access specifier is fine.
3676      } else {
3677        // We have something that isn't a non-static data
3678        // member. Complain about it.
3679        unsigned DK = diag::err_anonymous_record_bad_member;
3680        if (isa<TypeDecl>(*Mem))
3681          DK = diag::err_anonymous_record_with_type;
3682        else if (isa<FunctionDecl>(*Mem))
3683          DK = diag::err_anonymous_record_with_function;
3684        else if (isa<VarDecl>(*Mem))
3685          DK = diag::err_anonymous_record_with_static;
3686
3687        // Visual C++ allows type definition in anonymous struct or union.
3688        if (getLangOpts().MicrosoftExt &&
3689            DK == diag::err_anonymous_record_with_type)
3690          Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type)
3691            << (int)Record->isUnion();
3692        else {
3693          Diag((*Mem)->getLocation(), DK)
3694              << (int)Record->isUnion();
3695          Invalid = true;
3696        }
3697      }
3698    }
3699  }
3700
3701  if (!Record->isUnion() && !Owner->isRecord()) {
3702    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
3703      << (int)getLangOpts().CPlusPlus;
3704    Invalid = true;
3705  }
3706
3707  // Mock up a declarator.
3708  Declarator Dc(DS, Declarator::MemberContext);
3709  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3710  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
3711
3712  // Create a declaration for this anonymous struct/union.
3713  NamedDecl *Anon = 0;
3714  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
3715    Anon = FieldDecl::Create(Context, OwningClass,
3716                             DS.getLocStart(),
3717                             Record->getLocation(),
3718                             /*IdentifierInfo=*/0,
3719                             Context.getTypeDeclType(Record),
3720                             TInfo,
3721                             /*BitWidth=*/0, /*Mutable=*/false,
3722                             /*InitStyle=*/ICIS_NoInit);
3723    Anon->setAccess(AS);
3724    if (getLangOpts().CPlusPlus)
3725      FieldCollector->Add(cast<FieldDecl>(Anon));
3726  } else {
3727    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
3728    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
3729    if (SCSpec == DeclSpec::SCS_mutable) {
3730      // mutable can only appear on non-static class members, so it's always
3731      // an error here
3732      Diag(Record->getLocation(), diag::err_mutable_nonmember);
3733      Invalid = true;
3734      SC = SC_None;
3735    }
3736
3737    Anon = VarDecl::Create(Context, Owner,
3738                           DS.getLocStart(),
3739                           Record->getLocation(), /*IdentifierInfo=*/0,
3740                           Context.getTypeDeclType(Record),
3741                           TInfo, SC);
3742
3743    // Default-initialize the implicit variable. This initialization will be
3744    // trivial in almost all cases, except if a union member has an in-class
3745    // initializer:
3746    //   union { int n = 0; };
3747    ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
3748  }
3749  Anon->setImplicit();
3750
3751  // Add the anonymous struct/union object to the current
3752  // context. We'll be referencing this object when we refer to one of
3753  // its members.
3754  Owner->addDecl(Anon);
3755
3756  // Inject the members of the anonymous struct/union into the owning
3757  // context and into the identifier resolver chain for name lookup
3758  // purposes.
3759  SmallVector<NamedDecl*, 2> Chain;
3760  Chain.push_back(Anon);
3761
3762  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
3763                                          Chain, false))
3764    Invalid = true;
3765
3766  // Mark this as an anonymous struct/union type. Note that we do not
3767  // do this until after we have already checked and injected the
3768  // members of this anonymous struct/union type, because otherwise
3769  // the members could be injected twice: once by DeclContext when it
3770  // builds its lookup table, and once by
3771  // InjectAnonymousStructOrUnionMembers.
3772  Record->setAnonymousStructOrUnion(true);
3773
3774  if (Invalid)
3775    Anon->setInvalidDecl();
3776
3777  return Anon;
3778}
3779
3780/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
3781/// Microsoft C anonymous structure.
3782/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
3783/// Example:
3784///
3785/// struct A { int a; };
3786/// struct B { struct A; int b; };
3787///
3788/// void foo() {
3789///   B var;
3790///   var.a = 3;
3791/// }
3792///
3793Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3794                                           RecordDecl *Record) {
3795
3796  // If there is no Record, get the record via the typedef.
3797  if (!Record)
3798    Record = DS.getRepAsType().get()->getAsStructureType()->getDecl();
3799
3800  // Mock up a declarator.
3801  Declarator Dc(DS, Declarator::TypeNameContext);
3802  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
3803  assert(TInfo && "couldn't build declarator info for anonymous struct");
3804
3805  // Create a declaration for this anonymous struct.
3806  NamedDecl* Anon = FieldDecl::Create(Context,
3807                             cast<RecordDecl>(CurContext),
3808                             DS.getLocStart(),
3809                             DS.getLocStart(),
3810                             /*IdentifierInfo=*/0,
3811                             Context.getTypeDeclType(Record),
3812                             TInfo,
3813                             /*BitWidth=*/0, /*Mutable=*/false,
3814                             /*InitStyle=*/ICIS_NoInit);
3815  Anon->setImplicit();
3816
3817  // Add the anonymous struct object to the current context.
3818  CurContext->addDecl(Anon);
3819
3820  // Inject the members of the anonymous struct into the current
3821  // context and into the identifier resolver chain for name lookup
3822  // purposes.
3823  SmallVector<NamedDecl*, 2> Chain;
3824  Chain.push_back(Anon);
3825
3826  RecordDecl *RecordDef = Record->getDefinition();
3827  if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext,
3828                                                        RecordDef, AS_none,
3829                                                        Chain, true))
3830    Anon->setInvalidDecl();
3831
3832  return Anon;
3833}
3834
3835/// GetNameForDeclarator - Determine the full declaration name for the
3836/// given Declarator.
3837DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
3838  return GetNameFromUnqualifiedId(D.getName());
3839}
3840
3841/// \brief Retrieves the declaration name from a parsed unqualified-id.
3842DeclarationNameInfo
3843Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
3844  DeclarationNameInfo NameInfo;
3845  NameInfo.setLoc(Name.StartLocation);
3846
3847  switch (Name.getKind()) {
3848
3849  case UnqualifiedId::IK_ImplicitSelfParam:
3850  case UnqualifiedId::IK_Identifier:
3851    NameInfo.setName(Name.Identifier);
3852    NameInfo.setLoc(Name.StartLocation);
3853    return NameInfo;
3854
3855  case UnqualifiedId::IK_OperatorFunctionId:
3856    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
3857                                           Name.OperatorFunctionId.Operator));
3858    NameInfo.setLoc(Name.StartLocation);
3859    NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
3860      = Name.OperatorFunctionId.SymbolLocations[0];
3861    NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
3862      = Name.EndLocation.getRawEncoding();
3863    return NameInfo;
3864
3865  case UnqualifiedId::IK_LiteralOperatorId:
3866    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
3867                                                           Name.Identifier));
3868    NameInfo.setLoc(Name.StartLocation);
3869    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
3870    return NameInfo;
3871
3872  case UnqualifiedId::IK_ConversionFunctionId: {
3873    TypeSourceInfo *TInfo;
3874    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
3875    if (Ty.isNull())
3876      return DeclarationNameInfo();
3877    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
3878                                               Context.getCanonicalType(Ty)));
3879    NameInfo.setLoc(Name.StartLocation);
3880    NameInfo.setNamedTypeInfo(TInfo);
3881    return NameInfo;
3882  }
3883
3884  case UnqualifiedId::IK_ConstructorName: {
3885    TypeSourceInfo *TInfo;
3886    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
3887    if (Ty.isNull())
3888      return DeclarationNameInfo();
3889    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3890                                              Context.getCanonicalType(Ty)));
3891    NameInfo.setLoc(Name.StartLocation);
3892    NameInfo.setNamedTypeInfo(TInfo);
3893    return NameInfo;
3894  }
3895
3896  case UnqualifiedId::IK_ConstructorTemplateId: {
3897    // In well-formed code, we can only have a constructor
3898    // template-id that refers to the current context, so go there
3899    // to find the actual type being constructed.
3900    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
3901    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
3902      return DeclarationNameInfo();
3903
3904    // Determine the type of the class being constructed.
3905    QualType CurClassType = Context.getTypeDeclType(CurClass);
3906
3907    // FIXME: Check two things: that the template-id names the same type as
3908    // CurClassType, and that the template-id does not occur when the name
3909    // was qualified.
3910
3911    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
3912                                    Context.getCanonicalType(CurClassType)));
3913    NameInfo.setLoc(Name.StartLocation);
3914    // FIXME: should we retrieve TypeSourceInfo?
3915    NameInfo.setNamedTypeInfo(0);
3916    return NameInfo;
3917  }
3918
3919  case UnqualifiedId::IK_DestructorName: {
3920    TypeSourceInfo *TInfo;
3921    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
3922    if (Ty.isNull())
3923      return DeclarationNameInfo();
3924    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
3925                                              Context.getCanonicalType(Ty)));
3926    NameInfo.setLoc(Name.StartLocation);
3927    NameInfo.setNamedTypeInfo(TInfo);
3928    return NameInfo;
3929  }
3930
3931  case UnqualifiedId::IK_TemplateId: {
3932    TemplateName TName = Name.TemplateId->Template.get();
3933    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
3934    return Context.getNameForTemplate(TName, TNameLoc);
3935  }
3936
3937  } // switch (Name.getKind())
3938
3939  llvm_unreachable("Unknown name kind");
3940}
3941
3942static QualType getCoreType(QualType Ty) {
3943  do {
3944    if (Ty->isPointerType() || Ty->isReferenceType())
3945      Ty = Ty->getPointeeType();
3946    else if (Ty->isArrayType())
3947      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
3948    else
3949      return Ty.withoutLocalFastQualifiers();
3950  } while (true);
3951}
3952
3953/// hasSimilarParameters - Determine whether the C++ functions Declaration
3954/// and Definition have "nearly" matching parameters. This heuristic is
3955/// used to improve diagnostics in the case where an out-of-line function
3956/// definition doesn't match any declaration within the class or namespace.
3957/// Also sets Params to the list of indices to the parameters that differ
3958/// between the declaration and the definition. If hasSimilarParameters
3959/// returns true and Params is empty, then all of the parameters match.
3960static bool hasSimilarParameters(ASTContext &Context,
3961                                     FunctionDecl *Declaration,
3962                                     FunctionDecl *Definition,
3963                                     SmallVectorImpl<unsigned> &Params) {
3964  Params.clear();
3965  if (Declaration->param_size() != Definition->param_size())
3966    return false;
3967  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
3968    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
3969    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
3970
3971    // The parameter types are identical
3972    if (Context.hasSameType(DefParamTy, DeclParamTy))
3973      continue;
3974
3975    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
3976    QualType DefParamBaseTy = getCoreType(DefParamTy);
3977    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
3978    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
3979
3980    if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
3981        (DeclTyName && DeclTyName == DefTyName))
3982      Params.push_back(Idx);
3983    else  // The two parameters aren't even close
3984      return false;
3985  }
3986
3987  return true;
3988}
3989
3990/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
3991/// declarator needs to be rebuilt in the current instantiation.
3992/// Any bits of declarator which appear before the name are valid for
3993/// consideration here.  That's specifically the type in the decl spec
3994/// and the base type in any member-pointer chunks.
3995static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
3996                                                    DeclarationName Name) {
3997  // The types we specifically need to rebuild are:
3998  //   - typenames, typeofs, and decltypes
3999  //   - types which will become injected class names
4000  // Of course, we also need to rebuild any type referencing such a
4001  // type.  It's safest to just say "dependent", but we call out a
4002  // few cases here.
4003
4004  DeclSpec &DS = D.getMutableDeclSpec();
4005  switch (DS.getTypeSpecType()) {
4006  case DeclSpec::TST_typename:
4007  case DeclSpec::TST_typeofType:
4008  case DeclSpec::TST_underlyingType:
4009  case DeclSpec::TST_atomic: {
4010    // Grab the type from the parser.
4011    TypeSourceInfo *TSI = 0;
4012    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4013    if (T.isNull() || !T->isDependentType()) break;
4014
4015    // Make sure there's a type source info.  This isn't really much
4016    // of a waste; most dependent types should have type source info
4017    // attached already.
4018    if (!TSI)
4019      TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4020
4021    // Rebuild the type in the current instantiation.
4022    TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4023    if (!TSI) return true;
4024
4025    // Store the new type back in the decl spec.
4026    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4027    DS.UpdateTypeRep(LocType);
4028    break;
4029  }
4030
4031  case DeclSpec::TST_decltype:
4032  case DeclSpec::TST_typeofExpr: {
4033    Expr *E = DS.getRepAsExpr();
4034    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4035    if (Result.isInvalid()) return true;
4036    DS.UpdateExprRep(Result.get());
4037    break;
4038  }
4039
4040  default:
4041    // Nothing to do for these decl specs.
4042    break;
4043  }
4044
4045  // It doesn't matter what order we do this in.
4046  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4047    DeclaratorChunk &Chunk = D.getTypeObject(I);
4048
4049    // The only type information in the declarator which can come
4050    // before the declaration name is the base type of a member
4051    // pointer.
4052    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4053      continue;
4054
4055    // Rebuild the scope specifier in-place.
4056    CXXScopeSpec &SS = Chunk.Mem.Scope();
4057    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4058      return true;
4059  }
4060
4061  return false;
4062}
4063
4064Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4065  D.setFunctionDefinitionKind(FDK_Declaration);
4066  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4067
4068  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4069      Dcl && Dcl->getDeclContext()->isFileContext())
4070    Dcl->setTopLevelDeclInObjCContainer();
4071
4072  return Dcl;
4073}
4074
4075/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4076///   If T is the name of a class, then each of the following shall have a
4077///   name different from T:
4078///     - every static data member of class T;
4079///     - every member function of class T
4080///     - every member of class T that is itself a type;
4081/// \returns true if the declaration name violates these rules.
4082bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4083                                   DeclarationNameInfo NameInfo) {
4084  DeclarationName Name = NameInfo.getName();
4085
4086  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4087    if (Record->getIdentifier() && Record->getDeclName() == Name) {
4088      Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4089      return true;
4090    }
4091
4092  return false;
4093}
4094
4095/// \brief Diagnose a declaration whose declarator-id has the given
4096/// nested-name-specifier.
4097///
4098/// \param SS The nested-name-specifier of the declarator-id.
4099///
4100/// \param DC The declaration context to which the nested-name-specifier
4101/// resolves.
4102///
4103/// \param Name The name of the entity being declared.
4104///
4105/// \param Loc The location of the name of the entity being declared.
4106///
4107/// \returns true if we cannot safely recover from this error, false otherwise.
4108bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4109                                        DeclarationName Name,
4110                                      SourceLocation Loc) {
4111  DeclContext *Cur = CurContext;
4112  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4113    Cur = Cur->getParent();
4114
4115  // C++ [dcl.meaning]p1:
4116  //   A declarator-id shall not be qualified except for the definition
4117  //   of a member function (9.3) or static data member (9.4) outside of
4118  //   its class, the definition or explicit instantiation of a function
4119  //   or variable member of a namespace outside of its namespace, or the
4120  //   definition of an explicit specialization outside of its namespace,
4121  //   or the declaration of a friend function that is a member of
4122  //   another class or namespace (11.3). [...]
4123
4124  // The user provided a superfluous scope specifier that refers back to the
4125  // class or namespaces in which the entity is already declared.
4126  //
4127  // class X {
4128  //   void X::f();
4129  // };
4130  if (Cur->Equals(DC)) {
4131    Diag(Loc, LangOpts.MicrosoftExt? diag::warn_member_extra_qualification
4132                                   : diag::err_member_extra_qualification)
4133      << Name << FixItHint::CreateRemoval(SS.getRange());
4134    SS.clear();
4135    return false;
4136  }
4137
4138  // Check whether the qualifying scope encloses the scope of the original
4139  // declaration.
4140  if (!Cur->Encloses(DC)) {
4141    if (Cur->isRecord())
4142      Diag(Loc, diag::err_member_qualification)
4143        << Name << SS.getRange();
4144    else if (isa<TranslationUnitDecl>(DC))
4145      Diag(Loc, diag::err_invalid_declarator_global_scope)
4146        << Name << SS.getRange();
4147    else if (isa<FunctionDecl>(Cur))
4148      Diag(Loc, diag::err_invalid_declarator_in_function)
4149        << Name << SS.getRange();
4150    else if (isa<BlockDecl>(Cur))
4151      Diag(Loc, diag::err_invalid_declarator_in_block)
4152        << Name << SS.getRange();
4153    else
4154      Diag(Loc, diag::err_invalid_declarator_scope)
4155      << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4156
4157    return true;
4158  }
4159
4160  if (Cur->isRecord()) {
4161    // Cannot qualify members within a class.
4162    Diag(Loc, diag::err_member_qualification)
4163      << Name << SS.getRange();
4164    SS.clear();
4165
4166    // C++ constructors and destructors with incorrect scopes can break
4167    // our AST invariants by having the wrong underlying types. If
4168    // that's the case, then drop this declaration entirely.
4169    if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4170         Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4171        !Context.hasSameType(Name.getCXXNameType(),
4172                             Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4173      return true;
4174
4175    return false;
4176  }
4177
4178  // C++11 [dcl.meaning]p1:
4179  //   [...] "The nested-name-specifier of the qualified declarator-id shall
4180  //   not begin with a decltype-specifer"
4181  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4182  while (SpecLoc.getPrefix())
4183    SpecLoc = SpecLoc.getPrefix();
4184  if (dyn_cast_or_null<DecltypeType>(
4185        SpecLoc.getNestedNameSpecifier()->getAsType()))
4186    Diag(Loc, diag::err_decltype_in_declarator)
4187      << SpecLoc.getTypeLoc().getSourceRange();
4188
4189  return false;
4190}
4191
4192NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4193                                  MultiTemplateParamsArg TemplateParamLists) {
4194  // TODO: consider using NameInfo for diagnostic.
4195  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4196  DeclarationName Name = NameInfo.getName();
4197
4198  // All of these full declarators require an identifier.  If it doesn't have
4199  // one, the ParsedFreeStandingDeclSpec action should be used.
4200  if (!Name) {
4201    if (!D.isInvalidType())  // Reject this if we think it is valid.
4202      Diag(D.getDeclSpec().getLocStart(),
4203           diag::err_declarator_need_ident)
4204        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4205    return 0;
4206  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4207    return 0;
4208
4209  // The scope passed in may not be a decl scope.  Zip up the scope tree until
4210  // we find one that is.
4211  while ((S->getFlags() & Scope::DeclScope) == 0 ||
4212         (S->getFlags() & Scope::TemplateParamScope) != 0)
4213    S = S->getParent();
4214
4215  DeclContext *DC = CurContext;
4216  if (D.getCXXScopeSpec().isInvalid())
4217    D.setInvalidType();
4218  else if (D.getCXXScopeSpec().isSet()) {
4219    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4220                                        UPPC_DeclarationQualifier))
4221      return 0;
4222
4223    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4224    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4225    if (!DC) {
4226      // If we could not compute the declaration context, it's because the
4227      // declaration context is dependent but does not refer to a class,
4228      // class template, or class template partial specialization. Complain
4229      // and return early, to avoid the coming semantic disaster.
4230      Diag(D.getIdentifierLoc(),
4231           diag::err_template_qualified_declarator_no_match)
4232        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
4233        << D.getCXXScopeSpec().getRange();
4234      return 0;
4235    }
4236    bool IsDependentContext = DC->isDependentContext();
4237
4238    if (!IsDependentContext &&
4239        RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4240      return 0;
4241
4242    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4243      Diag(D.getIdentifierLoc(),
4244           diag::err_member_def_undefined_record)
4245        << Name << DC << D.getCXXScopeSpec().getRange();
4246      D.setInvalidType();
4247    } else if (!D.getDeclSpec().isFriendSpecified()) {
4248      if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4249                                      Name, D.getIdentifierLoc())) {
4250        if (DC->isRecord())
4251          return 0;
4252
4253        D.setInvalidType();
4254      }
4255    }
4256
4257    // Check whether we need to rebuild the type of the given
4258    // declaration in the current instantiation.
4259    if (EnteringContext && IsDependentContext &&
4260        TemplateParamLists.size() != 0) {
4261      ContextRAII SavedContext(*this, DC);
4262      if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4263        D.setInvalidType();
4264    }
4265  }
4266
4267  if (DiagnoseClassNameShadow(DC, NameInfo))
4268    // If this is a typedef, we'll end up spewing multiple diagnostics.
4269    // Just return early; it's safer.
4270    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4271      return 0;
4272
4273  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4274  QualType R = TInfo->getType();
4275
4276  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4277                                      UPPC_DeclarationType))
4278    D.setInvalidType();
4279
4280  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4281                        ForRedeclaration);
4282
4283  // See if this is a redefinition of a variable in the same scope.
4284  if (!D.getCXXScopeSpec().isSet()) {
4285    bool IsLinkageLookup = false;
4286    bool CreateBuiltins = false;
4287
4288    // If the declaration we're planning to build will be a function
4289    // or object with linkage, then look for another declaration with
4290    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4291    //
4292    // If the declaration we're planning to build will be declared with
4293    // external linkage in the translation unit, create any builtin with
4294    // the same name.
4295    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4296      /* Do nothing*/;
4297    else if (CurContext->isFunctionOrMethod() &&
4298             (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4299              R->isFunctionType())) {
4300      IsLinkageLookup = true;
4301      CreateBuiltins =
4302          CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4303    } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4304               D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4305      CreateBuiltins = true;
4306
4307    if (IsLinkageLookup)
4308      Previous.clear(LookupRedeclarationWithLinkage);
4309
4310    LookupName(Previous, S, CreateBuiltins);
4311  } else { // Something like "int foo::x;"
4312    LookupQualifiedName(Previous, DC);
4313
4314    // C++ [dcl.meaning]p1:
4315    //   When the declarator-id is qualified, the declaration shall refer to a
4316    //  previously declared member of the class or namespace to which the
4317    //  qualifier refers (or, in the case of a namespace, of an element of the
4318    //  inline namespace set of that namespace (7.3.1)) or to a specialization
4319    //  thereof; [...]
4320    //
4321    // Note that we already checked the context above, and that we do not have
4322    // enough information to make sure that Previous contains the declaration
4323    // we want to match. For example, given:
4324    //
4325    //   class X {
4326    //     void f();
4327    //     void f(float);
4328    //   };
4329    //
4330    //   void X::f(int) { } // ill-formed
4331    //
4332    // In this case, Previous will point to the overload set
4333    // containing the two f's declared in X, but neither of them
4334    // matches.
4335
4336    // C++ [dcl.meaning]p1:
4337    //   [...] the member shall not merely have been introduced by a
4338    //   using-declaration in the scope of the class or namespace nominated by
4339    //   the nested-name-specifier of the declarator-id.
4340    RemoveUsingDecls(Previous);
4341  }
4342
4343  if (Previous.isSingleResult() &&
4344      Previous.getFoundDecl()->isTemplateParameter()) {
4345    // Maybe we will complain about the shadowed template parameter.
4346    if (!D.isInvalidType())
4347      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4348                                      Previous.getFoundDecl());
4349
4350    // Just pretend that we didn't see the previous declaration.
4351    Previous.clear();
4352  }
4353
4354  // In C++, the previous declaration we find might be a tag type
4355  // (class or enum). In this case, the new declaration will hide the
4356  // tag type. Note that this does does not apply if we're declaring a
4357  // typedef (C++ [dcl.typedef]p4).
4358  if (Previous.isSingleTagDecl() &&
4359      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4360    Previous.clear();
4361
4362  // Check that there are no default arguments other than in the parameters
4363  // of a function declaration (C++ only).
4364  if (getLangOpts().CPlusPlus)
4365    CheckExtraCXXDefaultArguments(D);
4366
4367  NamedDecl *New;
4368
4369  bool AddToScope = true;
4370  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4371    if (TemplateParamLists.size()) {
4372      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4373      return 0;
4374    }
4375
4376    New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4377  } else if (R->isFunctionType()) {
4378    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4379                                  TemplateParamLists,
4380                                  AddToScope);
4381  } else {
4382    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4383                                  AddToScope);
4384  }
4385
4386  if (New == 0)
4387    return 0;
4388
4389  // If this has an identifier and is not an invalid redeclaration or
4390  // function template specialization, add it to the scope stack.
4391  if (New->getDeclName() && AddToScope &&
4392       !(D.isRedeclaration() && New->isInvalidDecl())) {
4393    // Only make a locally-scoped extern declaration visible if it is the first
4394    // declaration of this entity. Qualified lookup for such an entity should
4395    // only find this declaration if there is no visible declaration of it.
4396    bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4397    PushOnScopeChains(New, S, AddToContext);
4398    if (!AddToContext)
4399      CurContext->addHiddenDecl(New);
4400  }
4401
4402  return New;
4403}
4404
4405/// Helper method to turn variable array types into constant array
4406/// types in certain situations which would otherwise be errors (for
4407/// GCC compatibility).
4408static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4409                                                    ASTContext &Context,
4410                                                    bool &SizeIsNegative,
4411                                                    llvm::APSInt &Oversized) {
4412  // This method tries to turn a variable array into a constant
4413  // array even when the size isn't an ICE.  This is necessary
4414  // for compatibility with code that depends on gcc's buggy
4415  // constant expression folding, like struct {char x[(int)(char*)2];}
4416  SizeIsNegative = false;
4417  Oversized = 0;
4418
4419  if (T->isDependentType())
4420    return QualType();
4421
4422  QualifierCollector Qs;
4423  const Type *Ty = Qs.strip(T);
4424
4425  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4426    QualType Pointee = PTy->getPointeeType();
4427    QualType FixedType =
4428        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4429                                            Oversized);
4430    if (FixedType.isNull()) return FixedType;
4431    FixedType = Context.getPointerType(FixedType);
4432    return Qs.apply(Context, FixedType);
4433  }
4434  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
4435    QualType Inner = PTy->getInnerType();
4436    QualType FixedType =
4437        TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
4438                                            Oversized);
4439    if (FixedType.isNull()) return FixedType;
4440    FixedType = Context.getParenType(FixedType);
4441    return Qs.apply(Context, FixedType);
4442  }
4443
4444  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
4445  if (!VLATy)
4446    return QualType();
4447  // FIXME: We should probably handle this case
4448  if (VLATy->getElementType()->isVariablyModifiedType())
4449    return QualType();
4450
4451  llvm::APSInt Res;
4452  if (!VLATy->getSizeExpr() ||
4453      !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
4454    return QualType();
4455
4456  // Check whether the array size is negative.
4457  if (Res.isSigned() && Res.isNegative()) {
4458    SizeIsNegative = true;
4459    return QualType();
4460  }
4461
4462  // Check whether the array is too large to be addressed.
4463  unsigned ActiveSizeBits
4464    = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
4465                                              Res);
4466  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
4467    Oversized = Res;
4468    return QualType();
4469  }
4470
4471  return Context.getConstantArrayType(VLATy->getElementType(),
4472                                      Res, ArrayType::Normal, 0);
4473}
4474
4475static void
4476FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
4477  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
4478    PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
4479    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
4480                                      DstPTL.getPointeeLoc());
4481    DstPTL.setStarLoc(SrcPTL.getStarLoc());
4482    return;
4483  }
4484  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
4485    ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
4486    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
4487                                      DstPTL.getInnerLoc());
4488    DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
4489    DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
4490    return;
4491  }
4492  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
4493  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
4494  TypeLoc SrcElemTL = SrcATL.getElementLoc();
4495  TypeLoc DstElemTL = DstATL.getElementLoc();
4496  DstElemTL.initializeFullCopy(SrcElemTL);
4497  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
4498  DstATL.setSizeExpr(SrcATL.getSizeExpr());
4499  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
4500}
4501
4502/// Helper method to turn variable array types into constant array
4503/// types in certain situations which would otherwise be errors (for
4504/// GCC compatibility).
4505static TypeSourceInfo*
4506TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
4507                                              ASTContext &Context,
4508                                              bool &SizeIsNegative,
4509                                              llvm::APSInt &Oversized) {
4510  QualType FixedTy
4511    = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
4512                                          SizeIsNegative, Oversized);
4513  if (FixedTy.isNull())
4514    return 0;
4515  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
4516  FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
4517                                    FixedTInfo->getTypeLoc());
4518  return FixedTInfo;
4519}
4520
4521/// \brief Register the given locally-scoped extern "C" declaration so
4522/// that it can be found later for redeclarations. We include any extern "C"
4523/// declaration that is not visible in the translation unit here, not just
4524/// function-scope declarations.
4525void
4526Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
4527  if (!getLangOpts().CPlusPlus &&
4528      ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
4529    // Don't need to track declarations in the TU in C.
4530    return;
4531
4532  // Note that we have a locally-scoped external with this name.
4533  // FIXME: There can be multiple such declarations if they are functions marked
4534  // __attribute__((overloadable)) declared in function scope in C.
4535  LocallyScopedExternCDecls[ND->getDeclName()] = ND;
4536}
4537
4538NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
4539  if (ExternalSource) {
4540    // Load locally-scoped external decls from the external source.
4541    // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls?
4542    SmallVector<NamedDecl *, 4> Decls;
4543    ExternalSource->ReadLocallyScopedExternCDecls(Decls);
4544    for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
4545      llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4546        = LocallyScopedExternCDecls.find(Decls[I]->getDeclName());
4547      if (Pos == LocallyScopedExternCDecls.end())
4548        LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I];
4549    }
4550  }
4551
4552  NamedDecl *D = LocallyScopedExternCDecls.lookup(Name);
4553  return D ? D->getMostRecentDecl() : 0;
4554}
4555
4556/// \brief Diagnose function specifiers on a declaration of an identifier that
4557/// does not identify a function.
4558void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
4559  // FIXME: We should probably indicate the identifier in question to avoid
4560  // confusion for constructs like "inline int a(), b;"
4561  if (DS.isInlineSpecified())
4562    Diag(DS.getInlineSpecLoc(),
4563         diag::err_inline_non_function);
4564
4565  if (DS.isVirtualSpecified())
4566    Diag(DS.getVirtualSpecLoc(),
4567         diag::err_virtual_non_function);
4568
4569  if (DS.isExplicitSpecified())
4570    Diag(DS.getExplicitSpecLoc(),
4571         diag::err_explicit_non_function);
4572
4573  if (DS.isNoreturnSpecified())
4574    Diag(DS.getNoreturnSpecLoc(),
4575         diag::err_noreturn_non_function);
4576}
4577
4578NamedDecl*
4579Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
4580                             TypeSourceInfo *TInfo, LookupResult &Previous) {
4581  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
4582  if (D.getCXXScopeSpec().isSet()) {
4583    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
4584      << D.getCXXScopeSpec().getRange();
4585    D.setInvalidType();
4586    // Pretend we didn't see the scope specifier.
4587    DC = CurContext;
4588    Previous.clear();
4589  }
4590
4591  DiagnoseFunctionSpecifiers(D.getDeclSpec());
4592
4593  if (D.getDeclSpec().isConstexprSpecified())
4594    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
4595      << 1;
4596
4597  if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
4598    Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
4599      << D.getName().getSourceRange();
4600    return 0;
4601  }
4602
4603  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
4604  if (!NewTD) return 0;
4605
4606  // Handle attributes prior to checking for duplicates in MergeVarDecl
4607  ProcessDeclAttributes(S, NewTD, D);
4608
4609  CheckTypedefForVariablyModifiedType(S, NewTD);
4610
4611  bool Redeclaration = D.isRedeclaration();
4612  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
4613  D.setRedeclaration(Redeclaration);
4614  return ND;
4615}
4616
4617void
4618Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
4619  // C99 6.7.7p2: If a typedef name specifies a variably modified type
4620  // then it shall have block scope.
4621  // Note that variably modified types must be fixed before merging the decl so
4622  // that redeclarations will match.
4623  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
4624  QualType T = TInfo->getType();
4625  if (T->isVariablyModifiedType()) {
4626    getCurFunction()->setHasBranchProtectedScope();
4627
4628    if (S->getFnParent() == 0) {
4629      bool SizeIsNegative;
4630      llvm::APSInt Oversized;
4631      TypeSourceInfo *FixedTInfo =
4632        TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
4633                                                      SizeIsNegative,
4634                                                      Oversized);
4635      if (FixedTInfo) {
4636        Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
4637        NewTD->setTypeSourceInfo(FixedTInfo);
4638      } else {
4639        if (SizeIsNegative)
4640          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
4641        else if (T->isVariableArrayType())
4642          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
4643        else if (Oversized.getBoolValue())
4644          Diag(NewTD->getLocation(), diag::err_array_too_large)
4645            << Oversized.toString(10);
4646        else
4647          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
4648        NewTD->setInvalidDecl();
4649      }
4650    }
4651  }
4652}
4653
4654
4655/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
4656/// declares a typedef-name, either using the 'typedef' type specifier or via
4657/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
4658NamedDecl*
4659Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
4660                           LookupResult &Previous, bool &Redeclaration) {
4661  // Merge the decl with the existing one if appropriate. If the decl is
4662  // in an outer scope, it isn't the same thing.
4663  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false,
4664                       /*ExplicitInstantiationOrSpecialization=*/false);
4665  filterNonConflictingPreviousDecls(Context, NewTD, Previous);
4666  if (!Previous.empty()) {
4667    Redeclaration = true;
4668    MergeTypedefNameDecl(NewTD, Previous);
4669  }
4670
4671  // If this is the C FILE type, notify the AST context.
4672  if (IdentifierInfo *II = NewTD->getIdentifier())
4673    if (!NewTD->isInvalidDecl() &&
4674        NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
4675      if (II->isStr("FILE"))
4676        Context.setFILEDecl(NewTD);
4677      else if (II->isStr("jmp_buf"))
4678        Context.setjmp_bufDecl(NewTD);
4679      else if (II->isStr("sigjmp_buf"))
4680        Context.setsigjmp_bufDecl(NewTD);
4681      else if (II->isStr("ucontext_t"))
4682        Context.setucontext_tDecl(NewTD);
4683    }
4684
4685  return NewTD;
4686}
4687
4688/// \brief Determines whether the given declaration is an out-of-scope
4689/// previous declaration.
4690///
4691/// This routine should be invoked when name lookup has found a
4692/// previous declaration (PrevDecl) that is not in the scope where a
4693/// new declaration by the same name is being introduced. If the new
4694/// declaration occurs in a local scope, previous declarations with
4695/// linkage may still be considered previous declarations (C99
4696/// 6.2.2p4-5, C++ [basic.link]p6).
4697///
4698/// \param PrevDecl the previous declaration found by name
4699/// lookup
4700///
4701/// \param DC the context in which the new declaration is being
4702/// declared.
4703///
4704/// \returns true if PrevDecl is an out-of-scope previous declaration
4705/// for a new delcaration with the same name.
4706static bool
4707isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
4708                                ASTContext &Context) {
4709  if (!PrevDecl)
4710    return false;
4711
4712  if (!PrevDecl->hasLinkage())
4713    return false;
4714
4715  if (Context.getLangOpts().CPlusPlus) {
4716    // C++ [basic.link]p6:
4717    //   If there is a visible declaration of an entity with linkage
4718    //   having the same name and type, ignoring entities declared
4719    //   outside the innermost enclosing namespace scope, the block
4720    //   scope declaration declares that same entity and receives the
4721    //   linkage of the previous declaration.
4722    DeclContext *OuterContext = DC->getRedeclContext();
4723    if (!OuterContext->isFunctionOrMethod())
4724      // This rule only applies to block-scope declarations.
4725      return false;
4726
4727    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
4728    if (PrevOuterContext->isRecord())
4729      // We found a member function: ignore it.
4730      return false;
4731
4732    // Find the innermost enclosing namespace for the new and
4733    // previous declarations.
4734    OuterContext = OuterContext->getEnclosingNamespaceContext();
4735    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
4736
4737    // The previous declaration is in a different namespace, so it
4738    // isn't the same function.
4739    if (!OuterContext->Equals(PrevOuterContext))
4740      return false;
4741  }
4742
4743  return true;
4744}
4745
4746static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
4747  CXXScopeSpec &SS = D.getCXXScopeSpec();
4748  if (!SS.isSet()) return;
4749  DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
4750}
4751
4752bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
4753  QualType type = decl->getType();
4754  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
4755  if (lifetime == Qualifiers::OCL_Autoreleasing) {
4756    // Various kinds of declaration aren't allowed to be __autoreleasing.
4757    unsigned kind = -1U;
4758    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4759      if (var->hasAttr<BlocksAttr>())
4760        kind = 0; // __block
4761      else if (!var->hasLocalStorage())
4762        kind = 1; // global
4763    } else if (isa<ObjCIvarDecl>(decl)) {
4764      kind = 3; // ivar
4765    } else if (isa<FieldDecl>(decl)) {
4766      kind = 2; // field
4767    }
4768
4769    if (kind != -1U) {
4770      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
4771        << kind;
4772    }
4773  } else if (lifetime == Qualifiers::OCL_None) {
4774    // Try to infer lifetime.
4775    if (!type->isObjCLifetimeType())
4776      return false;
4777
4778    lifetime = type->getObjCARCImplicitLifetime();
4779    type = Context.getLifetimeQualifiedType(type, lifetime);
4780    decl->setType(type);
4781  }
4782
4783  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
4784    // Thread-local variables cannot have lifetime.
4785    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
4786        var->getTLSKind()) {
4787      Diag(var->getLocation(), diag::err_arc_thread_ownership)
4788        << var->getType();
4789      return true;
4790    }
4791  }
4792
4793  return false;
4794}
4795
4796static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
4797  // 'weak' only applies to declarations with external linkage.
4798  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
4799    if (!ND.isExternallyVisible()) {
4800      S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
4801      ND.dropAttr<WeakAttr>();
4802    }
4803  }
4804  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
4805    if (ND.isExternallyVisible()) {
4806      S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
4807      ND.dropAttr<WeakRefAttr>();
4808    }
4809  }
4810
4811  // 'selectany' only applies to externally visible varable declarations.
4812  // It does not apply to functions.
4813  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
4814    if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
4815      S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data);
4816      ND.dropAttr<SelectAnyAttr>();
4817    }
4818  }
4819}
4820
4821/// Given that we are within the definition of the given function,
4822/// will that definition behave like C99's 'inline', where the
4823/// definition is discarded except for optimization purposes?
4824static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
4825  // Try to avoid calling GetGVALinkageForFunction.
4826
4827  // All cases of this require the 'inline' keyword.
4828  if (!FD->isInlined()) return false;
4829
4830  // This is only possible in C++ with the gnu_inline attribute.
4831  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
4832    return false;
4833
4834  // Okay, go ahead and call the relatively-more-expensive function.
4835
4836#ifndef NDEBUG
4837  // AST quite reasonably asserts that it's working on a function
4838  // definition.  We don't really have a way to tell it that we're
4839  // currently defining the function, so just lie to it in +Asserts
4840  // builds.  This is an awful hack.
4841  FD->setLazyBody(1);
4842#endif
4843
4844  bool isC99Inline = (S.Context.GetGVALinkageForFunction(FD) == GVA_C99Inline);
4845
4846#ifndef NDEBUG
4847  FD->setLazyBody(0);
4848#endif
4849
4850  return isC99Inline;
4851}
4852
4853/// Determine whether a variable is extern "C" prior to attaching
4854/// an initializer. We can't just call isExternC() here, because that
4855/// will also compute and cache whether the declaration is externally
4856/// visible, which might change when we attach the initializer.
4857///
4858/// This can only be used if the declaration is known to not be a
4859/// redeclaration of an internal linkage declaration.
4860///
4861/// For instance:
4862///
4863///   auto x = []{};
4864///
4865/// Attaching the initializer here makes this declaration not externally
4866/// visible, because its type has internal linkage.
4867///
4868/// FIXME: This is a hack.
4869template<typename T>
4870static bool isIncompleteDeclExternC(Sema &S, const T *D) {
4871  if (S.getLangOpts().CPlusPlus) {
4872    // In C++, the overloadable attribute negates the effects of extern "C".
4873    if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
4874      return false;
4875  }
4876  return D->isExternC();
4877}
4878
4879static bool shouldConsiderLinkage(const VarDecl *VD) {
4880  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
4881  if (DC->isFunctionOrMethod())
4882    return VD->hasExternalStorage();
4883  if (DC->isFileContext())
4884    return true;
4885  if (DC->isRecord())
4886    return false;
4887  llvm_unreachable("Unexpected context");
4888}
4889
4890static bool shouldConsiderLinkage(const FunctionDecl *FD) {
4891  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
4892  if (DC->isFileContext() || DC->isFunctionOrMethod())
4893    return true;
4894  if (DC->isRecord())
4895    return false;
4896  llvm_unreachable("Unexpected context");
4897}
4898
4899/// Adjust the \c DeclContext for a function or variable that might be a
4900/// function-local external declaration.
4901bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
4902  if (!DC->isFunctionOrMethod())
4903    return false;
4904
4905  // If this is a local extern function or variable declared within a function
4906  // template, don't add it into the enclosing namespace scope until it is
4907  // instantiated; it might have a dependent type right now.
4908  if (DC->isDependentContext())
4909    return true;
4910
4911  // C++11 [basic.link]p7:
4912  //   When a block scope declaration of an entity with linkage is not found to
4913  //   refer to some other declaration, then that entity is a member of the
4914  //   innermost enclosing namespace.
4915  //
4916  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
4917  // semantically-enclosing namespace, not a lexically-enclosing one.
4918  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
4919    DC = DC->getParent();
4920  return true;
4921}
4922
4923NamedDecl *
4924Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
4925                              TypeSourceInfo *TInfo, LookupResult &Previous,
4926                              MultiTemplateParamsArg TemplateParamLists,
4927                              bool &AddToScope) {
4928  QualType R = TInfo->getType();
4929  DeclarationName Name = GetNameForDeclarator(D).getName();
4930
4931  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
4932  VarDecl::StorageClass SC =
4933    StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
4934
4935  DeclContext *OriginalDC = DC;
4936  bool IsLocalExternDecl = SC == SC_Extern &&
4937                           adjustContextForLocalExternDecl(DC);
4938
4939  if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16) {
4940    // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
4941    // half array type (unless the cl_khr_fp16 extension is enabled).
4942    if (Context.getBaseElementType(R)->isHalfType()) {
4943      Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
4944      D.setInvalidType();
4945    }
4946  }
4947
4948  if (SCSpec == DeclSpec::SCS_mutable) {
4949    // mutable can only appear on non-static class members, so it's always
4950    // an error here
4951    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
4952    D.setInvalidType();
4953    SC = SC_None;
4954  }
4955
4956  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
4957      !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
4958                              D.getDeclSpec().getStorageClassSpecLoc())) {
4959    // In C++11, the 'register' storage class specifier is deprecated.
4960    // Suppress the warning in system macros, it's used in macros in some
4961    // popular C system headers, such as in glibc's htonl() macro.
4962    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
4963         diag::warn_deprecated_register)
4964      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4965  }
4966
4967  IdentifierInfo *II = Name.getAsIdentifierInfo();
4968  if (!II) {
4969    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
4970      << Name;
4971    return 0;
4972  }
4973
4974  DiagnoseFunctionSpecifiers(D.getDeclSpec());
4975
4976  if (!DC->isRecord() && S->getFnParent() == 0) {
4977    // C99 6.9p2: The storage-class specifiers auto and register shall not
4978    // appear in the declaration specifiers in an external declaration.
4979    if (SC == SC_Auto || SC == SC_Register) {
4980      // If this is a register variable with an asm label specified, then this
4981      // is a GNU extension.
4982      if (SC == SC_Register && D.getAsmLabel())
4983        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
4984      else
4985        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
4986      D.setInvalidType();
4987    }
4988  }
4989
4990  if (getLangOpts().OpenCL) {
4991    // Set up the special work-group-local storage class for variables in the
4992    // OpenCL __local address space.
4993    if (R.getAddressSpace() == LangAS::opencl_local) {
4994      SC = SC_OpenCLWorkGroupLocal;
4995    }
4996
4997    // OpenCL v1.2 s6.9.b p4:
4998    // The sampler type cannot be used with the __local and __global address
4999    // space qualifiers.
5000    if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5001      R.getAddressSpace() == LangAS::opencl_global)) {
5002      Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5003    }
5004
5005    // OpenCL 1.2 spec, p6.9 r:
5006    // The event type cannot be used to declare a program scope variable.
5007    // The event type cannot be used with the __local, __constant and __global
5008    // address space qualifiers.
5009    if (R->isEventT()) {
5010      if (S->getParent() == 0) {
5011        Diag(D.getLocStart(), diag::err_event_t_global_var);
5012        D.setInvalidType();
5013      }
5014
5015      if (R.getAddressSpace()) {
5016        Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5017        D.setInvalidType();
5018      }
5019    }
5020  }
5021
5022  bool IsExplicitSpecialization = false;
5023  bool IsVariableTemplateSpecialization = false;
5024  bool IsPartialSpecialization = false;
5025  bool IsVariableTemplate = false;
5026  VarTemplateDecl *PrevVarTemplate = 0;
5027  VarDecl *NewVD = 0;
5028  VarTemplateDecl *NewTemplate = 0;
5029  if (!getLangOpts().CPlusPlus) {
5030    NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5031                            D.getIdentifierLoc(), II,
5032                            R, TInfo, SC);
5033
5034    if (D.isInvalidType())
5035      NewVD->setInvalidDecl();
5036  } else {
5037    bool Invalid = false;
5038
5039    if (DC->isRecord() && !CurContext->isRecord()) {
5040      // This is an out-of-line definition of a static data member.
5041      switch (SC) {
5042      case SC_None:
5043        break;
5044      case SC_Static:
5045        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5046             diag::err_static_out_of_line)
5047          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5048        break;
5049      case SC_Auto:
5050      case SC_Register:
5051      case SC_Extern:
5052        // [dcl.stc] p2: The auto or register specifiers shall be applied only
5053        // to names of variables declared in a block or to function parameters.
5054        // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5055        // of class members
5056
5057        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5058             diag::err_storage_class_for_static_member)
5059          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5060        break;
5061      case SC_PrivateExtern:
5062        llvm_unreachable("C storage class in c++!");
5063      case SC_OpenCLWorkGroupLocal:
5064        llvm_unreachable("OpenCL storage class in c++!");
5065      }
5066    }
5067
5068    if (SC == SC_Static && CurContext->isRecord()) {
5069      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5070        if (RD->isLocalClass())
5071          Diag(D.getIdentifierLoc(),
5072               diag::err_static_data_member_not_allowed_in_local_class)
5073            << Name << RD->getDeclName();
5074
5075        // C++98 [class.union]p1: If a union contains a static data member,
5076        // the program is ill-formed. C++11 drops this restriction.
5077        if (RD->isUnion())
5078          Diag(D.getIdentifierLoc(),
5079               getLangOpts().CPlusPlus11
5080                 ? diag::warn_cxx98_compat_static_data_member_in_union
5081                 : diag::ext_static_data_member_in_union) << Name;
5082        // We conservatively disallow static data members in anonymous structs.
5083        else if (!RD->getDeclName())
5084          Diag(D.getIdentifierLoc(),
5085               diag::err_static_data_member_not_allowed_in_anon_struct)
5086            << Name << RD->isUnion();
5087      }
5088    }
5089
5090    NamedDecl *PrevDecl = 0;
5091    if (Previous.begin() != Previous.end())
5092      PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5093    PrevVarTemplate = dyn_cast_or_null<VarTemplateDecl>(PrevDecl);
5094
5095    // Match up the template parameter lists with the scope specifier, then
5096    // determine whether we have a template or a template specialization.
5097    TemplateParameterList *TemplateParams =
5098        MatchTemplateParametersToScopeSpecifier(
5099            D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5100            D.getCXXScopeSpec(), TemplateParamLists,
5101            /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5102    if (TemplateParams) {
5103      if (!TemplateParams->size() &&
5104          D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5105        // There is an extraneous 'template<>' for this variable. Complain
5106        // about it, but allow the declaration of the variable.
5107        Diag(TemplateParams->getTemplateLoc(),
5108             diag::err_template_variable_noparams)
5109          << II
5110          << SourceRange(TemplateParams->getTemplateLoc(),
5111                         TemplateParams->getRAngleLoc());
5112      } else {
5113        // Only C++1y supports variable templates (N3651).
5114        Diag(D.getIdentifierLoc(),
5115             getLangOpts().CPlusPlus1y
5116                 ? diag::warn_cxx11_compat_variable_template
5117                 : diag::ext_variable_template);
5118
5119        if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5120          // This is an explicit specialization or a partial specialization.
5121          // Check that we can declare a specialization here
5122
5123          IsVariableTemplateSpecialization = true;
5124          IsPartialSpecialization = TemplateParams->size() > 0;
5125
5126        } else { // if (TemplateParams->size() > 0)
5127          // This is a template declaration.
5128          IsVariableTemplate = true;
5129
5130          // Check that we can declare a template here.
5131          if (CheckTemplateDeclScope(S, TemplateParams))
5132            return 0;
5133
5134          // If there is a previous declaration with the same name, check
5135          // whether this is a valid redeclaration.
5136          if (PrevDecl && !isDeclInScope(PrevDecl, DC, S))
5137            PrevDecl = PrevVarTemplate = 0;
5138
5139          if (PrevVarTemplate) {
5140            // Ensure that the template parameter lists are compatible.
5141            if (!TemplateParameterListsAreEqual(
5142                    TemplateParams, PrevVarTemplate->getTemplateParameters(),
5143                    /*Complain=*/true, TPL_TemplateMatch))
5144              return 0;
5145          } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
5146            // Maybe we will complain about the shadowed template parameter.
5147            DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5148
5149            // Just pretend that we didn't see the previous declaration.
5150            PrevDecl = 0;
5151          } else if (PrevDecl) {
5152            // C++ [temp]p5:
5153            // ... a template name declared in namespace scope or in class
5154            // scope shall be unique in that scope.
5155            Diag(D.getIdentifierLoc(), diag::err_redefinition_different_kind)
5156                << Name;
5157            Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5158            return 0;
5159          }
5160
5161          // Check the template parameter list of this declaration, possibly
5162          // merging in the template parameter list from the previous variable
5163          // template declaration.
5164          if (CheckTemplateParameterList(
5165                  TemplateParams,
5166                  PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
5167                                  : 0,
5168                  (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
5169                   DC->isDependentContext())
5170                      ? TPC_ClassTemplateMember
5171                      : TPC_VarTemplate))
5172            Invalid = true;
5173
5174          if (D.getCXXScopeSpec().isSet()) {
5175            // If the name of the template was qualified, we must be defining
5176            // the template out-of-line.
5177            if (!D.getCXXScopeSpec().isInvalid() && !Invalid &&
5178                !PrevVarTemplate) {
5179              Diag(D.getIdentifierLoc(), diag::err_member_decl_does_not_match)
5180                  << Name << DC << /*IsDefinition*/true
5181                  << D.getCXXScopeSpec().getRange();
5182              Invalid = true;
5183            }
5184          }
5185        }
5186      }
5187    } else if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5188      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5189
5190      // We have encountered something that the user meant to be a
5191      // specialization (because it has explicitly-specified template
5192      // arguments) but that was not introduced with a "template<>" (or had
5193      // too few of them).
5194      // FIXME: Differentiate between attempts for explicit instantiations
5195      // (starting with "template") and the rest.
5196      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
5197          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
5198          << FixItHint::CreateInsertion(D.getDeclSpec().getLocStart(),
5199                                        "template<> ");
5200      IsVariableTemplateSpecialization = true;
5201    }
5202
5203    if (IsVariableTemplateSpecialization) {
5204      if (!PrevVarTemplate) {
5205        Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5206            << IsPartialSpecialization;
5207        return 0;
5208      }
5209
5210      SourceLocation TemplateKWLoc =
5211          TemplateParamLists.size() > 0
5212              ? TemplateParamLists[0]->getTemplateLoc()
5213              : SourceLocation();
5214      DeclResult Res = ActOnVarTemplateSpecialization(
5215          S, PrevVarTemplate, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5216          IsPartialSpecialization);
5217      if (Res.isInvalid())
5218        return 0;
5219      NewVD = cast<VarDecl>(Res.get());
5220      AddToScope = false;
5221    } else
5222      NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5223                              D.getIdentifierLoc(), II, R, TInfo, SC);
5224
5225    // If this is supposed to be a variable template, create it as such.
5226    if (IsVariableTemplate) {
5227      NewTemplate =
5228          VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5229                                  TemplateParams, NewVD, PrevVarTemplate);
5230      NewVD->setDescribedVarTemplate(NewTemplate);
5231    }
5232
5233    // If this decl has an auto type in need of deduction, make a note of the
5234    // Decl so we can diagnose uses of it in its own initializer.
5235    if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5236      ParsingInitForAutoVars.insert(NewVD);
5237
5238    if (D.isInvalidType() || Invalid) {
5239      NewVD->setInvalidDecl();
5240      if (NewTemplate)
5241        NewTemplate->setInvalidDecl();
5242    }
5243
5244    SetNestedNameSpecifier(NewVD, D);
5245
5246    // FIXME: Do we need D.getCXXScopeSpec().isSet()?
5247    if (TemplateParams && TemplateParamLists.size() > 1 &&
5248        (!IsVariableTemplateSpecialization || D.getCXXScopeSpec().isSet())) {
5249      NewVD->setTemplateParameterListsInfo(
5250          Context, TemplateParamLists.size() - 1, TemplateParamLists.data());
5251    } else if (IsVariableTemplateSpecialization ||
5252               (!TemplateParams && TemplateParamLists.size() > 0 &&
5253                (D.getCXXScopeSpec().isSet()))) {
5254      NewVD->setTemplateParameterListsInfo(Context,
5255                                           TemplateParamLists.size(),
5256                                           TemplateParamLists.data());
5257    }
5258
5259    if (D.getDeclSpec().isConstexprSpecified())
5260      NewVD->setConstexpr(true);
5261  }
5262
5263  // Set the lexical context. If the declarator has a C++ scope specifier, the
5264  // lexical context will be different from the semantic context.
5265  NewVD->setLexicalDeclContext(CurContext);
5266  if (NewTemplate)
5267    NewTemplate->setLexicalDeclContext(CurContext);
5268
5269  if (IsLocalExternDecl)
5270    NewVD->setLocalExternDecl();
5271
5272  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5273    if (NewVD->hasLocalStorage()) {
5274      // C++11 [dcl.stc]p4:
5275      //   When thread_local is applied to a variable of block scope the
5276      //   storage-class-specifier static is implied if it does not appear
5277      //   explicitly.
5278      // Core issue: 'static' is not implied if the variable is declared
5279      //   'extern'.
5280      if (SCSpec == DeclSpec::SCS_unspecified &&
5281          TSCS == DeclSpec::TSCS_thread_local &&
5282          DC->isFunctionOrMethod())
5283        NewVD->setTSCSpec(TSCS);
5284      else
5285        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5286             diag::err_thread_non_global)
5287          << DeclSpec::getSpecifierName(TSCS);
5288    } else if (!Context.getTargetInfo().isTLSSupported())
5289      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5290           diag::err_thread_unsupported);
5291    else
5292      NewVD->setTSCSpec(TSCS);
5293  }
5294
5295  // C99 6.7.4p3
5296  //   An inline definition of a function with external linkage shall
5297  //   not contain a definition of a modifiable object with static or
5298  //   thread storage duration...
5299  // We only apply this when the function is required to be defined
5300  // elsewhere, i.e. when the function is not 'extern inline'.  Note
5301  // that a local variable with thread storage duration still has to
5302  // be marked 'static'.  Also note that it's possible to get these
5303  // semantics in C++ using __attribute__((gnu_inline)).
5304  if (SC == SC_Static && S->getFnParent() != 0 &&
5305      !NewVD->getType().isConstQualified()) {
5306    FunctionDecl *CurFD = getCurFunctionDecl();
5307    if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
5308      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5309           diag::warn_static_local_in_extern_inline);
5310      MaybeSuggestAddingStaticToDecl(CurFD);
5311    }
5312  }
5313
5314  if (D.getDeclSpec().isModulePrivateSpecified()) {
5315    if (IsVariableTemplateSpecialization)
5316      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5317          << (IsPartialSpecialization ? 1 : 0)
5318          << FixItHint::CreateRemoval(
5319                 D.getDeclSpec().getModulePrivateSpecLoc());
5320    else if (IsExplicitSpecialization)
5321      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
5322        << 2
5323        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5324    else if (NewVD->hasLocalStorage())
5325      Diag(NewVD->getLocation(), diag::err_module_private_local)
5326        << 0 << NewVD->getDeclName()
5327        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
5328        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
5329    else {
5330      NewVD->setModulePrivate();
5331      if (NewTemplate)
5332        NewTemplate->setModulePrivate();
5333    }
5334  }
5335
5336  // Handle attributes prior to checking for duplicates in MergeVarDecl
5337  ProcessDeclAttributes(S, NewVD, D);
5338
5339  if (NewVD->hasAttrs())
5340    CheckAlignasUnderalignment(NewVD);
5341
5342  if (getLangOpts().CUDA) {
5343    // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
5344    // storage [duration]."
5345    if (SC == SC_None && S->getFnParent() != 0 &&
5346        (NewVD->hasAttr<CUDASharedAttr>() ||
5347         NewVD->hasAttr<CUDAConstantAttr>())) {
5348      NewVD->setStorageClass(SC_Static);
5349    }
5350  }
5351
5352  // In auto-retain/release, infer strong retension for variables of
5353  // retainable type.
5354  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
5355    NewVD->setInvalidDecl();
5356
5357  // Handle GNU asm-label extension (encoded as an attribute).
5358  if (Expr *E = (Expr*)D.getAsmLabel()) {
5359    // The parser guarantees this is a string.
5360    StringLiteral *SE = cast<StringLiteral>(E);
5361    StringRef Label = SE->getString();
5362    if (S->getFnParent() != 0) {
5363      switch (SC) {
5364      case SC_None:
5365      case SC_Auto:
5366        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
5367        break;
5368      case SC_Register:
5369        if (!Context.getTargetInfo().isValidGCCRegisterName(Label))
5370          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
5371        break;
5372      case SC_Static:
5373      case SC_Extern:
5374      case SC_PrivateExtern:
5375      case SC_OpenCLWorkGroupLocal:
5376        break;
5377      }
5378    }
5379
5380    NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
5381                                                Context, Label));
5382  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
5383    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
5384      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
5385    if (I != ExtnameUndeclaredIdentifiers.end()) {
5386      NewVD->addAttr(I->second);
5387      ExtnameUndeclaredIdentifiers.erase(I);
5388    }
5389  }
5390
5391  // Diagnose shadowed variables before filtering for scope.
5392  if (!D.getCXXScopeSpec().isSet())
5393    CheckShadow(S, NewVD, Previous);
5394
5395  // Don't consider existing declarations that are in a different
5396  // scope and are out-of-semantic-context declarations (if the new
5397  // declaration has linkage).
5398  FilterLookupForScope(
5399      Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
5400      IsExplicitSpecialization || IsVariableTemplateSpecialization);
5401
5402  // Check whether the previous declaration is in the same block scope. This
5403  // affects whether we merge types with it, per C++11 [dcl.array]p3.
5404  if (getLangOpts().CPlusPlus &&
5405      NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
5406    NewVD->setPreviousDeclInSameBlockScope(
5407        Previous.isSingleResult() && !Previous.isShadowed() &&
5408        isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
5409
5410  if (!getLangOpts().CPlusPlus) {
5411    D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5412  } else {
5413    // Merge the decl with the existing one if appropriate.
5414    if (!Previous.empty()) {
5415      if (Previous.isSingleResult() &&
5416          isa<FieldDecl>(Previous.getFoundDecl()) &&
5417          D.getCXXScopeSpec().isSet()) {
5418        // The user tried to define a non-static data member
5419        // out-of-line (C++ [dcl.meaning]p1).
5420        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
5421          << D.getCXXScopeSpec().getRange();
5422        Previous.clear();
5423        NewVD->setInvalidDecl();
5424      }
5425    } else if (D.getCXXScopeSpec().isSet()) {
5426      // No previous declaration in the qualifying scope.
5427      Diag(D.getIdentifierLoc(), diag::err_no_member)
5428        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
5429        << D.getCXXScopeSpec().getRange();
5430      NewVD->setInvalidDecl();
5431    }
5432
5433    if (!IsVariableTemplateSpecialization) {
5434      if (PrevVarTemplate) {
5435        LookupResult PrevDecl(*this, GetNameForDeclarator(D),
5436                              LookupOrdinaryName, ForRedeclaration);
5437        PrevDecl.addDecl(PrevVarTemplate->getTemplatedDecl());
5438        D.setRedeclaration(CheckVariableDeclaration(NewVD, PrevDecl));
5439      } else
5440        D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
5441    }
5442
5443    // This is an explicit specialization of a static data member. Check it.
5444    if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
5445        CheckMemberSpecialization(NewVD, Previous))
5446      NewVD->setInvalidDecl();
5447  }
5448
5449  ProcessPragmaWeak(S, NewVD);
5450  checkAttributesAfterMerging(*this, *NewVD);
5451
5452  // If this is the first declaration of an extern C variable, update
5453  // the map of such variables.
5454  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
5455      isIncompleteDeclExternC(*this, NewVD))
5456    RegisterLocallyScopedExternCDecl(NewVD, S);
5457
5458  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5459    Decl *ManglingContextDecl;
5460    if (MangleNumberingContext *MCtx =
5461            getCurrentMangleNumberContext(NewVD->getDeclContext(),
5462                                          ManglingContextDecl)) {
5463      Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD));
5464    }
5465  }
5466
5467  // If we are providing an explicit specialization of a static variable
5468  // template, make a note of that.
5469  if (PrevVarTemplate && PrevVarTemplate->getInstantiatedFromMemberTemplate())
5470    PrevVarTemplate->setMemberSpecialization();
5471
5472  if (NewTemplate) {
5473    ActOnDocumentableDecl(NewTemplate);
5474    return NewTemplate;
5475  }
5476
5477  return NewVD;
5478}
5479
5480/// \brief Diagnose variable or built-in function shadowing.  Implements
5481/// -Wshadow.
5482///
5483/// This method is called whenever a VarDecl is added to a "useful"
5484/// scope.
5485///
5486/// \param S the scope in which the shadowing name is being declared
5487/// \param R the lookup of the name
5488///
5489void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
5490  // Return if warning is ignored.
5491  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) ==
5492        DiagnosticsEngine::Ignored)
5493    return;
5494
5495  // Don't diagnose declarations at file scope.
5496  if (D->hasGlobalStorage())
5497    return;
5498
5499  DeclContext *NewDC = D->getDeclContext();
5500
5501  // Only diagnose if we're shadowing an unambiguous field or variable.
5502  if (R.getResultKind() != LookupResult::Found)
5503    return;
5504
5505  NamedDecl* ShadowedDecl = R.getFoundDecl();
5506  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
5507    return;
5508
5509  // Fields are not shadowed by variables in C++ static methods.
5510  if (isa<FieldDecl>(ShadowedDecl))
5511    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
5512      if (MD->isStatic())
5513        return;
5514
5515  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
5516    if (shadowedVar->isExternC()) {
5517      // For shadowing external vars, make sure that we point to the global
5518      // declaration, not a locally scoped extern declaration.
5519      for (VarDecl::redecl_iterator
5520             I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end();
5521           I != E; ++I)
5522        if (I->isFileVarDecl()) {
5523          ShadowedDecl = *I;
5524          break;
5525        }
5526    }
5527
5528  DeclContext *OldDC = ShadowedDecl->getDeclContext();
5529
5530  // Only warn about certain kinds of shadowing for class members.
5531  if (NewDC && NewDC->isRecord()) {
5532    // In particular, don't warn about shadowing non-class members.
5533    if (!OldDC->isRecord())
5534      return;
5535
5536    // TODO: should we warn about static data members shadowing
5537    // static data members from base classes?
5538
5539    // TODO: don't diagnose for inaccessible shadowed members.
5540    // This is hard to do perfectly because we might friend the
5541    // shadowing context, but that's just a false negative.
5542  }
5543
5544  // Determine what kind of declaration we're shadowing.
5545  unsigned Kind;
5546  if (isa<RecordDecl>(OldDC)) {
5547    if (isa<FieldDecl>(ShadowedDecl))
5548      Kind = 3; // field
5549    else
5550      Kind = 2; // static data member
5551  } else if (OldDC->isFileContext())
5552    Kind = 1; // global
5553  else
5554    Kind = 0; // local
5555
5556  DeclarationName Name = R.getLookupName();
5557
5558  // Emit warning and note.
5559  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
5560  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
5561}
5562
5563/// \brief Check -Wshadow without the advantage of a previous lookup.
5564void Sema::CheckShadow(Scope *S, VarDecl *D) {
5565  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) ==
5566        DiagnosticsEngine::Ignored)
5567    return;
5568
5569  LookupResult R(*this, D->getDeclName(), D->getLocation(),
5570                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
5571  LookupName(R, S);
5572  CheckShadow(S, D, R);
5573}
5574
5575/// Check for conflict between this global or extern "C" declaration and
5576/// previous global or extern "C" declarations. This is only used in C++.
5577template<typename T>
5578static bool checkGlobalOrExternCConflict(
5579    Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
5580  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
5581  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
5582
5583  if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
5584    // The common case: this global doesn't conflict with any extern "C"
5585    // declaration.
5586    return false;
5587  }
5588
5589  if (Prev) {
5590    if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
5591      // Both the old and new declarations have C language linkage. This is a
5592      // redeclaration.
5593      Previous.clear();
5594      Previous.addDecl(Prev);
5595      return true;
5596    }
5597
5598    // This is a global, non-extern "C" declaration, and there is a previous
5599    // non-global extern "C" declaration. Diagnose if this is a variable
5600    // declaration.
5601    if (!isa<VarDecl>(ND))
5602      return false;
5603  } else {
5604    // The declaration is extern "C". Check for any declaration in the
5605    // translation unit which might conflict.
5606    if (IsGlobal) {
5607      // We have already performed the lookup into the translation unit.
5608      IsGlobal = false;
5609      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5610           I != E; ++I) {
5611        if (isa<VarDecl>(*I)) {
5612          Prev = *I;
5613          break;
5614        }
5615      }
5616    } else {
5617      DeclContext::lookup_result R =
5618          S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
5619      for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
5620           I != E; ++I) {
5621        if (isa<VarDecl>(*I)) {
5622          Prev = *I;
5623          break;
5624        }
5625        // FIXME: If we have any other entity with this name in global scope,
5626        // the declaration is ill-formed, but that is a defect: it breaks the
5627        // 'stat' hack, for instance. Only variables can have mangled name
5628        // clashes with extern "C" declarations, so only they deserve a
5629        // diagnostic.
5630      }
5631    }
5632
5633    if (!Prev)
5634      return false;
5635  }
5636
5637  // Use the first declaration's location to ensure we point at something which
5638  // is lexically inside an extern "C" linkage-spec.
5639  assert(Prev && "should have found a previous declaration to diagnose");
5640  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
5641    Prev = FD->getFirstDecl();
5642  else
5643    Prev = cast<VarDecl>(Prev)->getFirstDecl();
5644
5645  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
5646    << IsGlobal << ND;
5647  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
5648    << IsGlobal;
5649  return false;
5650}
5651
5652/// Apply special rules for handling extern "C" declarations. Returns \c true
5653/// if we have found that this is a redeclaration of some prior entity.
5654///
5655/// Per C++ [dcl.link]p6:
5656///   Two declarations [for a function or variable] with C language linkage
5657///   with the same name that appear in different scopes refer to the same
5658///   [entity]. An entity with C language linkage shall not be declared with
5659///   the same name as an entity in global scope.
5660template<typename T>
5661static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
5662                                                  LookupResult &Previous) {
5663  if (!S.getLangOpts().CPlusPlus) {
5664    // In C, when declaring a global variable, look for a corresponding 'extern'
5665    // variable declared in function scope. We don't need this in C++, because
5666    // we find local extern decls in the surrounding file-scope DeclContext.
5667    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5668      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
5669        Previous.clear();
5670        Previous.addDecl(Prev);
5671        return true;
5672      }
5673    }
5674    return false;
5675  }
5676
5677  // A declaration in the translation unit can conflict with an extern "C"
5678  // declaration.
5679  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
5680    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
5681
5682  // An extern "C" declaration can conflict with a declaration in the
5683  // translation unit or can be a redeclaration of an extern "C" declaration
5684  // in another scope.
5685  if (isIncompleteDeclExternC(S,ND))
5686    return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
5687
5688  // Neither global nor extern "C": nothing to do.
5689  return false;
5690}
5691
5692void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
5693  // If the decl is already known invalid, don't check it.
5694  if (NewVD->isInvalidDecl())
5695    return;
5696
5697  TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
5698  QualType T = TInfo->getType();
5699
5700  // Defer checking an 'auto' type until its initializer is attached.
5701  if (T->isUndeducedType())
5702    return;
5703
5704  if (T->isObjCObjectType()) {
5705    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
5706      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
5707    T = Context.getObjCObjectPointerType(T);
5708    NewVD->setType(T);
5709  }
5710
5711  // Emit an error if an address space was applied to decl with local storage.
5712  // This includes arrays of objects with address space qualifiers, but not
5713  // automatic variables that point to other address spaces.
5714  // ISO/IEC TR 18037 S5.1.2
5715  if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
5716    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
5717    NewVD->setInvalidDecl();
5718    return;
5719  }
5720
5721  // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
5722  // __constant address space.
5723  if (getLangOpts().OpenCL && NewVD->isFileVarDecl()
5724      && T.getAddressSpace() != LangAS::opencl_constant
5725      && !T->isSamplerT()){
5726    Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space);
5727    NewVD->setInvalidDecl();
5728    return;
5729  }
5730
5731  // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
5732  // scope.
5733  if ((getLangOpts().OpenCLVersion >= 120)
5734      && NewVD->isStaticLocal()) {
5735    Diag(NewVD->getLocation(), diag::err_static_function_scope);
5736    NewVD->setInvalidDecl();
5737    return;
5738  }
5739
5740  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
5741      && !NewVD->hasAttr<BlocksAttr>()) {
5742    if (getLangOpts().getGC() != LangOptions::NonGC)
5743      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
5744    else {
5745      assert(!getLangOpts().ObjCAutoRefCount);
5746      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
5747    }
5748  }
5749
5750  bool isVM = T->isVariablyModifiedType();
5751  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
5752      NewVD->hasAttr<BlocksAttr>())
5753    getCurFunction()->setHasBranchProtectedScope();
5754
5755  if ((isVM && NewVD->hasLinkage()) ||
5756      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
5757    bool SizeIsNegative;
5758    llvm::APSInt Oversized;
5759    TypeSourceInfo *FixedTInfo =
5760      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5761                                                    SizeIsNegative, Oversized);
5762    if (FixedTInfo == 0 && T->isVariableArrayType()) {
5763      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
5764      // FIXME: This won't give the correct result for
5765      // int a[10][n];
5766      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
5767
5768      if (NewVD->isFileVarDecl())
5769        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
5770        << SizeRange;
5771      else if (NewVD->isStaticLocal())
5772        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
5773        << SizeRange;
5774      else
5775        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
5776        << SizeRange;
5777      NewVD->setInvalidDecl();
5778      return;
5779    }
5780
5781    if (FixedTInfo == 0) {
5782      if (NewVD->isFileVarDecl())
5783        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
5784      else
5785        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
5786      NewVD->setInvalidDecl();
5787      return;
5788    }
5789
5790    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
5791    NewVD->setType(FixedTInfo->getType());
5792    NewVD->setTypeSourceInfo(FixedTInfo);
5793  }
5794
5795  if (T->isVoidType()) {
5796    // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
5797    //                    of objects and functions.
5798    if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
5799      Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
5800        << T;
5801      NewVD->setInvalidDecl();
5802      return;
5803    }
5804  }
5805
5806  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
5807    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
5808    NewVD->setInvalidDecl();
5809    return;
5810  }
5811
5812  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
5813    Diag(NewVD->getLocation(), diag::err_block_on_vm);
5814    NewVD->setInvalidDecl();
5815    return;
5816  }
5817
5818  if (NewVD->isConstexpr() && !T->isDependentType() &&
5819      RequireLiteralType(NewVD->getLocation(), T,
5820                         diag::err_constexpr_var_non_literal)) {
5821    // Can't perform this check until the type is deduced.
5822    NewVD->setInvalidDecl();
5823    return;
5824  }
5825}
5826
5827/// \brief Perform semantic checking on a newly-created variable
5828/// declaration.
5829///
5830/// This routine performs all of the type-checking required for a
5831/// variable declaration once it has been built. It is used both to
5832/// check variables after they have been parsed and their declarators
5833/// have been translated into a declaration, and to check variables
5834/// that have been instantiated from a template.
5835///
5836/// Sets NewVD->isInvalidDecl() if an error was encountered.
5837///
5838/// Returns true if the variable declaration is a redeclaration.
5839bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
5840  CheckVariableDeclarationType(NewVD);
5841
5842  // If the decl is already known invalid, don't check it.
5843  if (NewVD->isInvalidDecl())
5844    return false;
5845
5846  // If we did not find anything by this name, look for a non-visible
5847  // extern "C" declaration with the same name.
5848  if (Previous.empty() &&
5849      checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
5850    Previous.setShadowed();
5851
5852  // Filter out any non-conflicting previous declarations.
5853  filterNonConflictingPreviousDecls(Context, NewVD, Previous);
5854
5855  if (!Previous.empty()) {
5856    MergeVarDecl(NewVD, Previous);
5857    return true;
5858  }
5859  return false;
5860}
5861
5862/// \brief Data used with FindOverriddenMethod
5863struct FindOverriddenMethodData {
5864  Sema *S;
5865  CXXMethodDecl *Method;
5866};
5867
5868/// \brief Member lookup function that determines whether a given C++
5869/// method overrides a method in a base class, to be used with
5870/// CXXRecordDecl::lookupInBases().
5871static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
5872                                 CXXBasePath &Path,
5873                                 void *UserData) {
5874  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
5875
5876  FindOverriddenMethodData *Data
5877    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
5878
5879  DeclarationName Name = Data->Method->getDeclName();
5880
5881  // FIXME: Do we care about other names here too?
5882  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
5883    // We really want to find the base class destructor here.
5884    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
5885    CanQualType CT = Data->S->Context.getCanonicalType(T);
5886
5887    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
5888  }
5889
5890  for (Path.Decls = BaseRecord->lookup(Name);
5891       !Path.Decls.empty();
5892       Path.Decls = Path.Decls.slice(1)) {
5893    NamedDecl *D = Path.Decls.front();
5894    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
5895      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false))
5896        return true;
5897    }
5898  }
5899
5900  return false;
5901}
5902
5903namespace {
5904  enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
5905}
5906/// \brief Report an error regarding overriding, along with any relevant
5907/// overriden methods.
5908///
5909/// \param DiagID the primary error to report.
5910/// \param MD the overriding method.
5911/// \param OEK which overrides to include as notes.
5912static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
5913                            OverrideErrorKind OEK = OEK_All) {
5914  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
5915  for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
5916                                      E = MD->end_overridden_methods();
5917       I != E; ++I) {
5918    // This check (& the OEK parameter) could be replaced by a predicate, but
5919    // without lambdas that would be overkill. This is still nicer than writing
5920    // out the diag loop 3 times.
5921    if ((OEK == OEK_All) ||
5922        (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
5923        (OEK == OEK_Deleted && (*I)->isDeleted()))
5924      S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
5925  }
5926}
5927
5928/// AddOverriddenMethods - See if a method overrides any in the base classes,
5929/// and if so, check that it's a valid override and remember it.
5930bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
5931  // Look for virtual methods in base classes that this method might override.
5932  CXXBasePaths Paths;
5933  FindOverriddenMethodData Data;
5934  Data.Method = MD;
5935  Data.S = this;
5936  bool hasDeletedOverridenMethods = false;
5937  bool hasNonDeletedOverridenMethods = false;
5938  bool AddedAny = false;
5939  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
5940    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
5941         E = Paths.found_decls_end(); I != E; ++I) {
5942      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
5943        MD->addOverriddenMethod(OldMD->getCanonicalDecl());
5944        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
5945            !CheckOverridingFunctionAttributes(MD, OldMD) &&
5946            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
5947            !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
5948          hasDeletedOverridenMethods |= OldMD->isDeleted();
5949          hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
5950          AddedAny = true;
5951        }
5952      }
5953    }
5954  }
5955
5956  if (hasDeletedOverridenMethods && !MD->isDeleted()) {
5957    ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
5958  }
5959  if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
5960    ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
5961  }
5962
5963  return AddedAny;
5964}
5965
5966namespace {
5967  // Struct for holding all of the extra arguments needed by
5968  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
5969  struct ActOnFDArgs {
5970    Scope *S;
5971    Declarator &D;
5972    MultiTemplateParamsArg TemplateParamLists;
5973    bool AddToScope;
5974  };
5975}
5976
5977namespace {
5978
5979// Callback to only accept typo corrections that have a non-zero edit distance.
5980// Also only accept corrections that have the same parent decl.
5981class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
5982 public:
5983  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
5984                            CXXRecordDecl *Parent)
5985      : Context(Context), OriginalFD(TypoFD),
5986        ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {}
5987
5988  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5989    if (candidate.getEditDistance() == 0)
5990      return false;
5991
5992    SmallVector<unsigned, 1> MismatchedParams;
5993    for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
5994                                          CDeclEnd = candidate.end();
5995         CDecl != CDeclEnd; ++CDecl) {
5996      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
5997
5998      if (FD && !FD->hasBody() &&
5999          hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6000        if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6001          CXXRecordDecl *Parent = MD->getParent();
6002          if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6003            return true;
6004        } else if (!ExpectedParent) {
6005          return true;
6006        }
6007      }
6008    }
6009
6010    return false;
6011  }
6012
6013 private:
6014  ASTContext &Context;
6015  FunctionDecl *OriginalFD;
6016  CXXRecordDecl *ExpectedParent;
6017};
6018
6019}
6020
6021/// \brief Generate diagnostics for an invalid function redeclaration.
6022///
6023/// This routine handles generating the diagnostic messages for an invalid
6024/// function redeclaration, including finding possible similar declarations
6025/// or performing typo correction if there are no previous declarations with
6026/// the same name.
6027///
6028/// Returns a NamedDecl iff typo correction was performed and substituting in
6029/// the new declaration name does not cause new errors.
6030static NamedDecl *DiagnoseInvalidRedeclaration(
6031    Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6032    ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6033  DeclarationName Name = NewFD->getDeclName();
6034  DeclContext *NewDC = NewFD->getDeclContext();
6035  SmallVector<unsigned, 1> MismatchedParams;
6036  SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6037  TypoCorrection Correction;
6038  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6039  unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6040                                   : diag::err_member_decl_does_not_match;
6041  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6042                    IsLocalFriend ? Sema::LookupLocalFriendName
6043                                  : Sema::LookupOrdinaryName,
6044                    Sema::ForRedeclaration);
6045
6046  NewFD->setInvalidDecl();
6047  if (IsLocalFriend)
6048    SemaRef.LookupName(Prev, S);
6049  else
6050    SemaRef.LookupQualifiedName(Prev, NewDC);
6051  assert(!Prev.isAmbiguous() &&
6052         "Cannot have an ambiguity in previous-declaration lookup");
6053  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6054  DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD,
6055                                      MD ? MD->getParent() : 0);
6056  if (!Prev.empty()) {
6057    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6058         Func != FuncEnd; ++Func) {
6059      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6060      if (FD &&
6061          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6062        // Add 1 to the index so that 0 can mean the mismatch didn't
6063        // involve a parameter
6064        unsigned ParamNum =
6065            MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6066        NearMatches.push_back(std::make_pair(FD, ParamNum));
6067      }
6068    }
6069  // If the qualified name lookup yielded nothing, try typo correction
6070  } else if ((Correction = SemaRef.CorrectTypo(
6071                 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6072                 &ExtraArgs.D.getCXXScopeSpec(), Validator,
6073                 IsLocalFriend ? 0 : NewDC))) {
6074    // Set up everything for the call to ActOnFunctionDeclarator
6075    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6076                              ExtraArgs.D.getIdentifierLoc());
6077    Previous.clear();
6078    Previous.setLookupName(Correction.getCorrection());
6079    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6080                                    CDeclEnd = Correction.end();
6081         CDecl != CDeclEnd; ++CDecl) {
6082      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6083      if (FD && !FD->hasBody() &&
6084          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6085        Previous.addDecl(FD);
6086      }
6087    }
6088    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6089
6090    NamedDecl *Result;
6091    // Retry building the function declaration with the new previous
6092    // declarations, and with errors suppressed.
6093    {
6094      // Trap errors.
6095      Sema::SFINAETrap Trap(SemaRef);
6096
6097      // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6098      // pieces need to verify the typo-corrected C++ declaration and hopefully
6099      // eliminate the need for the parameter pack ExtraArgs.
6100      Result = SemaRef.ActOnFunctionDeclarator(
6101          ExtraArgs.S, ExtraArgs.D,
6102          Correction.getCorrectionDecl()->getDeclContext(),
6103          NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6104          ExtraArgs.AddToScope);
6105
6106      if (Trap.hasErrorOccurred())
6107        Result = 0;
6108    }
6109
6110    if (Result) {
6111      // Determine which correction we picked.
6112      Decl *Canonical = Result->getCanonicalDecl();
6113      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6114           I != E; ++I)
6115        if ((*I)->getCanonicalDecl() == Canonical)
6116          Correction.setCorrectionDecl(*I);
6117
6118      SemaRef.diagnoseTypo(
6119          Correction,
6120          SemaRef.PDiag(IsLocalFriend
6121                          ? diag::err_no_matching_local_friend_suggest
6122                          : diag::err_member_decl_does_not_match_suggest)
6123            << Name << NewDC << IsDefinition);
6124      return Result;
6125    }
6126
6127    // Pretend the typo correction never occurred
6128    ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6129                              ExtraArgs.D.getIdentifierLoc());
6130    ExtraArgs.D.setRedeclaration(wasRedeclaration);
6131    Previous.clear();
6132    Previous.setLookupName(Name);
6133  }
6134
6135  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6136      << Name << NewDC << IsDefinition << NewFD->getLocation();
6137
6138  bool NewFDisConst = false;
6139  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6140    NewFDisConst = NewMD->isConst();
6141
6142  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6143       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6144       NearMatch != NearMatchEnd; ++NearMatch) {
6145    FunctionDecl *FD = NearMatch->first;
6146    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6147    bool FDisConst = MD && MD->isConst();
6148    bool IsMember = MD || !IsLocalFriend;
6149
6150    // FIXME: These notes are poorly worded for the local friend case.
6151    if (unsigned Idx = NearMatch->second) {
6152      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6153      SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6154      if (Loc.isInvalid()) Loc = FD->getLocation();
6155      SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6156                                 : diag::note_local_decl_close_param_match)
6157        << Idx << FDParam->getType()
6158        << NewFD->getParamDecl(Idx - 1)->getType();
6159    } else if (FDisConst != NewFDisConst) {
6160      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6161          << NewFDisConst << FD->getSourceRange().getEnd();
6162    } else
6163      SemaRef.Diag(FD->getLocation(),
6164                   IsMember ? diag::note_member_def_close_match
6165                            : diag::note_local_decl_close_match);
6166  }
6167  return 0;
6168}
6169
6170static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef,
6171                                                          Declarator &D) {
6172  switch (D.getDeclSpec().getStorageClassSpec()) {
6173  default: llvm_unreachable("Unknown storage class!");
6174  case DeclSpec::SCS_auto:
6175  case DeclSpec::SCS_register:
6176  case DeclSpec::SCS_mutable:
6177    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6178                 diag::err_typecheck_sclass_func);
6179    D.setInvalidType();
6180    break;
6181  case DeclSpec::SCS_unspecified: break;
6182  case DeclSpec::SCS_extern:
6183    if (D.getDeclSpec().isExternInLinkageSpec())
6184      return SC_None;
6185    return SC_Extern;
6186  case DeclSpec::SCS_static: {
6187    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6188      // C99 6.7.1p5:
6189      //   The declaration of an identifier for a function that has
6190      //   block scope shall have no explicit storage-class specifier
6191      //   other than extern
6192      // See also (C++ [dcl.stc]p4).
6193      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6194                   diag::err_static_block_func);
6195      break;
6196    } else
6197      return SC_Static;
6198  }
6199  case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
6200  }
6201
6202  // No explicit storage class has already been returned
6203  return SC_None;
6204}
6205
6206static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
6207                                           DeclContext *DC, QualType &R,
6208                                           TypeSourceInfo *TInfo,
6209                                           FunctionDecl::StorageClass SC,
6210                                           bool &IsVirtualOkay) {
6211  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
6212  DeclarationName Name = NameInfo.getName();
6213
6214  FunctionDecl *NewFD = 0;
6215  bool isInline = D.getDeclSpec().isInlineSpecified();
6216
6217  if (!SemaRef.getLangOpts().CPlusPlus) {
6218    // Determine whether the function was written with a
6219    // prototype. This true when:
6220    //   - there is a prototype in the declarator, or
6221    //   - the type R of the function is some kind of typedef or other reference
6222    //     to a type name (which eventually refers to a function type).
6223    bool HasPrototype =
6224      (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
6225      (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
6226
6227    NewFD = FunctionDecl::Create(SemaRef.Context, DC,
6228                                 D.getLocStart(), NameInfo, R,
6229                                 TInfo, SC, isInline,
6230                                 HasPrototype, false);
6231    if (D.isInvalidType())
6232      NewFD->setInvalidDecl();
6233
6234    // Set the lexical context.
6235    NewFD->setLexicalDeclContext(SemaRef.CurContext);
6236
6237    return NewFD;
6238  }
6239
6240  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6241  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6242
6243  // Check that the return type is not an abstract class type.
6244  // For record types, this is done by the AbstractClassUsageDiagnoser once
6245  // the class has been completely parsed.
6246  if (!DC->isRecord() &&
6247      SemaRef.RequireNonAbstractType(D.getIdentifierLoc(),
6248                                     R->getAs<FunctionType>()->getResultType(),
6249                                     diag::err_abstract_type_in_decl,
6250                                     SemaRef.AbstractReturnType))
6251    D.setInvalidType();
6252
6253  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
6254    // This is a C++ constructor declaration.
6255    assert(DC->isRecord() &&
6256           "Constructors can only be declared in a member context");
6257
6258    R = SemaRef.CheckConstructorDeclarator(D, R, SC);
6259    return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6260                                      D.getLocStart(), NameInfo,
6261                                      R, TInfo, isExplicit, isInline,
6262                                      /*isImplicitlyDeclared=*/false,
6263                                      isConstexpr);
6264
6265  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6266    // This is a C++ destructor declaration.
6267    if (DC->isRecord()) {
6268      R = SemaRef.CheckDestructorDeclarator(D, R, SC);
6269      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
6270      CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
6271                                        SemaRef.Context, Record,
6272                                        D.getLocStart(),
6273                                        NameInfo, R, TInfo, isInline,
6274                                        /*isImplicitlyDeclared=*/false);
6275
6276      // If the class is complete, then we now create the implicit exception
6277      // specification. If the class is incomplete or dependent, we can't do
6278      // it yet.
6279      if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
6280          Record->getDefinition() && !Record->isBeingDefined() &&
6281          R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
6282        SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
6283      }
6284
6285      // The Microsoft ABI requires that we perform the destructor body
6286      // checks (i.e. operator delete() lookup) at every declaration, as
6287      // any translation unit may need to emit a deleting destructor.
6288      if (SemaRef.Context.getTargetInfo().getCXXABI().isMicrosoft() &&
6289          !Record->isDependentType() && Record->getDefinition() &&
6290          !Record->isBeingDefined()) {
6291        SemaRef.CheckDestructor(NewDD);
6292      }
6293
6294      IsVirtualOkay = true;
6295      return NewDD;
6296
6297    } else {
6298      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
6299      D.setInvalidType();
6300
6301      // Create a FunctionDecl to satisfy the function definition parsing
6302      // code path.
6303      return FunctionDecl::Create(SemaRef.Context, DC,
6304                                  D.getLocStart(),
6305                                  D.getIdentifierLoc(), Name, R, TInfo,
6306                                  SC, isInline,
6307                                  /*hasPrototype=*/true, isConstexpr);
6308    }
6309
6310  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
6311    if (!DC->isRecord()) {
6312      SemaRef.Diag(D.getIdentifierLoc(),
6313           diag::err_conv_function_not_member);
6314      return 0;
6315    }
6316
6317    SemaRef.CheckConversionDeclarator(D, R, SC);
6318    IsVirtualOkay = true;
6319    return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
6320                                     D.getLocStart(), NameInfo,
6321                                     R, TInfo, isInline, isExplicit,
6322                                     isConstexpr, SourceLocation());
6323
6324  } else if (DC->isRecord()) {
6325    // If the name of the function is the same as the name of the record,
6326    // then this must be an invalid constructor that has a return type.
6327    // (The parser checks for a return type and makes the declarator a
6328    // constructor if it has no return type).
6329    if (Name.getAsIdentifierInfo() &&
6330        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
6331      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
6332        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
6333        << SourceRange(D.getIdentifierLoc());
6334      return 0;
6335    }
6336
6337    // This is a C++ method declaration.
6338    CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
6339                                               cast<CXXRecordDecl>(DC),
6340                                               D.getLocStart(), NameInfo, R,
6341                                               TInfo, SC, isInline,
6342                                               isConstexpr, SourceLocation());
6343    IsVirtualOkay = !Ret->isStatic();
6344    return Ret;
6345  } else {
6346    // Determine whether the function was written with a
6347    // prototype. This true when:
6348    //   - we're in C++ (where every function has a prototype),
6349    return FunctionDecl::Create(SemaRef.Context, DC,
6350                                D.getLocStart(),
6351                                NameInfo, R, TInfo, SC, isInline,
6352                                true/*HasPrototype*/, isConstexpr);
6353  }
6354}
6355
6356void Sema::checkVoidParamDecl(ParmVarDecl *Param) {
6357  // In C++, the empty parameter-type-list must be spelled "void"; a
6358  // typedef of void is not permitted.
6359  if (getLangOpts().CPlusPlus &&
6360      Param->getType().getUnqualifiedType() != Context.VoidTy) {
6361    bool IsTypeAlias = false;
6362    if (const TypedefType *TT = Param->getType()->getAs<TypedefType>())
6363      IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl());
6364    else if (const TemplateSpecializationType *TST =
6365               Param->getType()->getAs<TemplateSpecializationType>())
6366      IsTypeAlias = TST->isTypeAlias();
6367    Diag(Param->getLocation(), diag::err_param_typedef_of_void)
6368      << IsTypeAlias;
6369  }
6370}
6371
6372enum OpenCLParamType {
6373  ValidKernelParam,
6374  PtrPtrKernelParam,
6375  PtrKernelParam,
6376  InvalidKernelParam,
6377  RecordKernelParam
6378};
6379
6380static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
6381  if (PT->isPointerType()) {
6382    QualType PointeeType = PT->getPointeeType();
6383    return PointeeType->isPointerType() ? PtrPtrKernelParam : PtrKernelParam;
6384  }
6385
6386  // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
6387  // be used as builtin types.
6388
6389  if (PT->isImageType())
6390    return PtrKernelParam;
6391
6392  if (PT->isBooleanType())
6393    return InvalidKernelParam;
6394
6395  if (PT->isEventT())
6396    return InvalidKernelParam;
6397
6398  if (PT->isHalfType())
6399    return InvalidKernelParam;
6400
6401  if (PT->isRecordType())
6402    return RecordKernelParam;
6403
6404  return ValidKernelParam;
6405}
6406
6407static void checkIsValidOpenCLKernelParameter(
6408  Sema &S,
6409  Declarator &D,
6410  ParmVarDecl *Param,
6411  llvm::SmallPtrSet<const Type *, 16> &ValidTypes) {
6412  QualType PT = Param->getType();
6413
6414  // Cache the valid types we encounter to avoid rechecking structs that are
6415  // used again
6416  if (ValidTypes.count(PT.getTypePtr()))
6417    return;
6418
6419  switch (getOpenCLKernelParameterType(PT)) {
6420  case PtrPtrKernelParam:
6421    // OpenCL v1.2 s6.9.a:
6422    // A kernel function argument cannot be declared as a
6423    // pointer to a pointer type.
6424    S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
6425    D.setInvalidType();
6426    return;
6427
6428    // OpenCL v1.2 s6.9.k:
6429    // Arguments to kernel functions in a program cannot be declared with the
6430    // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
6431    // uintptr_t or a struct and/or union that contain fields declared to be
6432    // one of these built-in scalar types.
6433
6434  case InvalidKernelParam:
6435    // OpenCL v1.2 s6.8 n:
6436    // A kernel function argument cannot be declared
6437    // of event_t type.
6438    S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6439    D.setInvalidType();
6440    return;
6441
6442  case PtrKernelParam:
6443  case ValidKernelParam:
6444    ValidTypes.insert(PT.getTypePtr());
6445    return;
6446
6447  case RecordKernelParam:
6448    break;
6449  }
6450
6451  // Track nested structs we will inspect
6452  SmallVector<const Decl *, 4> VisitStack;
6453
6454  // Track where we are in the nested structs. Items will migrate from
6455  // VisitStack to HistoryStack as we do the DFS for bad field.
6456  SmallVector<const FieldDecl *, 4> HistoryStack;
6457  HistoryStack.push_back((const FieldDecl *) 0);
6458
6459  const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
6460  VisitStack.push_back(PD);
6461
6462  assert(VisitStack.back() && "First decl null?");
6463
6464  do {
6465    const Decl *Next = VisitStack.pop_back_val();
6466    if (!Next) {
6467      assert(!HistoryStack.empty());
6468      // Found a marker, we have gone up a level
6469      if (const FieldDecl *Hist = HistoryStack.pop_back_val())
6470        ValidTypes.insert(Hist->getType().getTypePtr());
6471
6472      continue;
6473    }
6474
6475    // Adds everything except the original parameter declaration (which is not a
6476    // field itself) to the history stack.
6477    const RecordDecl *RD;
6478    if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
6479      HistoryStack.push_back(Field);
6480      RD = Field->getType()->castAs<RecordType>()->getDecl();
6481    } else {
6482      RD = cast<RecordDecl>(Next);
6483    }
6484
6485    // Add a null marker so we know when we've gone back up a level
6486    VisitStack.push_back((const Decl *) 0);
6487
6488    for (RecordDecl::field_iterator I = RD->field_begin(),
6489           E = RD->field_end(); I != E; ++I) {
6490      const FieldDecl *FD = *I;
6491      QualType QT = FD->getType();
6492
6493      if (ValidTypes.count(QT.getTypePtr()))
6494        continue;
6495
6496      OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
6497      if (ParamType == ValidKernelParam)
6498        continue;
6499
6500      if (ParamType == RecordKernelParam) {
6501        VisitStack.push_back(FD);
6502        continue;
6503      }
6504
6505      // OpenCL v1.2 s6.9.p:
6506      // Arguments to kernel functions that are declared to be a struct or union
6507      // do not allow OpenCL objects to be passed as elements of the struct or
6508      // union.
6509      if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam) {
6510        S.Diag(Param->getLocation(),
6511               diag::err_record_with_pointers_kernel_param)
6512          << PT->isUnionType()
6513          << PT;
6514      } else {
6515        S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
6516      }
6517
6518      S.Diag(PD->getLocation(), diag::note_within_field_of_type)
6519        << PD->getDeclName();
6520
6521      // We have an error, now let's go back up through history and show where
6522      // the offending field came from
6523      for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1,
6524             E = HistoryStack.end(); I != E; ++I) {
6525        const FieldDecl *OuterField = *I;
6526        S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
6527          << OuterField->getType();
6528      }
6529
6530      S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
6531        << QT->isPointerType()
6532        << QT;
6533      D.setInvalidType();
6534      return;
6535    }
6536  } while (!VisitStack.empty());
6537}
6538
6539NamedDecl*
6540Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
6541                              TypeSourceInfo *TInfo, LookupResult &Previous,
6542                              MultiTemplateParamsArg TemplateParamLists,
6543                              bool &AddToScope) {
6544  QualType R = TInfo->getType();
6545
6546  assert(R.getTypePtr()->isFunctionType());
6547
6548  // TODO: consider using NameInfo for diagnostic.
6549  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6550  DeclarationName Name = NameInfo.getName();
6551  FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D);
6552
6553  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
6554    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6555         diag::err_invalid_thread)
6556      << DeclSpec::getSpecifierName(TSCS);
6557
6558  if (D.isFirstDeclarationOfMember())
6559    adjustMemberFunctionCC(R, D.isStaticMember());
6560
6561  bool isFriend = false;
6562  FunctionTemplateDecl *FunctionTemplate = 0;
6563  bool isExplicitSpecialization = false;
6564  bool isFunctionTemplateSpecialization = false;
6565
6566  bool isDependentClassScopeExplicitSpecialization = false;
6567  bool HasExplicitTemplateArgs = false;
6568  TemplateArgumentListInfo TemplateArgs;
6569
6570  bool isVirtualOkay = false;
6571
6572  DeclContext *OriginalDC = DC;
6573  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
6574
6575  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
6576                                              isVirtualOkay);
6577  if (!NewFD) return 0;
6578
6579  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
6580    NewFD->setTopLevelDeclInObjCContainer();
6581
6582  // Set the lexical context. If this is a function-scope declaration, or has a
6583  // C++ scope specifier, or is the object of a friend declaration, the lexical
6584  // context will be different from the semantic context.
6585  NewFD->setLexicalDeclContext(CurContext);
6586
6587  if (IsLocalExternDecl)
6588    NewFD->setLocalExternDecl();
6589
6590  if (getLangOpts().CPlusPlus) {
6591    bool isInline = D.getDeclSpec().isInlineSpecified();
6592    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
6593    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
6594    bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
6595    isFriend = D.getDeclSpec().isFriendSpecified();
6596    if (isFriend && !isInline && D.isFunctionDefinition()) {
6597      // C++ [class.friend]p5
6598      //   A function can be defined in a friend declaration of a
6599      //   class . . . . Such a function is implicitly inline.
6600      NewFD->setImplicitlyInline();
6601    }
6602
6603    // If this is a method defined in an __interface, and is not a constructor
6604    // or an overloaded operator, then set the pure flag (isVirtual will already
6605    // return true).
6606    if (const CXXRecordDecl *Parent =
6607          dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
6608      if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
6609        NewFD->setPure(true);
6610    }
6611
6612    SetNestedNameSpecifier(NewFD, D);
6613    isExplicitSpecialization = false;
6614    isFunctionTemplateSpecialization = false;
6615    if (D.isInvalidType())
6616      NewFD->setInvalidDecl();
6617
6618    // Match up the template parameter lists with the scope specifier, then
6619    // determine whether we have a template or a template specialization.
6620    bool Invalid = false;
6621    if (TemplateParameterList *TemplateParams =
6622            MatchTemplateParametersToScopeSpecifier(
6623                D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6624                D.getCXXScopeSpec(), TemplateParamLists, isFriend,
6625                isExplicitSpecialization, Invalid)) {
6626      if (TemplateParams->size() > 0) {
6627        // This is a function template
6628
6629        // Check that we can declare a template here.
6630        if (CheckTemplateDeclScope(S, TemplateParams))
6631          return 0;
6632
6633        // A destructor cannot be a template.
6634        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6635          Diag(NewFD->getLocation(), diag::err_destructor_template);
6636          return 0;
6637        }
6638
6639        // If we're adding a template to a dependent context, we may need to
6640        // rebuilding some of the types used within the template parameter list,
6641        // now that we know what the current instantiation is.
6642        if (DC->isDependentContext()) {
6643          ContextRAII SavedContext(*this, DC);
6644          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
6645            Invalid = true;
6646        }
6647
6648
6649        FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
6650                                                        NewFD->getLocation(),
6651                                                        Name, TemplateParams,
6652                                                        NewFD);
6653        FunctionTemplate->setLexicalDeclContext(CurContext);
6654        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
6655
6656        // For source fidelity, store the other template param lists.
6657        if (TemplateParamLists.size() > 1) {
6658          NewFD->setTemplateParameterListsInfo(Context,
6659                                               TemplateParamLists.size() - 1,
6660                                               TemplateParamLists.data());
6661        }
6662      } else {
6663        // This is a function template specialization.
6664        isFunctionTemplateSpecialization = true;
6665        // For source fidelity, store all the template param lists.
6666        NewFD->setTemplateParameterListsInfo(Context,
6667                                             TemplateParamLists.size(),
6668                                             TemplateParamLists.data());
6669
6670        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
6671        if (isFriend) {
6672          // We want to remove the "template<>", found here.
6673          SourceRange RemoveRange = TemplateParams->getSourceRange();
6674
6675          // If we remove the template<> and the name is not a
6676          // template-id, we're actually silently creating a problem:
6677          // the friend declaration will refer to an untemplated decl,
6678          // and clearly the user wants a template specialization.  So
6679          // we need to insert '<>' after the name.
6680          SourceLocation InsertLoc;
6681          if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6682            InsertLoc = D.getName().getSourceRange().getEnd();
6683            InsertLoc = PP.getLocForEndOfToken(InsertLoc);
6684          }
6685
6686          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
6687            << Name << RemoveRange
6688            << FixItHint::CreateRemoval(RemoveRange)
6689            << FixItHint::CreateInsertion(InsertLoc, "<>");
6690        }
6691      }
6692    }
6693    else {
6694      // All template param lists were matched against the scope specifier:
6695      // this is NOT (an explicit specialization of) a template.
6696      if (TemplateParamLists.size() > 0)
6697        // For source fidelity, store all the template param lists.
6698        NewFD->setTemplateParameterListsInfo(Context,
6699                                             TemplateParamLists.size(),
6700                                             TemplateParamLists.data());
6701    }
6702
6703    if (Invalid) {
6704      NewFD->setInvalidDecl();
6705      if (FunctionTemplate)
6706        FunctionTemplate->setInvalidDecl();
6707    }
6708
6709    // C++ [dcl.fct.spec]p5:
6710    //   The virtual specifier shall only be used in declarations of
6711    //   nonstatic class member functions that appear within a
6712    //   member-specification of a class declaration; see 10.3.
6713    //
6714    if (isVirtual && !NewFD->isInvalidDecl()) {
6715      if (!isVirtualOkay) {
6716        Diag(D.getDeclSpec().getVirtualSpecLoc(),
6717             diag::err_virtual_non_function);
6718      } else if (!CurContext->isRecord()) {
6719        // 'virtual' was specified outside of the class.
6720        Diag(D.getDeclSpec().getVirtualSpecLoc(),
6721             diag::err_virtual_out_of_class)
6722          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6723      } else if (NewFD->getDescribedFunctionTemplate()) {
6724        // C++ [temp.mem]p3:
6725        //  A member function template shall not be virtual.
6726        Diag(D.getDeclSpec().getVirtualSpecLoc(),
6727             diag::err_virtual_member_function_template)
6728          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
6729      } else {
6730        // Okay: Add virtual to the method.
6731        NewFD->setVirtualAsWritten(true);
6732      }
6733
6734      if (getLangOpts().CPlusPlus1y &&
6735          NewFD->getResultType()->isUndeducedType())
6736        Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
6737    }
6738
6739    if (getLangOpts().CPlusPlus1y && NewFD->isDependentContext() &&
6740        NewFD->getResultType()->isUndeducedType()) {
6741      // If the function template is referenced directly (for instance, as a
6742      // member of the current instantiation), pretend it has a dependent type.
6743      // This is not really justified by the standard, but is the only sane
6744      // thing to do.
6745      const FunctionProtoType *FPT =
6746          NewFD->getType()->castAs<FunctionProtoType>();
6747      QualType Result = SubstAutoType(FPT->getResultType(),
6748                                       Context.DependentTy);
6749      NewFD->setType(Context.getFunctionType(Result, FPT->getArgTypes(),
6750                                             FPT->getExtProtoInfo()));
6751    }
6752
6753    // C++ [dcl.fct.spec]p3:
6754    //  The inline specifier shall not appear on a block scope function
6755    //  declaration.
6756    if (isInline && !NewFD->isInvalidDecl()) {
6757      if (CurContext->isFunctionOrMethod()) {
6758        // 'inline' is not allowed on block scope function declaration.
6759        Diag(D.getDeclSpec().getInlineSpecLoc(),
6760             diag::err_inline_declaration_block_scope) << Name
6761          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6762      }
6763    }
6764
6765    // C++ [dcl.fct.spec]p6:
6766    //  The explicit specifier shall be used only in the declaration of a
6767    //  constructor or conversion function within its class definition;
6768    //  see 12.3.1 and 12.3.2.
6769    if (isExplicit && !NewFD->isInvalidDecl()) {
6770      if (!CurContext->isRecord()) {
6771        // 'explicit' was specified outside of the class.
6772        Diag(D.getDeclSpec().getExplicitSpecLoc(),
6773             diag::err_explicit_out_of_class)
6774          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6775      } else if (!isa<CXXConstructorDecl>(NewFD) &&
6776                 !isa<CXXConversionDecl>(NewFD)) {
6777        // 'explicit' was specified on a function that wasn't a constructor
6778        // or conversion function.
6779        Diag(D.getDeclSpec().getExplicitSpecLoc(),
6780             diag::err_explicit_non_ctor_or_conv_function)
6781          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
6782      }
6783    }
6784
6785    if (isConstexpr) {
6786      // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
6787      // are implicitly inline.
6788      NewFD->setImplicitlyInline();
6789
6790      // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
6791      // be either constructors or to return a literal type. Therefore,
6792      // destructors cannot be declared constexpr.
6793      if (isa<CXXDestructorDecl>(NewFD))
6794        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
6795    }
6796
6797    // If __module_private__ was specified, mark the function accordingly.
6798    if (D.getDeclSpec().isModulePrivateSpecified()) {
6799      if (isFunctionTemplateSpecialization) {
6800        SourceLocation ModulePrivateLoc
6801          = D.getDeclSpec().getModulePrivateSpecLoc();
6802        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
6803          << 0
6804          << FixItHint::CreateRemoval(ModulePrivateLoc);
6805      } else {
6806        NewFD->setModulePrivate();
6807        if (FunctionTemplate)
6808          FunctionTemplate->setModulePrivate();
6809      }
6810    }
6811
6812    if (isFriend) {
6813      if (FunctionTemplate) {
6814        FunctionTemplate->setObjectOfFriendDecl();
6815        FunctionTemplate->setAccess(AS_public);
6816      }
6817      NewFD->setObjectOfFriendDecl();
6818      NewFD->setAccess(AS_public);
6819    }
6820
6821    // If a function is defined as defaulted or deleted, mark it as such now.
6822    switch (D.getFunctionDefinitionKind()) {
6823      case FDK_Declaration:
6824      case FDK_Definition:
6825        break;
6826
6827      case FDK_Defaulted:
6828        NewFD->setDefaulted();
6829        break;
6830
6831      case FDK_Deleted:
6832        NewFD->setDeletedAsWritten();
6833        break;
6834    }
6835
6836    if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
6837        D.isFunctionDefinition()) {
6838      // C++ [class.mfct]p2:
6839      //   A member function may be defined (8.4) in its class definition, in
6840      //   which case it is an inline member function (7.1.2)
6841      NewFD->setImplicitlyInline();
6842    }
6843
6844    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
6845        !CurContext->isRecord()) {
6846      // C++ [class.static]p1:
6847      //   A data or function member of a class may be declared static
6848      //   in a class definition, in which case it is a static member of
6849      //   the class.
6850
6851      // Complain about the 'static' specifier if it's on an out-of-line
6852      // member function definition.
6853      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6854           diag::err_static_out_of_line)
6855        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6856    }
6857
6858    // C++11 [except.spec]p15:
6859    //   A deallocation function with no exception-specification is treated
6860    //   as if it were specified with noexcept(true).
6861    const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
6862    if ((Name.getCXXOverloadedOperator() == OO_Delete ||
6863         Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
6864        getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) {
6865      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6866      EPI.ExceptionSpecType = EST_BasicNoexcept;
6867      NewFD->setType(Context.getFunctionType(FPT->getResultType(),
6868                                             FPT->getArgTypes(), EPI));
6869    }
6870
6871    // C++11 [replacement.functions]p3:
6872    //  The program's definitions shall not be specified as inline.
6873    //
6874    // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
6875    if (isInline && NewFD->isReplaceableGlobalAllocationFunction())
6876      Diag(D.getDeclSpec().getInlineSpecLoc(),
6877           diag::err_operator_new_delete_declared_inline)
6878        << NewFD->getDeclName();
6879  }
6880
6881  // Filter out previous declarations that don't match the scope.
6882  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
6883                       isExplicitSpecialization ||
6884                       isFunctionTemplateSpecialization);
6885
6886  // Handle GNU asm-label extension (encoded as an attribute).
6887  if (Expr *E = (Expr*) D.getAsmLabel()) {
6888    // The parser guarantees this is a string.
6889    StringLiteral *SE = cast<StringLiteral>(E);
6890    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
6891                                                SE->getString()));
6892  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6893    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6894      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
6895    if (I != ExtnameUndeclaredIdentifiers.end()) {
6896      NewFD->addAttr(I->second);
6897      ExtnameUndeclaredIdentifiers.erase(I);
6898    }
6899  }
6900
6901  // Copy the parameter declarations from the declarator D to the function
6902  // declaration NewFD, if they are available.  First scavenge them into Params.
6903  SmallVector<ParmVarDecl*, 16> Params;
6904  if (D.isFunctionDeclarator()) {
6905    DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6906
6907    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
6908    // function that takes no arguments, not a function that takes a
6909    // single void argument.
6910    // We let through "const void" here because Sema::GetTypeForDeclarator
6911    // already checks for that case.
6912    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6913        FTI.ArgInfo[0].Param &&
6914        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
6915      // Empty arg list, don't push any params.
6916      checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
6917    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
6918      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6919        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
6920        assert(Param->getDeclContext() != NewFD && "Was set before ?");
6921        Param->setDeclContext(NewFD);
6922        Params.push_back(Param);
6923
6924        if (Param->isInvalidDecl())
6925          NewFD->setInvalidDecl();
6926      }
6927    }
6928
6929  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
6930    // When we're declaring a function with a typedef, typeof, etc as in the
6931    // following example, we'll need to synthesize (unnamed)
6932    // parameters for use in the declaration.
6933    //
6934    // @code
6935    // typedef void fn(int);
6936    // fn f;
6937    // @endcode
6938
6939    // Synthesize a parameter for each argument type.
6940    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
6941         AE = FT->arg_type_end(); AI != AE; ++AI) {
6942      ParmVarDecl *Param =
6943        BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI);
6944      Param->setScopeInfo(0, Params.size());
6945      Params.push_back(Param);
6946    }
6947  } else {
6948    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
6949           "Should not need args for typedef of non-prototype fn");
6950  }
6951
6952  // Finally, we know we have the right number of parameters, install them.
6953  NewFD->setParams(Params);
6954
6955  // Find all anonymous symbols defined during the declaration of this function
6956  // and add to NewFD. This lets us track decls such 'enum Y' in:
6957  //
6958  //   void f(enum Y {AA} x) {}
6959  //
6960  // which would otherwise incorrectly end up in the translation unit scope.
6961  NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
6962  DeclsInPrototypeScope.clear();
6963
6964  if (D.getDeclSpec().isNoreturnSpecified())
6965    NewFD->addAttr(
6966        ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
6967                                       Context));
6968
6969  // Functions returning a variably modified type violate C99 6.7.5.2p2
6970  // because all functions have linkage.
6971  if (!NewFD->isInvalidDecl() &&
6972      NewFD->getResultType()->isVariablyModifiedType()) {
6973    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
6974    NewFD->setInvalidDecl();
6975  }
6976
6977  // Handle attributes.
6978  ProcessDeclAttributes(S, NewFD, D);
6979
6980  QualType RetType = NewFD->getResultType();
6981  const CXXRecordDecl *Ret = RetType->isRecordType() ?
6982      RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl();
6983  if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() &&
6984      Ret && Ret->hasAttr<WarnUnusedResultAttr>()) {
6985    const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6986    // Attach the attribute to the new decl. Don't apply the attribute if it
6987    // returns an instance of the class (e.g. assignment operators).
6988    if (!MD || MD->getParent() != Ret) {
6989      NewFD->addAttr(new (Context) WarnUnusedResultAttr(SourceRange(),
6990                                                        Context));
6991    }
6992  }
6993
6994  if (!getLangOpts().CPlusPlus) {
6995    // Perform semantic checking on the function declaration.
6996    bool isExplicitSpecialization=false;
6997    if (!NewFD->isInvalidDecl() && NewFD->isMain())
6998      CheckMain(NewFD, D.getDeclSpec());
6999
7000    if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7001      CheckMSVCRTEntryPoint(NewFD);
7002
7003    if (!NewFD->isInvalidDecl())
7004      D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7005                                                  isExplicitSpecialization));
7006    else if (!Previous.empty())
7007      // Make graceful recovery from an invalid redeclaration.
7008      D.setRedeclaration(true);
7009    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7010            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7011           "previous declaration set still overloaded");
7012  } else {
7013    // If the declarator is a template-id, translate the parser's template
7014    // argument list into our AST format.
7015    if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7016      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7017      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7018      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7019      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7020                                         TemplateId->NumArgs);
7021      translateTemplateArguments(TemplateArgsPtr,
7022                                 TemplateArgs);
7023
7024      HasExplicitTemplateArgs = true;
7025
7026      if (NewFD->isInvalidDecl()) {
7027        HasExplicitTemplateArgs = false;
7028      } else if (FunctionTemplate) {
7029        // Function template with explicit template arguments.
7030        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7031          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7032
7033        HasExplicitTemplateArgs = false;
7034      } else if (!isFunctionTemplateSpecialization &&
7035                 !D.getDeclSpec().isFriendSpecified()) {
7036        // We have encountered something that the user meant to be a
7037        // specialization (because it has explicitly-specified template
7038        // arguments) but that was not introduced with a "template<>" (or had
7039        // too few of them).
7040        // FIXME: Differentiate between attempts for explicit instantiations
7041        // (starting with "template") and the rest.
7042        Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
7043          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
7044          << FixItHint::CreateInsertion(
7045                                    D.getDeclSpec().getLocStart(),
7046                                        "template<> ");
7047        isFunctionTemplateSpecialization = true;
7048      } else {
7049        // "friend void foo<>(int);" is an implicit specialization decl.
7050        isFunctionTemplateSpecialization = true;
7051      }
7052    } else if (isFriend && isFunctionTemplateSpecialization) {
7053      // This combination is only possible in a recovery case;  the user
7054      // wrote something like:
7055      //   template <> friend void foo(int);
7056      // which we're recovering from as if the user had written:
7057      //   friend void foo<>(int);
7058      // Go ahead and fake up a template id.
7059      HasExplicitTemplateArgs = true;
7060        TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7061      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7062    }
7063
7064    // If it's a friend (and only if it's a friend), it's possible
7065    // that either the specialized function type or the specialized
7066    // template is dependent, and therefore matching will fail.  In
7067    // this case, don't check the specialization yet.
7068    bool InstantiationDependent = false;
7069    if (isFunctionTemplateSpecialization && isFriend &&
7070        (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7071         TemplateSpecializationType::anyDependentTemplateArguments(
7072            TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7073            InstantiationDependent))) {
7074      assert(HasExplicitTemplateArgs &&
7075             "friend function specialization without template args");
7076      if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7077                                                       Previous))
7078        NewFD->setInvalidDecl();
7079    } else if (isFunctionTemplateSpecialization) {
7080      if (CurContext->isDependentContext() && CurContext->isRecord()
7081          && !isFriend) {
7082        isDependentClassScopeExplicitSpecialization = true;
7083        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7084          diag::ext_function_specialization_in_class :
7085          diag::err_function_specialization_in_class)
7086          << NewFD->getDeclName();
7087      } else if (CheckFunctionTemplateSpecialization(NewFD,
7088                                  (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7089                                                     Previous))
7090        NewFD->setInvalidDecl();
7091
7092      // C++ [dcl.stc]p1:
7093      //   A storage-class-specifier shall not be specified in an explicit
7094      //   specialization (14.7.3)
7095      FunctionTemplateSpecializationInfo *Info =
7096          NewFD->getTemplateSpecializationInfo();
7097      if (Info && SC != SC_None) {
7098        if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7099          Diag(NewFD->getLocation(),
7100               diag::err_explicit_specialization_inconsistent_storage_class)
7101            << SC
7102            << FixItHint::CreateRemoval(
7103                                      D.getDeclSpec().getStorageClassSpecLoc());
7104
7105        else
7106          Diag(NewFD->getLocation(),
7107               diag::ext_explicit_specialization_storage_class)
7108            << FixItHint::CreateRemoval(
7109                                      D.getDeclSpec().getStorageClassSpecLoc());
7110      }
7111
7112    } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
7113      if (CheckMemberSpecialization(NewFD, Previous))
7114          NewFD->setInvalidDecl();
7115    }
7116
7117    // Perform semantic checking on the function declaration.
7118    if (!isDependentClassScopeExplicitSpecialization) {
7119      if (!NewFD->isInvalidDecl() && NewFD->isMain())
7120        CheckMain(NewFD, D.getDeclSpec());
7121
7122      if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7123        CheckMSVCRTEntryPoint(NewFD);
7124
7125      if (NewFD->isInvalidDecl()) {
7126        // If this is a class member, mark the class invalid immediately.
7127        // This avoids some consistency errors later.
7128        if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD))
7129          methodDecl->getParent()->setInvalidDecl();
7130      } else
7131        D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7132                                                    isExplicitSpecialization));
7133    }
7134
7135    assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7136            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7137           "previous declaration set still overloaded");
7138
7139    NamedDecl *PrincipalDecl = (FunctionTemplate
7140                                ? cast<NamedDecl>(FunctionTemplate)
7141                                : NewFD);
7142
7143    if (isFriend && D.isRedeclaration()) {
7144      AccessSpecifier Access = AS_public;
7145      if (!NewFD->isInvalidDecl())
7146        Access = NewFD->getPreviousDecl()->getAccess();
7147
7148      NewFD->setAccess(Access);
7149      if (FunctionTemplate) FunctionTemplate->setAccess(Access);
7150    }
7151
7152    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
7153        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
7154      PrincipalDecl->setNonMemberOperator();
7155
7156    // If we have a function template, check the template parameter
7157    // list. This will check and merge default template arguments.
7158    if (FunctionTemplate) {
7159      FunctionTemplateDecl *PrevTemplate =
7160                                     FunctionTemplate->getPreviousDecl();
7161      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
7162                       PrevTemplate ? PrevTemplate->getTemplateParameters() : 0,
7163                            D.getDeclSpec().isFriendSpecified()
7164                              ? (D.isFunctionDefinition()
7165                                   ? TPC_FriendFunctionTemplateDefinition
7166                                   : TPC_FriendFunctionTemplate)
7167                              : (D.getCXXScopeSpec().isSet() &&
7168                                 DC && DC->isRecord() &&
7169                                 DC->isDependentContext())
7170                                  ? TPC_ClassTemplateMember
7171                                  : TPC_FunctionTemplate);
7172    }
7173
7174    if (NewFD->isInvalidDecl()) {
7175      // Ignore all the rest of this.
7176    } else if (!D.isRedeclaration()) {
7177      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
7178                                       AddToScope };
7179      // Fake up an access specifier if it's supposed to be a class member.
7180      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
7181        NewFD->setAccess(AS_public);
7182
7183      // Qualified decls generally require a previous declaration.
7184      if (D.getCXXScopeSpec().isSet()) {
7185        // ...with the major exception of templated-scope or
7186        // dependent-scope friend declarations.
7187
7188        // TODO: we currently also suppress this check in dependent
7189        // contexts because (1) the parameter depth will be off when
7190        // matching friend templates and (2) we might actually be
7191        // selecting a friend based on a dependent factor.  But there
7192        // are situations where these conditions don't apply and we
7193        // can actually do this check immediately.
7194        if (isFriend &&
7195            (TemplateParamLists.size() ||
7196             D.getCXXScopeSpec().getScopeRep()->isDependent() ||
7197             CurContext->isDependentContext())) {
7198          // ignore these
7199        } else {
7200          // The user tried to provide an out-of-line definition for a
7201          // function that is a member of a class or namespace, but there
7202          // was no such member function declared (C++ [class.mfct]p2,
7203          // C++ [namespace.memdef]p2). For example:
7204          //
7205          // class X {
7206          //   void f() const;
7207          // };
7208          //
7209          // void X::f() { } // ill-formed
7210          //
7211          // Complain about this problem, and attempt to suggest close
7212          // matches (e.g., those that differ only in cv-qualifiers and
7213          // whether the parameter types are references).
7214
7215          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7216                  *this, Previous, NewFD, ExtraArgs, false, 0)) {
7217            AddToScope = ExtraArgs.AddToScope;
7218            return Result;
7219          }
7220        }
7221
7222        // Unqualified local friend declarations are required to resolve
7223        // to something.
7224      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
7225        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
7226                *this, Previous, NewFD, ExtraArgs, true, S)) {
7227          AddToScope = ExtraArgs.AddToScope;
7228          return Result;
7229        }
7230      }
7231
7232    } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() &&
7233               !isFriend && !isFunctionTemplateSpecialization &&
7234               !isExplicitSpecialization) {
7235      // An out-of-line member function declaration must also be a
7236      // definition (C++ [dcl.meaning]p1).
7237      // Note that this is not the case for explicit specializations of
7238      // function templates or member functions of class templates, per
7239      // C++ [temp.expl.spec]p2. We also allow these declarations as an
7240      // extension for compatibility with old SWIG code which likes to
7241      // generate them.
7242      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
7243        << D.getCXXScopeSpec().getRange();
7244    }
7245  }
7246
7247  ProcessPragmaWeak(S, NewFD);
7248  checkAttributesAfterMerging(*this, *NewFD);
7249
7250  AddKnownFunctionAttributes(NewFD);
7251
7252  if (NewFD->hasAttr<OverloadableAttr>() &&
7253      !NewFD->getType()->getAs<FunctionProtoType>()) {
7254    Diag(NewFD->getLocation(),
7255         diag::err_attribute_overloadable_no_prototype)
7256      << NewFD;
7257
7258    // Turn this into a variadic function with no parameters.
7259    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
7260    FunctionProtoType::ExtProtoInfo EPI(
7261        Context.getDefaultCallingConvention(true, false));
7262    EPI.Variadic = true;
7263    EPI.ExtInfo = FT->getExtInfo();
7264
7265    QualType R = Context.getFunctionType(FT->getResultType(), None, EPI);
7266    NewFD->setType(R);
7267  }
7268
7269  // If there's a #pragma GCC visibility in scope, and this isn't a class
7270  // member, set the visibility of this function.
7271  if (!DC->isRecord() && NewFD->isExternallyVisible())
7272    AddPushedVisibilityAttribute(NewFD);
7273
7274  // If there's a #pragma clang arc_cf_code_audited in scope, consider
7275  // marking the function.
7276  AddCFAuditedAttribute(NewFD);
7277
7278  // If this is the first declaration of an extern C variable, update
7279  // the map of such variables.
7280  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
7281      isIncompleteDeclExternC(*this, NewFD))
7282    RegisterLocallyScopedExternCDecl(NewFD, S);
7283
7284  // Set this FunctionDecl's range up to the right paren.
7285  NewFD->setRangeEnd(D.getSourceRange().getEnd());
7286
7287  if (getLangOpts().CPlusPlus) {
7288    if (FunctionTemplate) {
7289      if (NewFD->isInvalidDecl())
7290        FunctionTemplate->setInvalidDecl();
7291      return FunctionTemplate;
7292    }
7293  }
7294
7295  if (NewFD->hasAttr<OpenCLKernelAttr>()) {
7296    // OpenCL v1.2 s6.8 static is invalid for kernel functions.
7297    if ((getLangOpts().OpenCLVersion >= 120)
7298        && (SC == SC_Static)) {
7299      Diag(D.getIdentifierLoc(), diag::err_static_kernel);
7300      D.setInvalidType();
7301    }
7302
7303    // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
7304    if (!NewFD->getResultType()->isVoidType()) {
7305      Diag(D.getIdentifierLoc(),
7306           diag::err_expected_kernel_void_return_type);
7307      D.setInvalidType();
7308    }
7309
7310    llvm::SmallPtrSet<const Type *, 16> ValidTypes;
7311    for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
7312         PE = NewFD->param_end(); PI != PE; ++PI) {
7313      ParmVarDecl *Param = *PI;
7314      checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
7315    }
7316  }
7317
7318  MarkUnusedFileScopedDecl(NewFD);
7319
7320  if (getLangOpts().CUDA)
7321    if (IdentifierInfo *II = NewFD->getIdentifier())
7322      if (!NewFD->isInvalidDecl() &&
7323          NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7324        if (II->isStr("cudaConfigureCall")) {
7325          if (!R->getAs<FunctionType>()->getResultType()->isScalarType())
7326            Diag(NewFD->getLocation(), diag::err_config_scalar_return);
7327
7328          Context.setcudaConfigureCallDecl(NewFD);
7329        }
7330      }
7331
7332  // Here we have an function template explicit specialization at class scope.
7333  // The actually specialization will be postponed to template instatiation
7334  // time via the ClassScopeFunctionSpecializationDecl node.
7335  if (isDependentClassScopeExplicitSpecialization) {
7336    ClassScopeFunctionSpecializationDecl *NewSpec =
7337                         ClassScopeFunctionSpecializationDecl::Create(
7338                                Context, CurContext, SourceLocation(),
7339                                cast<CXXMethodDecl>(NewFD),
7340                                HasExplicitTemplateArgs, TemplateArgs);
7341    CurContext->addDecl(NewSpec);
7342    AddToScope = false;
7343  }
7344
7345  return NewFD;
7346}
7347
7348/// \brief Perform semantic checking of a new function declaration.
7349///
7350/// Performs semantic analysis of the new function declaration
7351/// NewFD. This routine performs all semantic checking that does not
7352/// require the actual declarator involved in the declaration, and is
7353/// used both for the declaration of functions as they are parsed
7354/// (called via ActOnDeclarator) and for the declaration of functions
7355/// that have been instantiated via C++ template instantiation (called
7356/// via InstantiateDecl).
7357///
7358/// \param IsExplicitSpecialization whether this new function declaration is
7359/// an explicit specialization of the previous declaration.
7360///
7361/// This sets NewFD->isInvalidDecl() to true if there was an error.
7362///
7363/// \returns true if the function declaration is a redeclaration.
7364bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
7365                                    LookupResult &Previous,
7366                                    bool IsExplicitSpecialization) {
7367  assert(!NewFD->getResultType()->isVariablyModifiedType()
7368         && "Variably modified return types are not handled here");
7369
7370  // Determine whether the type of this function should be merged with
7371  // a previous visible declaration. This never happens for functions in C++,
7372  // and always happens in C if the previous declaration was visible.
7373  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
7374                               !Previous.isShadowed();
7375
7376  // Filter out any non-conflicting previous declarations.
7377  filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7378
7379  bool Redeclaration = false;
7380  NamedDecl *OldDecl = 0;
7381
7382  // Merge or overload the declaration with an existing declaration of
7383  // the same name, if appropriate.
7384  if (!Previous.empty()) {
7385    // Determine whether NewFD is an overload of PrevDecl or
7386    // a declaration that requires merging. If it's an overload,
7387    // there's no more work to do here; we'll just add the new
7388    // function to the scope.
7389    if (!AllowOverloadingOfFunction(Previous, Context)) {
7390      NamedDecl *Candidate = Previous.getFoundDecl();
7391      if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
7392        Redeclaration = true;
7393        OldDecl = Candidate;
7394      }
7395    } else {
7396      switch (CheckOverload(S, NewFD, Previous, OldDecl,
7397                            /*NewIsUsingDecl*/ false)) {
7398      case Ovl_Match:
7399        Redeclaration = true;
7400        break;
7401
7402      case Ovl_NonFunction:
7403        Redeclaration = true;
7404        break;
7405
7406      case Ovl_Overload:
7407        Redeclaration = false;
7408        break;
7409      }
7410
7411      if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7412        // If a function name is overloadable in C, then every function
7413        // with that name must be marked "overloadable".
7414        Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7415          << Redeclaration << NewFD;
7416        NamedDecl *OverloadedDecl = 0;
7417        if (Redeclaration)
7418          OverloadedDecl = OldDecl;
7419        else if (!Previous.empty())
7420          OverloadedDecl = Previous.getRepresentativeDecl();
7421        if (OverloadedDecl)
7422          Diag(OverloadedDecl->getLocation(),
7423               diag::note_attribute_overloadable_prev_overload);
7424        NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7425                                                        Context));
7426      }
7427    }
7428  }
7429
7430  // Check for a previous extern "C" declaration with this name.
7431  if (!Redeclaration &&
7432      checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
7433    filterNonConflictingPreviousDecls(Context, NewFD, Previous);
7434    if (!Previous.empty()) {
7435      // This is an extern "C" declaration with the same name as a previous
7436      // declaration, and thus redeclares that entity...
7437      Redeclaration = true;
7438      OldDecl = Previous.getFoundDecl();
7439      MergeTypeWithPrevious = false;
7440
7441      // ... except in the presence of __attribute__((overloadable)).
7442      if (OldDecl->hasAttr<OverloadableAttr>()) {
7443        if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
7444          Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
7445            << Redeclaration << NewFD;
7446          Diag(Previous.getFoundDecl()->getLocation(),
7447               diag::note_attribute_overloadable_prev_overload);
7448          NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(),
7449                                                          Context));
7450        }
7451        if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
7452          Redeclaration = false;
7453          OldDecl = 0;
7454        }
7455      }
7456    }
7457  }
7458
7459  // C++11 [dcl.constexpr]p8:
7460  //   A constexpr specifier for a non-static member function that is not
7461  //   a constructor declares that member function to be const.
7462  //
7463  // This needs to be delayed until we know whether this is an out-of-line
7464  // definition of a static member function.
7465  //
7466  // This rule is not present in C++1y, so we produce a backwards
7467  // compatibility warning whenever it happens in C++11.
7468  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7469  if (!getLangOpts().CPlusPlus1y && MD && MD->isConstexpr() &&
7470      !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
7471      (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
7472    CXXMethodDecl *OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl);
7473    if (FunctionTemplateDecl *OldTD =
7474          dyn_cast_or_null<FunctionTemplateDecl>(OldDecl))
7475      OldMD = dyn_cast<CXXMethodDecl>(OldTD->getTemplatedDecl());
7476    if (!OldMD || !OldMD->isStatic()) {
7477      const FunctionProtoType *FPT =
7478        MD->getType()->castAs<FunctionProtoType>();
7479      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7480      EPI.TypeQuals |= Qualifiers::Const;
7481      MD->setType(Context.getFunctionType(FPT->getResultType(),
7482                                          FPT->getArgTypes(), EPI));
7483
7484      // Warn that we did this, if we're not performing template instantiation.
7485      // In that case, we'll have warned already when the template was defined.
7486      if (ActiveTemplateInstantiations.empty()) {
7487        SourceLocation AddConstLoc;
7488        if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
7489                .IgnoreParens().getAs<FunctionTypeLoc>())
7490          AddConstLoc = PP.getLocForEndOfToken(FTL.getRParenLoc());
7491
7492        Diag(MD->getLocation(), diag::warn_cxx1y_compat_constexpr_not_const)
7493          << FixItHint::CreateInsertion(AddConstLoc, " const");
7494      }
7495    }
7496  }
7497
7498  if (Redeclaration) {
7499    // NewFD and OldDecl represent declarations that need to be
7500    // merged.
7501    if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
7502      NewFD->setInvalidDecl();
7503      return Redeclaration;
7504    }
7505
7506    Previous.clear();
7507    Previous.addDecl(OldDecl);
7508
7509    if (FunctionTemplateDecl *OldTemplateDecl
7510                                  = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
7511      NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
7512      FunctionTemplateDecl *NewTemplateDecl
7513        = NewFD->getDescribedFunctionTemplate();
7514      assert(NewTemplateDecl && "Template/non-template mismatch");
7515      if (CXXMethodDecl *Method
7516            = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
7517        Method->setAccess(OldTemplateDecl->getAccess());
7518        NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
7519      }
7520
7521      // If this is an explicit specialization of a member that is a function
7522      // template, mark it as a member specialization.
7523      if (IsExplicitSpecialization &&
7524          NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
7525        NewTemplateDecl->setMemberSpecialization();
7526        assert(OldTemplateDecl->isMemberSpecialization());
7527      }
7528
7529    } else {
7530      // This needs to happen first so that 'inline' propagates.
7531      NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
7532
7533      if (isa<CXXMethodDecl>(NewFD)) {
7534        // A valid redeclaration of a C++ method must be out-of-line,
7535        // but (unfortunately) it's not necessarily a definition
7536        // because of templates, which means that the previous
7537        // declaration is not necessarily from the class definition.
7538
7539        // For just setting the access, that doesn't matter.
7540        CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl);
7541        NewFD->setAccess(oldMethod->getAccess());
7542
7543        // Update the key-function state if necessary for this ABI.
7544        if (NewFD->isInlined() &&
7545            !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
7546          // setNonKeyFunction needs to work with the original
7547          // declaration from the class definition, and isVirtual() is
7548          // just faster in that case, so map back to that now.
7549          oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl());
7550          if (oldMethod->isVirtual()) {
7551            Context.setNonKeyFunction(oldMethod);
7552          }
7553        }
7554      }
7555    }
7556  }
7557
7558  // Semantic checking for this function declaration (in isolation).
7559  if (getLangOpts().CPlusPlus) {
7560    // C++-specific checks.
7561    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
7562      CheckConstructor(Constructor);
7563    } else if (CXXDestructorDecl *Destructor =
7564                dyn_cast<CXXDestructorDecl>(NewFD)) {
7565      CXXRecordDecl *Record = Destructor->getParent();
7566      QualType ClassType = Context.getTypeDeclType(Record);
7567
7568      // FIXME: Shouldn't we be able to perform this check even when the class
7569      // type is dependent? Both gcc and edg can handle that.
7570      if (!ClassType->isDependentType()) {
7571        DeclarationName Name
7572          = Context.DeclarationNames.getCXXDestructorName(
7573                                        Context.getCanonicalType(ClassType));
7574        if (NewFD->getDeclName() != Name) {
7575          Diag(NewFD->getLocation(), diag::err_destructor_name);
7576          NewFD->setInvalidDecl();
7577          return Redeclaration;
7578        }
7579      }
7580    } else if (CXXConversionDecl *Conversion
7581               = dyn_cast<CXXConversionDecl>(NewFD)) {
7582      ActOnConversionDeclarator(Conversion);
7583    }
7584
7585    // Find any virtual functions that this function overrides.
7586    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
7587      if (!Method->isFunctionTemplateSpecialization() &&
7588          !Method->getDescribedFunctionTemplate() &&
7589          Method->isCanonicalDecl()) {
7590        if (AddOverriddenMethods(Method->getParent(), Method)) {
7591          // If the function was marked as "static", we have a problem.
7592          if (NewFD->getStorageClass() == SC_Static) {
7593            ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
7594          }
7595        }
7596      }
7597
7598      if (Method->isStatic())
7599        checkThisInStaticMemberFunctionType(Method);
7600    }
7601
7602    // Extra checking for C++ overloaded operators (C++ [over.oper]).
7603    if (NewFD->isOverloadedOperator() &&
7604        CheckOverloadedOperatorDeclaration(NewFD)) {
7605      NewFD->setInvalidDecl();
7606      return Redeclaration;
7607    }
7608
7609    // Extra checking for C++0x literal operators (C++0x [over.literal]).
7610    if (NewFD->getLiteralIdentifier() &&
7611        CheckLiteralOperatorDeclaration(NewFD)) {
7612      NewFD->setInvalidDecl();
7613      return Redeclaration;
7614    }
7615
7616    // In C++, check default arguments now that we have merged decls. Unless
7617    // the lexical context is the class, because in this case this is done
7618    // during delayed parsing anyway.
7619    if (!CurContext->isRecord())
7620      CheckCXXDefaultArguments(NewFD);
7621
7622    // If this function declares a builtin function, check the type of this
7623    // declaration against the expected type for the builtin.
7624    if (unsigned BuiltinID = NewFD->getBuiltinID()) {
7625      ASTContext::GetBuiltinTypeError Error;
7626      LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
7627      QualType T = Context.GetBuiltinType(BuiltinID, Error);
7628      if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
7629        // The type of this function differs from the type of the builtin,
7630        // so forget about the builtin entirely.
7631        Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents);
7632      }
7633    }
7634
7635    // If this function is declared as being extern "C", then check to see if
7636    // the function returns a UDT (class, struct, or union type) that is not C
7637    // compatible, and if it does, warn the user.
7638    // But, issue any diagnostic on the first declaration only.
7639    if (NewFD->isExternC() && Previous.empty()) {
7640      QualType R = NewFD->getResultType();
7641      if (R->isIncompleteType() && !R->isVoidType())
7642        Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
7643            << NewFD << R;
7644      else if (!R.isPODType(Context) && !R->isVoidType() &&
7645               !R->isObjCObjectPointerType())
7646        Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
7647    }
7648  }
7649  return Redeclaration;
7650}
7651
7652static SourceRange getResultSourceRange(const FunctionDecl *FD) {
7653  const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
7654  if (!TSI)
7655    return SourceRange();
7656
7657  TypeLoc TL = TSI->getTypeLoc();
7658  FunctionTypeLoc FunctionTL = TL.getAs<FunctionTypeLoc>();
7659  if (!FunctionTL)
7660    return SourceRange();
7661
7662  TypeLoc ResultTL = FunctionTL.getResultLoc();
7663  if (ResultTL.getUnqualifiedLoc().getAs<BuiltinTypeLoc>())
7664    return ResultTL.getSourceRange();
7665
7666  return SourceRange();
7667}
7668
7669void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
7670  // C++11 [basic.start.main]p3:  A program that declares main to be inline,
7671  //   static or constexpr is ill-formed.
7672  // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
7673  //   appear in a declaration of main.
7674  // static main is not an error under C99, but we should warn about it.
7675  // We accept _Noreturn main as an extension.
7676  if (FD->getStorageClass() == SC_Static)
7677    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
7678         ? diag::err_static_main : diag::warn_static_main)
7679      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
7680  if (FD->isInlineSpecified())
7681    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
7682      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
7683  if (DS.isNoreturnSpecified()) {
7684    SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
7685    SourceRange NoreturnRange(NoreturnLoc,
7686                              PP.getLocForEndOfToken(NoreturnLoc));
7687    Diag(NoreturnLoc, diag::ext_noreturn_main);
7688    Diag(NoreturnLoc, diag::note_main_remove_noreturn)
7689      << FixItHint::CreateRemoval(NoreturnRange);
7690  }
7691  if (FD->isConstexpr()) {
7692    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
7693      << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
7694    FD->setConstexpr(false);
7695  }
7696
7697  if (getLangOpts().OpenCL) {
7698    Diag(FD->getLocation(), diag::err_opencl_no_main)
7699        << FD->hasAttr<OpenCLKernelAttr>();
7700    FD->setInvalidDecl();
7701    return;
7702  }
7703
7704  QualType T = FD->getType();
7705  assert(T->isFunctionType() && "function decl is not of function type");
7706  const FunctionType* FT = T->castAs<FunctionType>();
7707
7708  // All the standards say that main() should should return 'int'.
7709  if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
7710    // In C and C++, main magically returns 0 if you fall off the end;
7711    // set the flag which tells us that.
7712    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
7713    FD->setHasImplicitReturnZero(true);
7714
7715  // In C with GNU extensions we allow main() to have non-integer return
7716  // type, but we should warn about the extension, and we disable the
7717  // implicit-return-zero rule.
7718  } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
7719    Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
7720
7721    SourceRange ResultRange = getResultSourceRange(FD);
7722    if (ResultRange.isValid())
7723      Diag(ResultRange.getBegin(), diag::note_main_change_return_type)
7724          << FixItHint::CreateReplacement(ResultRange, "int");
7725
7726  // Otherwise, this is just a flat-out error.
7727  } else {
7728    SourceRange ResultRange = getResultSourceRange(FD);
7729    if (ResultRange.isValid())
7730      Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
7731          << FixItHint::CreateReplacement(ResultRange, "int");
7732    else
7733      Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
7734
7735    FD->setInvalidDecl(true);
7736  }
7737
7738  // Treat protoless main() as nullary.
7739  if (isa<FunctionNoProtoType>(FT)) return;
7740
7741  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
7742  unsigned nparams = FTP->getNumArgs();
7743  assert(FD->getNumParams() == nparams);
7744
7745  bool HasExtraParameters = (nparams > 3);
7746
7747  // Darwin passes an undocumented fourth argument of type char**.  If
7748  // other platforms start sprouting these, the logic below will start
7749  // getting shifty.
7750  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
7751    HasExtraParameters = false;
7752
7753  if (HasExtraParameters) {
7754    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
7755    FD->setInvalidDecl(true);
7756    nparams = 3;
7757  }
7758
7759  // FIXME: a lot of the following diagnostics would be improved
7760  // if we had some location information about types.
7761
7762  QualType CharPP =
7763    Context.getPointerType(Context.getPointerType(Context.CharTy));
7764  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
7765
7766  for (unsigned i = 0; i < nparams; ++i) {
7767    QualType AT = FTP->getArgType(i);
7768
7769    bool mismatch = true;
7770
7771    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
7772      mismatch = false;
7773    else if (Expected[i] == CharPP) {
7774      // As an extension, the following forms are okay:
7775      //   char const **
7776      //   char const * const *
7777      //   char * const *
7778
7779      QualifierCollector qs;
7780      const PointerType* PT;
7781      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
7782          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
7783          Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
7784                              Context.CharTy)) {
7785        qs.removeConst();
7786        mismatch = !qs.empty();
7787      }
7788    }
7789
7790    if (mismatch) {
7791      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
7792      // TODO: suggest replacing given type with expected type
7793      FD->setInvalidDecl(true);
7794    }
7795  }
7796
7797  if (nparams == 1 && !FD->isInvalidDecl()) {
7798    Diag(FD->getLocation(), diag::warn_main_one_arg);
7799  }
7800
7801  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7802    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7803    FD->setInvalidDecl();
7804  }
7805}
7806
7807void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
7808  QualType T = FD->getType();
7809  assert(T->isFunctionType() && "function decl is not of function type");
7810  const FunctionType *FT = T->castAs<FunctionType>();
7811
7812  // Set an implicit return of 'zero' if the function can return some integral,
7813  // enumeration, pointer or nullptr type.
7814  if (FT->getResultType()->isIntegralOrEnumerationType() ||
7815      FT->getResultType()->isAnyPointerType() ||
7816      FT->getResultType()->isNullPtrType())
7817    // DllMain is exempt because a return value of zero means it failed.
7818    if (FD->getName() != "DllMain")
7819      FD->setHasImplicitReturnZero(true);
7820
7821  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
7822    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD->getName();
7823    FD->setInvalidDecl();
7824  }
7825}
7826
7827bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
7828  // FIXME: Need strict checking.  In C89, we need to check for
7829  // any assignment, increment, decrement, function-calls, or
7830  // commas outside of a sizeof.  In C99, it's the same list,
7831  // except that the aforementioned are allowed in unevaluated
7832  // expressions.  Everything else falls under the
7833  // "may accept other forms of constant expressions" exception.
7834  // (We never end up here for C++, so the constant expression
7835  // rules there don't matter.)
7836  if (Init->isConstantInitializer(Context, false))
7837    return false;
7838  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7839    << Init->getSourceRange();
7840  return true;
7841}
7842
7843namespace {
7844  // Visits an initialization expression to see if OrigDecl is evaluated in
7845  // its own initialization and throws a warning if it does.
7846  class SelfReferenceChecker
7847      : public EvaluatedExprVisitor<SelfReferenceChecker> {
7848    Sema &S;
7849    Decl *OrigDecl;
7850    bool isRecordType;
7851    bool isPODType;
7852    bool isReferenceType;
7853
7854  public:
7855    typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
7856
7857    SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
7858                                                    S(S), OrigDecl(OrigDecl) {
7859      isPODType = false;
7860      isRecordType = false;
7861      isReferenceType = false;
7862      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
7863        isPODType = VD->getType().isPODType(S.Context);
7864        isRecordType = VD->getType()->isRecordType();
7865        isReferenceType = VD->getType()->isReferenceType();
7866      }
7867    }
7868
7869    // For most expressions, the cast is directly above the DeclRefExpr.
7870    // For conditional operators, the cast can be outside the conditional
7871    // operator if both expressions are DeclRefExpr's.
7872    void HandleValue(Expr *E) {
7873      if (isReferenceType)
7874        return;
7875      E = E->IgnoreParenImpCasts();
7876      if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
7877        HandleDeclRefExpr(DRE);
7878        return;
7879      }
7880
7881      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7882        HandleValue(CO->getTrueExpr());
7883        HandleValue(CO->getFalseExpr());
7884        return;
7885      }
7886
7887      if (isa<MemberExpr>(E)) {
7888        Expr *Base = E->IgnoreParenImpCasts();
7889        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7890          // Check for static member variables and don't warn on them.
7891          if (!isa<FieldDecl>(ME->getMemberDecl()))
7892            return;
7893          Base = ME->getBase()->IgnoreParenImpCasts();
7894        }
7895        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
7896          HandleDeclRefExpr(DRE);
7897        return;
7898      }
7899    }
7900
7901    // Reference types are handled here since all uses of references are
7902    // bad, not just r-value uses.
7903    void VisitDeclRefExpr(DeclRefExpr *E) {
7904      if (isReferenceType)
7905        HandleDeclRefExpr(E);
7906    }
7907
7908    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
7909      if (E->getCastKind() == CK_LValueToRValue ||
7910          (isRecordType && E->getCastKind() == CK_NoOp))
7911        HandleValue(E->getSubExpr());
7912
7913      Inherited::VisitImplicitCastExpr(E);
7914    }
7915
7916    void VisitMemberExpr(MemberExpr *E) {
7917      // Don't warn on arrays since they can be treated as pointers.
7918      if (E->getType()->canDecayToPointerType()) return;
7919
7920      // Warn when a non-static method call is followed by non-static member
7921      // field accesses, which is followed by a DeclRefExpr.
7922      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
7923      bool Warn = (MD && !MD->isStatic());
7924      Expr *Base = E->getBase()->IgnoreParenImpCasts();
7925      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
7926        if (!isa<FieldDecl>(ME->getMemberDecl()))
7927          Warn = false;
7928        Base = ME->getBase()->IgnoreParenImpCasts();
7929      }
7930
7931      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
7932        if (Warn)
7933          HandleDeclRefExpr(DRE);
7934        return;
7935      }
7936
7937      // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
7938      // Visit that expression.
7939      Visit(Base);
7940    }
7941
7942    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
7943      if (E->getNumArgs() > 0)
7944        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0)))
7945          HandleDeclRefExpr(DRE);
7946
7947      Inherited::VisitCXXOperatorCallExpr(E);
7948    }
7949
7950    void VisitUnaryOperator(UnaryOperator *E) {
7951      // For POD record types, addresses of its own members are well-defined.
7952      if (E->getOpcode() == UO_AddrOf && isRecordType &&
7953          isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
7954        if (!isPODType)
7955          HandleValue(E->getSubExpr());
7956        return;
7957      }
7958      Inherited::VisitUnaryOperator(E);
7959    }
7960
7961    void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
7962
7963    void HandleDeclRefExpr(DeclRefExpr *DRE) {
7964      Decl* ReferenceDecl = DRE->getDecl();
7965      if (OrigDecl != ReferenceDecl) return;
7966      unsigned diag;
7967      if (isReferenceType) {
7968        diag = diag::warn_uninit_self_reference_in_reference_init;
7969      } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
7970        diag = diag::warn_static_self_reference_in_init;
7971      } else {
7972        diag = diag::warn_uninit_self_reference_in_init;
7973      }
7974
7975      S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
7976                            S.PDiag(diag)
7977                              << DRE->getNameInfo().getName()
7978                              << OrigDecl->getLocation()
7979                              << DRE->getSourceRange());
7980    }
7981  };
7982
7983  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
7984  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
7985                                 bool DirectInit) {
7986    // Parameters arguments are occassionially constructed with itself,
7987    // for instance, in recursive functions.  Skip them.
7988    if (isa<ParmVarDecl>(OrigDecl))
7989      return;
7990
7991    E = E->IgnoreParens();
7992
7993    // Skip checking T a = a where T is not a record or reference type.
7994    // Doing so is a way to silence uninitialized warnings.
7995    if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
7996      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
7997        if (ICE->getCastKind() == CK_LValueToRValue)
7998          if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
7999            if (DRE->getDecl() == OrigDecl)
8000              return;
8001
8002    SelfReferenceChecker(S, OrigDecl).Visit(E);
8003  }
8004}
8005
8006/// AddInitializerToDecl - Adds the initializer Init to the
8007/// declaration dcl. If DirectInit is true, this is C++ direct
8008/// initialization rather than copy initialization.
8009void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
8010                                bool DirectInit, bool TypeMayContainAuto) {
8011  // If there is no declaration, there was an error parsing it.  Just ignore
8012  // the initializer.
8013  if (RealDecl == 0 || RealDecl->isInvalidDecl())
8014    return;
8015
8016  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
8017    // With declarators parsed the way they are, the parser cannot
8018    // distinguish between a normal initializer and a pure-specifier.
8019    // Thus this grotesque test.
8020    IntegerLiteral *IL;
8021    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
8022        Context.getCanonicalType(IL->getType()) == Context.IntTy)
8023      CheckPureMethod(Method, Init->getSourceRange());
8024    else {
8025      Diag(Method->getLocation(), diag::err_member_function_initialization)
8026        << Method->getDeclName() << Init->getSourceRange();
8027      Method->setInvalidDecl();
8028    }
8029    return;
8030  }
8031
8032  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
8033  if (!VDecl) {
8034    assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
8035    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
8036    RealDecl->setInvalidDecl();
8037    return;
8038  }
8039  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
8040
8041  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
8042  if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
8043    Expr *DeduceInit = Init;
8044    // Initializer could be a C++ direct-initializer. Deduction only works if it
8045    // contains exactly one expression.
8046    if (CXXDirectInit) {
8047      if (CXXDirectInit->getNumExprs() == 0) {
8048        // It isn't possible to write this directly, but it is possible to
8049        // end up in this situation with "auto x(some_pack...);"
8050        Diag(CXXDirectInit->getLocStart(),
8051             VDecl->isInitCapture() ? diag::err_init_capture_no_expression
8052                                    : diag::err_auto_var_init_no_expression)
8053          << VDecl->getDeclName() << VDecl->getType()
8054          << VDecl->getSourceRange();
8055        RealDecl->setInvalidDecl();
8056        return;
8057      } else if (CXXDirectInit->getNumExprs() > 1) {
8058        Diag(CXXDirectInit->getExpr(1)->getLocStart(),
8059             VDecl->isInitCapture()
8060                 ? diag::err_init_capture_multiple_expressions
8061                 : diag::err_auto_var_init_multiple_expressions)
8062          << VDecl->getDeclName() << VDecl->getType()
8063          << VDecl->getSourceRange();
8064        RealDecl->setInvalidDecl();
8065        return;
8066      } else {
8067        DeduceInit = CXXDirectInit->getExpr(0);
8068      }
8069    }
8070
8071    // Expressions default to 'id' when we're in a debugger.
8072    bool DefaultedToAuto = false;
8073    if (getLangOpts().DebuggerCastResultToId &&
8074        Init->getType() == Context.UnknownAnyTy) {
8075      ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8076      if (Result.isInvalid()) {
8077        VDecl->setInvalidDecl();
8078        return;
8079      }
8080      Init = Result.take();
8081      DefaultedToAuto = true;
8082    }
8083
8084    QualType DeducedType;
8085    if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) ==
8086            DAR_Failed)
8087      DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
8088    if (DeducedType.isNull()) {
8089      RealDecl->setInvalidDecl();
8090      return;
8091    }
8092    VDecl->setType(DeducedType);
8093    assert(VDecl->isLinkageValid());
8094
8095    // In ARC, infer lifetime.
8096    if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
8097      VDecl->setInvalidDecl();
8098
8099    // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
8100    // 'id' instead of a specific object type prevents most of our usual checks.
8101    // We only want to warn outside of template instantiations, though:
8102    // inside a template, the 'id' could have come from a parameter.
8103    if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto &&
8104        DeducedType->isObjCIdType()) {
8105      SourceLocation Loc =
8106          VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
8107      Diag(Loc, diag::warn_auto_var_is_id)
8108        << VDecl->getDeclName() << DeduceInit->getSourceRange();
8109    }
8110
8111    // If this is a redeclaration, check that the type we just deduced matches
8112    // the previously declared type.
8113    if (VarDecl *Old = VDecl->getPreviousDecl()) {
8114      // We never need to merge the type, because we cannot form an incomplete
8115      // array of auto, nor deduce such a type.
8116      MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false);
8117    }
8118
8119    // Check the deduced type is valid for a variable declaration.
8120    CheckVariableDeclarationType(VDecl);
8121    if (VDecl->isInvalidDecl())
8122      return;
8123  }
8124
8125  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
8126    // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
8127    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
8128    VDecl->setInvalidDecl();
8129    return;
8130  }
8131
8132  if (!VDecl->getType()->isDependentType()) {
8133    // A definition must end up with a complete type, which means it must be
8134    // complete with the restriction that an array type might be completed by
8135    // the initializer; note that later code assumes this restriction.
8136    QualType BaseDeclType = VDecl->getType();
8137    if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
8138      BaseDeclType = Array->getElementType();
8139    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
8140                            diag::err_typecheck_decl_incomplete_type)) {
8141      RealDecl->setInvalidDecl();
8142      return;
8143    }
8144
8145    // The variable can not have an abstract class type.
8146    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
8147                               diag::err_abstract_type_in_decl,
8148                               AbstractVariableType))
8149      VDecl->setInvalidDecl();
8150  }
8151
8152  const VarDecl *Def;
8153  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
8154    Diag(VDecl->getLocation(), diag::err_redefinition)
8155      << VDecl->getDeclName();
8156    Diag(Def->getLocation(), diag::note_previous_definition);
8157    VDecl->setInvalidDecl();
8158    return;
8159  }
8160
8161  const VarDecl* PrevInit = 0;
8162  if (getLangOpts().CPlusPlus) {
8163    // C++ [class.static.data]p4
8164    //   If a static data member is of const integral or const
8165    //   enumeration type, its declaration in the class definition can
8166    //   specify a constant-initializer which shall be an integral
8167    //   constant expression (5.19). In that case, the member can appear
8168    //   in integral constant expressions. The member shall still be
8169    //   defined in a namespace scope if it is used in the program and the
8170    //   namespace scope definition shall not contain an initializer.
8171    //
8172    // We already performed a redefinition check above, but for static
8173    // data members we also need to check whether there was an in-class
8174    // declaration with an initializer.
8175    if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
8176      Diag(VDecl->getLocation(), diag::err_redefinition)
8177        << VDecl->getDeclName();
8178      Diag(PrevInit->getLocation(), diag::note_previous_definition);
8179      return;
8180    }
8181
8182    if (VDecl->hasLocalStorage())
8183      getCurFunction()->setHasBranchProtectedScope();
8184
8185    if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
8186      VDecl->setInvalidDecl();
8187      return;
8188    }
8189  }
8190
8191  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
8192  // a kernel function cannot be initialized."
8193  if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) {
8194    Diag(VDecl->getLocation(), diag::err_local_cant_init);
8195    VDecl->setInvalidDecl();
8196    return;
8197  }
8198
8199  // Get the decls type and save a reference for later, since
8200  // CheckInitializerTypes may change it.
8201  QualType DclT = VDecl->getType(), SavT = DclT;
8202
8203  // Expressions default to 'id' when we're in a debugger
8204  // and we are assigning it to a variable of Objective-C pointer type.
8205  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
8206      Init->getType() == Context.UnknownAnyTy) {
8207    ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
8208    if (Result.isInvalid()) {
8209      VDecl->setInvalidDecl();
8210      return;
8211    }
8212    Init = Result.take();
8213  }
8214
8215  // Perform the initialization.
8216  if (!VDecl->isInvalidDecl()) {
8217    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
8218    InitializationKind Kind
8219      = DirectInit ?
8220          CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(),
8221                                                           Init->getLocStart(),
8222                                                           Init->getLocEnd())
8223                        : InitializationKind::CreateDirectList(
8224                                                          VDecl->getLocation())
8225                   : InitializationKind::CreateCopy(VDecl->getLocation(),
8226                                                    Init->getLocStart());
8227
8228    MultiExprArg Args = Init;
8229    if (CXXDirectInit)
8230      Args = MultiExprArg(CXXDirectInit->getExprs(),
8231                          CXXDirectInit->getNumExprs());
8232
8233    InitializationSequence InitSeq(*this, Entity, Kind, Args);
8234    ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
8235    if (Result.isInvalid()) {
8236      VDecl->setInvalidDecl();
8237      return;
8238    }
8239
8240    Init = Result.takeAs<Expr>();
8241  }
8242
8243  // Check for self-references within variable initializers.
8244  // Variables declared within a function/method body (except for references)
8245  // are handled by a dataflow analysis.
8246  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
8247      VDecl->getType()->isReferenceType()) {
8248    CheckSelfReference(*this, RealDecl, Init, DirectInit);
8249  }
8250
8251  // If the type changed, it means we had an incomplete type that was
8252  // completed by the initializer. For example:
8253  //   int ary[] = { 1, 3, 5 };
8254  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
8255  if (!VDecl->isInvalidDecl() && (DclT != SavT))
8256    VDecl->setType(DclT);
8257
8258  if (!VDecl->isInvalidDecl()) {
8259    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
8260
8261    if (VDecl->hasAttr<BlocksAttr>())
8262      checkRetainCycles(VDecl, Init);
8263
8264    // It is safe to assign a weak reference into a strong variable.
8265    // Although this code can still have problems:
8266    //   id x = self.weakProp;
8267    //   id y = self.weakProp;
8268    // we do not warn to warn spuriously when 'x' and 'y' are on separate
8269    // paths through the function. This should be revisited if
8270    // -Wrepeated-use-of-weak is made flow-sensitive.
8271    if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
8272      DiagnosticsEngine::Level Level =
8273        Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8274                                 Init->getLocStart());
8275      if (Level != DiagnosticsEngine::Ignored)
8276        getCurFunction()->markSafeWeakUse(Init);
8277    }
8278  }
8279
8280  // The initialization is usually a full-expression.
8281  //
8282  // FIXME: If this is a braced initialization of an aggregate, it is not
8283  // an expression, and each individual field initializer is a separate
8284  // full-expression. For instance, in:
8285  //
8286  //   struct Temp { ~Temp(); };
8287  //   struct S { S(Temp); };
8288  //   struct T { S a, b; } t = { Temp(), Temp() }
8289  //
8290  // we should destroy the first Temp before constructing the second.
8291  ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
8292                                          false,
8293                                          VDecl->isConstexpr());
8294  if (Result.isInvalid()) {
8295    VDecl->setInvalidDecl();
8296    return;
8297  }
8298  Init = Result.take();
8299
8300  // Attach the initializer to the decl.
8301  VDecl->setInit(Init);
8302
8303  if (VDecl->isLocalVarDecl()) {
8304    // C99 6.7.8p4: All the expressions in an initializer for an object that has
8305    // static storage duration shall be constant expressions or string literals.
8306    // C++ does not have this restriction.
8307    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
8308      if (VDecl->getStorageClass() == SC_Static)
8309        CheckForConstantInitializer(Init, DclT);
8310      // C89 is stricter than C99 for non-static aggregate types.
8311      // C89 6.5.7p3: All the expressions [...] in an initializer list
8312      // for an object that has aggregate or union type shall be
8313      // constant expressions.
8314      else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
8315               isa<InitListExpr>(Init) &&
8316               !Init->isConstantInitializer(Context, false))
8317        Diag(Init->getExprLoc(),
8318             diag::ext_aggregate_init_not_constant)
8319          << Init->getSourceRange();
8320    }
8321  } else if (VDecl->isStaticDataMember() &&
8322             VDecl->getLexicalDeclContext()->isRecord()) {
8323    // This is an in-class initialization for a static data member, e.g.,
8324    //
8325    // struct S {
8326    //   static const int value = 17;
8327    // };
8328
8329    // C++ [class.mem]p4:
8330    //   A member-declarator can contain a constant-initializer only
8331    //   if it declares a static member (9.4) of const integral or
8332    //   const enumeration type, see 9.4.2.
8333    //
8334    // C++11 [class.static.data]p3:
8335    //   If a non-volatile const static data member is of integral or
8336    //   enumeration type, its declaration in the class definition can
8337    //   specify a brace-or-equal-initializer in which every initalizer-clause
8338    //   that is an assignment-expression is a constant expression. A static
8339    //   data member of literal type can be declared in the class definition
8340    //   with the constexpr specifier; if so, its declaration shall specify a
8341    //   brace-or-equal-initializer in which every initializer-clause that is
8342    //   an assignment-expression is a constant expression.
8343
8344    // Do nothing on dependent types.
8345    if (DclT->isDependentType()) {
8346
8347    // Allow any 'static constexpr' members, whether or not they are of literal
8348    // type. We separately check that every constexpr variable is of literal
8349    // type.
8350    } else if (VDecl->isConstexpr()) {
8351
8352    // Require constness.
8353    } else if (!DclT.isConstQualified()) {
8354      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
8355        << Init->getSourceRange();
8356      VDecl->setInvalidDecl();
8357
8358    // We allow integer constant expressions in all cases.
8359    } else if (DclT->isIntegralOrEnumerationType()) {
8360      // Check whether the expression is a constant expression.
8361      SourceLocation Loc;
8362      if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
8363        // In C++11, a non-constexpr const static data member with an
8364        // in-class initializer cannot be volatile.
8365        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
8366      else if (Init->isValueDependent())
8367        ; // Nothing to check.
8368      else if (Init->isIntegerConstantExpr(Context, &Loc))
8369        ; // Ok, it's an ICE!
8370      else if (Init->isEvaluatable(Context)) {
8371        // If we can constant fold the initializer through heroics, accept it,
8372        // but report this as a use of an extension for -pedantic.
8373        Diag(Loc, diag::ext_in_class_initializer_non_constant)
8374          << Init->getSourceRange();
8375      } else {
8376        // Otherwise, this is some crazy unknown case.  Report the issue at the
8377        // location provided by the isIntegerConstantExpr failed check.
8378        Diag(Loc, diag::err_in_class_initializer_non_constant)
8379          << Init->getSourceRange();
8380        VDecl->setInvalidDecl();
8381      }
8382
8383    // We allow foldable floating-point constants as an extension.
8384    } else if (DclT->isFloatingType()) { // also permits complex, which is ok
8385      // In C++98, this is a GNU extension. In C++11, it is not, but we support
8386      // it anyway and provide a fixit to add the 'constexpr'.
8387      if (getLangOpts().CPlusPlus11) {
8388        Diag(VDecl->getLocation(),
8389             diag::ext_in_class_initializer_float_type_cxx11)
8390            << DclT << Init->getSourceRange();
8391        Diag(VDecl->getLocStart(),
8392             diag::note_in_class_initializer_float_type_cxx11)
8393            << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8394      } else {
8395        Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
8396          << DclT << Init->getSourceRange();
8397
8398        if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
8399          Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
8400            << Init->getSourceRange();
8401          VDecl->setInvalidDecl();
8402        }
8403      }
8404
8405    // Suggest adding 'constexpr' in C++11 for literal types.
8406    } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
8407      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
8408        << DclT << Init->getSourceRange()
8409        << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
8410      VDecl->setConstexpr(true);
8411
8412    } else {
8413      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
8414        << DclT << Init->getSourceRange();
8415      VDecl->setInvalidDecl();
8416    }
8417  } else if (VDecl->isFileVarDecl()) {
8418    if (VDecl->getStorageClass() == SC_Extern &&
8419        (!getLangOpts().CPlusPlus ||
8420         !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
8421           VDecl->isExternC())) &&
8422        !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
8423      Diag(VDecl->getLocation(), diag::warn_extern_init);
8424
8425    // C99 6.7.8p4. All file scoped initializers need to be constant.
8426    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
8427      CheckForConstantInitializer(Init, DclT);
8428    else if (VDecl->getTLSKind() == VarDecl::TLS_Static &&
8429             !VDecl->isInvalidDecl() && !DclT->isDependentType() &&
8430             !Init->isValueDependent() && !VDecl->isConstexpr() &&
8431             !Init->isConstantInitializer(
8432                 Context, VDecl->getType()->isReferenceType())) {
8433      // GNU C++98 edits for __thread, [basic.start.init]p4:
8434      //   An object of thread storage duration shall not require dynamic
8435      //   initialization.
8436      // FIXME: Need strict checking here.
8437      Diag(VDecl->getLocation(), diag::err_thread_dynamic_init);
8438      if (getLangOpts().CPlusPlus11)
8439        Diag(VDecl->getLocation(), diag::note_use_thread_local);
8440    }
8441  }
8442
8443  // We will represent direct-initialization similarly to copy-initialization:
8444  //    int x(1);  -as-> int x = 1;
8445  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
8446  //
8447  // Clients that want to distinguish between the two forms, can check for
8448  // direct initializer using VarDecl::getInitStyle().
8449  // A major benefit is that clients that don't particularly care about which
8450  // exactly form was it (like the CodeGen) can handle both cases without
8451  // special case code.
8452
8453  // C++ 8.5p11:
8454  // The form of initialization (using parentheses or '=') is generally
8455  // insignificant, but does matter when the entity being initialized has a
8456  // class type.
8457  if (CXXDirectInit) {
8458    assert(DirectInit && "Call-style initializer must be direct init.");
8459    VDecl->setInitStyle(VarDecl::CallInit);
8460  } else if (DirectInit) {
8461    // This must be list-initialization. No other way is direct-initialization.
8462    VDecl->setInitStyle(VarDecl::ListInit);
8463  }
8464
8465  CheckCompleteVariableDeclaration(VDecl);
8466}
8467
8468/// ActOnInitializerError - Given that there was an error parsing an
8469/// initializer for the given declaration, try to return to some form
8470/// of sanity.
8471void Sema::ActOnInitializerError(Decl *D) {
8472  // Our main concern here is re-establishing invariants like "a
8473  // variable's type is either dependent or complete".
8474  if (!D || D->isInvalidDecl()) return;
8475
8476  VarDecl *VD = dyn_cast<VarDecl>(D);
8477  if (!VD) return;
8478
8479  // Auto types are meaningless if we can't make sense of the initializer.
8480  if (ParsingInitForAutoVars.count(D)) {
8481    D->setInvalidDecl();
8482    return;
8483  }
8484
8485  QualType Ty = VD->getType();
8486  if (Ty->isDependentType()) return;
8487
8488  // Require a complete type.
8489  if (RequireCompleteType(VD->getLocation(),
8490                          Context.getBaseElementType(Ty),
8491                          diag::err_typecheck_decl_incomplete_type)) {
8492    VD->setInvalidDecl();
8493    return;
8494  }
8495
8496  // Require an abstract type.
8497  if (RequireNonAbstractType(VD->getLocation(), Ty,
8498                             diag::err_abstract_type_in_decl,
8499                             AbstractVariableType)) {
8500    VD->setInvalidDecl();
8501    return;
8502  }
8503
8504  // Don't bother complaining about constructors or destructors,
8505  // though.
8506}
8507
8508void Sema::ActOnUninitializedDecl(Decl *RealDecl,
8509                                  bool TypeMayContainAuto) {
8510  // If there is no declaration, there was an error parsing it. Just ignore it.
8511  if (RealDecl == 0)
8512    return;
8513
8514  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
8515    QualType Type = Var->getType();
8516
8517    // C++11 [dcl.spec.auto]p3
8518    if (TypeMayContainAuto && Type->getContainedAutoType()) {
8519      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
8520        << Var->getDeclName() << Type;
8521      Var->setInvalidDecl();
8522      return;
8523    }
8524
8525    // C++11 [class.static.data]p3: A static data member can be declared with
8526    // the constexpr specifier; if so, its declaration shall specify
8527    // a brace-or-equal-initializer.
8528    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
8529    // the definition of a variable [...] or the declaration of a static data
8530    // member.
8531    if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
8532      if (Var->isStaticDataMember())
8533        Diag(Var->getLocation(),
8534             diag::err_constexpr_static_mem_var_requires_init)
8535          << Var->getDeclName();
8536      else
8537        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
8538      Var->setInvalidDecl();
8539      return;
8540    }
8541
8542    switch (Var->isThisDeclarationADefinition()) {
8543    case VarDecl::Definition:
8544      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
8545        break;
8546
8547      // We have an out-of-line definition of a static data member
8548      // that has an in-class initializer, so we type-check this like
8549      // a declaration.
8550      //
8551      // Fall through
8552
8553    case VarDecl::DeclarationOnly:
8554      // It's only a declaration.
8555
8556      // Block scope. C99 6.7p7: If an identifier for an object is
8557      // declared with no linkage (C99 6.2.2p6), the type for the
8558      // object shall be complete.
8559      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
8560          !Var->hasLinkage() && !Var->isInvalidDecl() &&
8561          RequireCompleteType(Var->getLocation(), Type,
8562                              diag::err_typecheck_decl_incomplete_type))
8563        Var->setInvalidDecl();
8564
8565      // Make sure that the type is not abstract.
8566      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8567          RequireNonAbstractType(Var->getLocation(), Type,
8568                                 diag::err_abstract_type_in_decl,
8569                                 AbstractVariableType))
8570        Var->setInvalidDecl();
8571      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
8572          Var->getStorageClass() == SC_PrivateExtern) {
8573        Diag(Var->getLocation(), diag::warn_private_extern);
8574        Diag(Var->getLocation(), diag::note_private_extern);
8575      }
8576
8577      return;
8578
8579    case VarDecl::TentativeDefinition:
8580      // File scope. C99 6.9.2p2: A declaration of an identifier for an
8581      // object that has file scope without an initializer, and without a
8582      // storage-class specifier or with the storage-class specifier "static",
8583      // constitutes a tentative definition. Note: A tentative definition with
8584      // external linkage is valid (C99 6.2.2p5).
8585      if (!Var->isInvalidDecl()) {
8586        if (const IncompleteArrayType *ArrayT
8587                                    = Context.getAsIncompleteArrayType(Type)) {
8588          if (RequireCompleteType(Var->getLocation(),
8589                                  ArrayT->getElementType(),
8590                                  diag::err_illegal_decl_array_incomplete_type))
8591            Var->setInvalidDecl();
8592        } else if (Var->getStorageClass() == SC_Static) {
8593          // C99 6.9.2p3: If the declaration of an identifier for an object is
8594          // a tentative definition and has internal linkage (C99 6.2.2p3), the
8595          // declared type shall not be an incomplete type.
8596          // NOTE: code such as the following
8597          //     static struct s;
8598          //     struct s { int a; };
8599          // is accepted by gcc. Hence here we issue a warning instead of
8600          // an error and we do not invalidate the static declaration.
8601          // NOTE: to avoid multiple warnings, only check the first declaration.
8602          if (Var->isFirstDecl())
8603            RequireCompleteType(Var->getLocation(), Type,
8604                                diag::ext_typecheck_decl_incomplete_type);
8605        }
8606      }
8607
8608      // Record the tentative definition; we're done.
8609      if (!Var->isInvalidDecl())
8610        TentativeDefinitions.push_back(Var);
8611      return;
8612    }
8613
8614    // Provide a specific diagnostic for uninitialized variable
8615    // definitions with incomplete array type.
8616    if (Type->isIncompleteArrayType()) {
8617      Diag(Var->getLocation(),
8618           diag::err_typecheck_incomplete_array_needs_initializer);
8619      Var->setInvalidDecl();
8620      return;
8621    }
8622
8623    // Provide a specific diagnostic for uninitialized variable
8624    // definitions with reference type.
8625    if (Type->isReferenceType()) {
8626      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
8627        << Var->getDeclName()
8628        << SourceRange(Var->getLocation(), Var->getLocation());
8629      Var->setInvalidDecl();
8630      return;
8631    }
8632
8633    // Do not attempt to type-check the default initializer for a
8634    // variable with dependent type.
8635    if (Type->isDependentType())
8636      return;
8637
8638    if (Var->isInvalidDecl())
8639      return;
8640
8641    if (RequireCompleteType(Var->getLocation(),
8642                            Context.getBaseElementType(Type),
8643                            diag::err_typecheck_decl_incomplete_type)) {
8644      Var->setInvalidDecl();
8645      return;
8646    }
8647
8648    // The variable can not have an abstract class type.
8649    if (RequireNonAbstractType(Var->getLocation(), Type,
8650                               diag::err_abstract_type_in_decl,
8651                               AbstractVariableType)) {
8652      Var->setInvalidDecl();
8653      return;
8654    }
8655
8656    // Check for jumps past the implicit initializer.  C++0x
8657    // clarifies that this applies to a "variable with automatic
8658    // storage duration", not a "local variable".
8659    // C++11 [stmt.dcl]p3
8660    //   A program that jumps from a point where a variable with automatic
8661    //   storage duration is not in scope to a point where it is in scope is
8662    //   ill-formed unless the variable has scalar type, class type with a
8663    //   trivial default constructor and a trivial destructor, a cv-qualified
8664    //   version of one of these types, or an array of one of the preceding
8665    //   types and is declared without an initializer.
8666    if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
8667      if (const RecordType *Record
8668            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
8669        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
8670        // Mark the function for further checking even if the looser rules of
8671        // C++11 do not require such checks, so that we can diagnose
8672        // incompatibilities with C++98.
8673        if (!CXXRecord->isPOD())
8674          getCurFunction()->setHasBranchProtectedScope();
8675      }
8676    }
8677
8678    // C++03 [dcl.init]p9:
8679    //   If no initializer is specified for an object, and the
8680    //   object is of (possibly cv-qualified) non-POD class type (or
8681    //   array thereof), the object shall be default-initialized; if
8682    //   the object is of const-qualified type, the underlying class
8683    //   type shall have a user-declared default
8684    //   constructor. Otherwise, if no initializer is specified for
8685    //   a non- static object, the object and its subobjects, if
8686    //   any, have an indeterminate initial value); if the object
8687    //   or any of its subobjects are of const-qualified type, the
8688    //   program is ill-formed.
8689    // C++0x [dcl.init]p11:
8690    //   If no initializer is specified for an object, the object is
8691    //   default-initialized; [...].
8692    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
8693    InitializationKind Kind
8694      = InitializationKind::CreateDefault(Var->getLocation());
8695
8696    InitializationSequence InitSeq(*this, Entity, Kind, None);
8697    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
8698    if (Init.isInvalid())
8699      Var->setInvalidDecl();
8700    else if (Init.get()) {
8701      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
8702      // This is important for template substitution.
8703      Var->setInitStyle(VarDecl::CallInit);
8704    }
8705
8706    CheckCompleteVariableDeclaration(Var);
8707  }
8708}
8709
8710void Sema::ActOnCXXForRangeDecl(Decl *D) {
8711  VarDecl *VD = dyn_cast<VarDecl>(D);
8712  if (!VD) {
8713    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
8714    D->setInvalidDecl();
8715    return;
8716  }
8717
8718  VD->setCXXForRangeDecl(true);
8719
8720  // for-range-declaration cannot be given a storage class specifier.
8721  int Error = -1;
8722  switch (VD->getStorageClass()) {
8723  case SC_None:
8724    break;
8725  case SC_Extern:
8726    Error = 0;
8727    break;
8728  case SC_Static:
8729    Error = 1;
8730    break;
8731  case SC_PrivateExtern:
8732    Error = 2;
8733    break;
8734  case SC_Auto:
8735    Error = 3;
8736    break;
8737  case SC_Register:
8738    Error = 4;
8739    break;
8740  case SC_OpenCLWorkGroupLocal:
8741    llvm_unreachable("Unexpected storage class");
8742  }
8743  if (VD->isConstexpr())
8744    Error = 5;
8745  if (Error != -1) {
8746    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
8747      << VD->getDeclName() << Error;
8748    D->setInvalidDecl();
8749  }
8750}
8751
8752void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
8753  if (var->isInvalidDecl()) return;
8754
8755  // In ARC, don't allow jumps past the implicit initialization of a
8756  // local retaining variable.
8757  if (getLangOpts().ObjCAutoRefCount &&
8758      var->hasLocalStorage()) {
8759    switch (var->getType().getObjCLifetime()) {
8760    case Qualifiers::OCL_None:
8761    case Qualifiers::OCL_ExplicitNone:
8762    case Qualifiers::OCL_Autoreleasing:
8763      break;
8764
8765    case Qualifiers::OCL_Weak:
8766    case Qualifiers::OCL_Strong:
8767      getCurFunction()->setHasBranchProtectedScope();
8768      break;
8769    }
8770  }
8771
8772  if (var->isThisDeclarationADefinition() &&
8773      var->isExternallyVisible() && var->hasLinkage() &&
8774      getDiagnostics().getDiagnosticLevel(
8775                       diag::warn_missing_variable_declarations,
8776                       var->getLocation())) {
8777    // Find a previous declaration that's not a definition.
8778    VarDecl *prev = var->getPreviousDecl();
8779    while (prev && prev->isThisDeclarationADefinition())
8780      prev = prev->getPreviousDecl();
8781
8782    if (!prev)
8783      Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
8784  }
8785
8786  if (var->getTLSKind() == VarDecl::TLS_Static &&
8787      var->getType().isDestructedType()) {
8788    // GNU C++98 edits for __thread, [basic.start.term]p3:
8789    //   The type of an object with thread storage duration shall not
8790    //   have a non-trivial destructor.
8791    Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
8792    if (getLangOpts().CPlusPlus11)
8793      Diag(var->getLocation(), diag::note_use_thread_local);
8794  }
8795
8796  // All the following checks are C++ only.
8797  if (!getLangOpts().CPlusPlus) return;
8798
8799  QualType type = var->getType();
8800  if (type->isDependentType()) return;
8801
8802  // __block variables might require us to capture a copy-initializer.
8803  if (var->hasAttr<BlocksAttr>()) {
8804    // It's currently invalid to ever have a __block variable with an
8805    // array type; should we diagnose that here?
8806
8807    // Regardless, we don't want to ignore array nesting when
8808    // constructing this copy.
8809    if (type->isStructureOrClassType()) {
8810      EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
8811      SourceLocation poi = var->getLocation();
8812      Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
8813      ExprResult result
8814        = PerformMoveOrCopyInitialization(
8815            InitializedEntity::InitializeBlock(poi, type, false),
8816            var, var->getType(), varRef, /*AllowNRVO=*/true);
8817      if (!result.isInvalid()) {
8818        result = MaybeCreateExprWithCleanups(result);
8819        Expr *init = result.takeAs<Expr>();
8820        Context.setBlockVarCopyInits(var, init);
8821      }
8822    }
8823  }
8824
8825  Expr *Init = var->getInit();
8826  bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal();
8827  QualType baseType = Context.getBaseElementType(type);
8828
8829  if (!var->getDeclContext()->isDependentContext() &&
8830      Init && !Init->isValueDependent()) {
8831    if (IsGlobal && !var->isConstexpr() &&
8832        getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor,
8833                                            var->getLocation())
8834          != DiagnosticsEngine::Ignored) {
8835      // Warn about globals which don't have a constant initializer.  Don't
8836      // warn about globals with a non-trivial destructor because we already
8837      // warned about them.
8838      CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
8839      if (!(RD && !RD->hasTrivialDestructor()) &&
8840          !Init->isConstantInitializer(Context, baseType->isReferenceType()))
8841        Diag(var->getLocation(), diag::warn_global_constructor)
8842          << Init->getSourceRange();
8843    }
8844
8845    if (var->isConstexpr()) {
8846      SmallVector<PartialDiagnosticAt, 8> Notes;
8847      if (!var->evaluateValue(Notes) || !var->isInitICE()) {
8848        SourceLocation DiagLoc = var->getLocation();
8849        // If the note doesn't add any useful information other than a source
8850        // location, fold it into the primary diagnostic.
8851        if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
8852              diag::note_invalid_subexpr_in_const_expr) {
8853          DiagLoc = Notes[0].first;
8854          Notes.clear();
8855        }
8856        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
8857          << var << Init->getSourceRange();
8858        for (unsigned I = 0, N = Notes.size(); I != N; ++I)
8859          Diag(Notes[I].first, Notes[I].second);
8860      }
8861    } else if (var->isUsableInConstantExpressions(Context)) {
8862      // Check whether the initializer of a const variable of integral or
8863      // enumeration type is an ICE now, since we can't tell whether it was
8864      // initialized by a constant expression if we check later.
8865      var->checkInitIsICE();
8866    }
8867  }
8868
8869  // Require the destructor.
8870  if (const RecordType *recordType = baseType->getAs<RecordType>())
8871    FinalizeVarWithDestructor(var, recordType);
8872}
8873
8874/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
8875/// any semantic actions necessary after any initializer has been attached.
8876void
8877Sema::FinalizeDeclaration(Decl *ThisDecl) {
8878  // Note that we are no longer parsing the initializer for this declaration.
8879  ParsingInitForAutoVars.erase(ThisDecl);
8880
8881  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
8882  if (!VD)
8883    return;
8884
8885  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
8886    if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
8887      Diag(Attr->getLocation(), diag::warn_attribute_ignored) << "used";
8888      VD->dropAttr<UsedAttr>();
8889    }
8890  }
8891
8892  if (!VD->isInvalidDecl() &&
8893      VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) {
8894    if (const VarDecl *Def = VD->getDefinition()) {
8895      if (Def->hasAttr<AliasAttr>()) {
8896        Diag(VD->getLocation(), diag::err_tentative_after_alias)
8897            << VD->getDeclName();
8898        Diag(Def->getLocation(), diag::note_previous_definition);
8899        VD->setInvalidDecl();
8900      }
8901    }
8902  }
8903
8904  const DeclContext *DC = VD->getDeclContext();
8905  // If there's a #pragma GCC visibility in scope, and this isn't a class
8906  // member, set the visibility of this variable.
8907  if (!DC->isRecord() && VD->isExternallyVisible())
8908    AddPushedVisibilityAttribute(VD);
8909
8910  if (VD->isFileVarDecl())
8911    MarkUnusedFileScopedDecl(VD);
8912
8913  // Now we have parsed the initializer and can update the table of magic
8914  // tag values.
8915  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
8916      !VD->getType()->isIntegralOrEnumerationType())
8917    return;
8918
8919  for (specific_attr_iterator<TypeTagForDatatypeAttr>
8920         I = ThisDecl->specific_attr_begin<TypeTagForDatatypeAttr>(),
8921         E = ThisDecl->specific_attr_end<TypeTagForDatatypeAttr>();
8922       I != E; ++I) {
8923    const Expr *MagicValueExpr = VD->getInit();
8924    if (!MagicValueExpr) {
8925      continue;
8926    }
8927    llvm::APSInt MagicValueInt;
8928    if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
8929      Diag(I->getRange().getBegin(),
8930           diag::err_type_tag_for_datatype_not_ice)
8931        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8932      continue;
8933    }
8934    if (MagicValueInt.getActiveBits() > 64) {
8935      Diag(I->getRange().getBegin(),
8936           diag::err_type_tag_for_datatype_too_large)
8937        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
8938      continue;
8939    }
8940    uint64_t MagicValue = MagicValueInt.getZExtValue();
8941    RegisterTypeTagForDatatype(I->getArgumentKind(),
8942                               MagicValue,
8943                               I->getMatchingCType(),
8944                               I->getLayoutCompatible(),
8945                               I->getMustBeNull());
8946  }
8947}
8948
8949Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
8950                                                   ArrayRef<Decl *> Group) {
8951  SmallVector<Decl*, 8> Decls;
8952
8953  if (DS.isTypeSpecOwned())
8954    Decls.push_back(DS.getRepAsDecl());
8955
8956  DeclaratorDecl *FirstDeclaratorInGroup = 0;
8957  for (unsigned i = 0, e = Group.size(); i != e; ++i)
8958    if (Decl *D = Group[i]) {
8959      if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
8960        if (!FirstDeclaratorInGroup)
8961          FirstDeclaratorInGroup = DD;
8962      Decls.push_back(D);
8963    }
8964
8965  if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
8966    if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
8967      HandleTagNumbering(*this, Tag);
8968      if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl())
8969        Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup);
8970    }
8971  }
8972
8973  return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
8974}
8975
8976/// BuildDeclaratorGroup - convert a list of declarations into a declaration
8977/// group, performing any necessary semantic checking.
8978Sema::DeclGroupPtrTy
8979Sema::BuildDeclaratorGroup(llvm::MutableArrayRef<Decl *> Group,
8980                           bool TypeMayContainAuto) {
8981  // C++0x [dcl.spec.auto]p7:
8982  //   If the type deduced for the template parameter U is not the same in each
8983  //   deduction, the program is ill-formed.
8984  // FIXME: When initializer-list support is added, a distinction is needed
8985  // between the deduced type U and the deduced type which 'auto' stands for.
8986  //   auto a = 0, b = { 1, 2, 3 };
8987  // is legal because the deduced type U is 'int' in both cases.
8988  if (TypeMayContainAuto && Group.size() > 1) {
8989    QualType Deduced;
8990    CanQualType DeducedCanon;
8991    VarDecl *DeducedDecl = 0;
8992    for (unsigned i = 0, e = Group.size(); i != e; ++i) {
8993      if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
8994        AutoType *AT = D->getType()->getContainedAutoType();
8995        // Don't reissue diagnostics when instantiating a template.
8996        if (AT && D->isInvalidDecl())
8997          break;
8998        QualType U = AT ? AT->getDeducedType() : QualType();
8999        if (!U.isNull()) {
9000          CanQualType UCanon = Context.getCanonicalType(U);
9001          if (Deduced.isNull()) {
9002            Deduced = U;
9003            DeducedCanon = UCanon;
9004            DeducedDecl = D;
9005          } else if (DeducedCanon != UCanon) {
9006            Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
9007                 diag::err_auto_different_deductions)
9008              << (AT->isDecltypeAuto() ? 1 : 0)
9009              << Deduced << DeducedDecl->getDeclName()
9010              << U << D->getDeclName()
9011              << DeducedDecl->getInit()->getSourceRange()
9012              << D->getInit()->getSourceRange();
9013            D->setInvalidDecl();
9014            break;
9015          }
9016        }
9017      }
9018    }
9019  }
9020
9021  ActOnDocumentableDecls(Group);
9022
9023  return DeclGroupPtrTy::make(
9024      DeclGroupRef::Create(Context, Group.data(), Group.size()));
9025}
9026
9027void Sema::ActOnDocumentableDecl(Decl *D) {
9028  ActOnDocumentableDecls(D);
9029}
9030
9031void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
9032  // Don't parse the comment if Doxygen diagnostics are ignored.
9033  if (Group.empty() || !Group[0])
9034   return;
9035
9036  if (Diags.getDiagnosticLevel(diag::warn_doc_param_not_found,
9037                               Group[0]->getLocation())
9038        == DiagnosticsEngine::Ignored)
9039    return;
9040
9041  if (Group.size() >= 2) {
9042    // This is a decl group.  Normally it will contain only declarations
9043    // produced from declarator list.  But in case we have any definitions or
9044    // additional declaration references:
9045    //   'typedef struct S {} S;'
9046    //   'typedef struct S *S;'
9047    //   'struct S *pS;'
9048    // FinalizeDeclaratorGroup adds these as separate declarations.
9049    Decl *MaybeTagDecl = Group[0];
9050    if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
9051      Group = Group.slice(1);
9052    }
9053  }
9054
9055  // See if there are any new comments that are not attached to a decl.
9056  ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
9057  if (!Comments.empty() &&
9058      !Comments.back()->isAttached()) {
9059    // There is at least one comment that not attached to a decl.
9060    // Maybe it should be attached to one of these decls?
9061    //
9062    // Note that this way we pick up not only comments that precede the
9063    // declaration, but also comments that *follow* the declaration -- thanks to
9064    // the lookahead in the lexer: we've consumed the semicolon and looked
9065    // ahead through comments.
9066    for (unsigned i = 0, e = Group.size(); i != e; ++i)
9067      Context.getCommentForDecl(Group[i], &PP);
9068  }
9069}
9070
9071/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
9072/// to introduce parameters into function prototype scope.
9073Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
9074  const DeclSpec &DS = D.getDeclSpec();
9075
9076  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
9077
9078  // C++03 [dcl.stc]p2 also permits 'auto'.
9079  VarDecl::StorageClass StorageClass = SC_None;
9080  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
9081    StorageClass = SC_Register;
9082  } else if (getLangOpts().CPlusPlus &&
9083             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
9084    StorageClass = SC_Auto;
9085  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
9086    Diag(DS.getStorageClassSpecLoc(),
9087         diag::err_invalid_storage_class_in_func_decl);
9088    D.getMutableDeclSpec().ClearStorageClassSpecs();
9089  }
9090
9091  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
9092    Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
9093      << DeclSpec::getSpecifierName(TSCS);
9094  if (DS.isConstexprSpecified())
9095    Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
9096      << 0;
9097
9098  DiagnoseFunctionSpecifiers(DS);
9099
9100  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
9101  QualType parmDeclType = TInfo->getType();
9102
9103  if (getLangOpts().CPlusPlus) {
9104    // Check that there are no default arguments inside the type of this
9105    // parameter.
9106    CheckExtraCXXDefaultArguments(D);
9107
9108    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
9109    if (D.getCXXScopeSpec().isSet()) {
9110      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
9111        << D.getCXXScopeSpec().getRange();
9112      D.getCXXScopeSpec().clear();
9113    }
9114  }
9115
9116  // Ensure we have a valid name
9117  IdentifierInfo *II = 0;
9118  if (D.hasName()) {
9119    II = D.getIdentifier();
9120    if (!II) {
9121      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
9122        << GetNameForDeclarator(D).getName().getAsString();
9123      D.setInvalidType(true);
9124    }
9125  }
9126
9127  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
9128  if (II) {
9129    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
9130                   ForRedeclaration);
9131    LookupName(R, S);
9132    if (R.isSingleResult()) {
9133      NamedDecl *PrevDecl = R.getFoundDecl();
9134      if (PrevDecl->isTemplateParameter()) {
9135        // Maybe we will complain about the shadowed template parameter.
9136        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
9137        // Just pretend that we didn't see the previous declaration.
9138        PrevDecl = 0;
9139      } else if (S->isDeclScope(PrevDecl)) {
9140        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
9141        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
9142
9143        // Recover by removing the name
9144        II = 0;
9145        D.SetIdentifier(0, D.getIdentifierLoc());
9146        D.setInvalidType(true);
9147      }
9148    }
9149  }
9150
9151  // Temporarily put parameter variables in the translation unit, not
9152  // the enclosing context.  This prevents them from accidentally
9153  // looking like class members in C++.
9154  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
9155                                    D.getLocStart(),
9156                                    D.getIdentifierLoc(), II,
9157                                    parmDeclType, TInfo,
9158                                    StorageClass);
9159
9160  if (D.isInvalidType())
9161    New->setInvalidDecl();
9162
9163  assert(S->isFunctionPrototypeScope());
9164  assert(S->getFunctionPrototypeDepth() >= 1);
9165  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
9166                    S->getNextFunctionPrototypeIndex());
9167
9168  // Add the parameter declaration into this scope.
9169  S->AddDecl(New);
9170  if (II)
9171    IdResolver.AddDecl(New);
9172
9173  ProcessDeclAttributes(S, New, D);
9174
9175  if (D.getDeclSpec().isModulePrivateSpecified())
9176    Diag(New->getLocation(), diag::err_module_private_local)
9177      << 1 << New->getDeclName()
9178      << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
9179      << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
9180
9181  if (New->hasAttr<BlocksAttr>()) {
9182    Diag(New->getLocation(), diag::err_block_on_nonlocal);
9183  }
9184  return New;
9185}
9186
9187/// \brief Synthesizes a variable for a parameter arising from a
9188/// typedef.
9189ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
9190                                              SourceLocation Loc,
9191                                              QualType T) {
9192  /* FIXME: setting StartLoc == Loc.
9193     Would it be worth to modify callers so as to provide proper source
9194     location for the unnamed parameters, embedding the parameter's type? */
9195  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0,
9196                                T, Context.getTrivialTypeSourceInfo(T, Loc),
9197                                           SC_None, 0);
9198  Param->setImplicit();
9199  return Param;
9200}
9201
9202void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
9203                                    ParmVarDecl * const *ParamEnd) {
9204  // Don't diagnose unused-parameter errors in template instantiations; we
9205  // will already have done so in the template itself.
9206  if (!ActiveTemplateInstantiations.empty())
9207    return;
9208
9209  for (; Param != ParamEnd; ++Param) {
9210    if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
9211        !(*Param)->hasAttr<UnusedAttr>()) {
9212      Diag((*Param)->getLocation(), diag::warn_unused_parameter)
9213        << (*Param)->getDeclName();
9214    }
9215  }
9216}
9217
9218void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
9219                                                  ParmVarDecl * const *ParamEnd,
9220                                                  QualType ReturnTy,
9221                                                  NamedDecl *D) {
9222  if (LangOpts.NumLargeByValueCopy == 0) // No check.
9223    return;
9224
9225  // Warn if the return value is pass-by-value and larger than the specified
9226  // threshold.
9227  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
9228    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
9229    if (Size > LangOpts.NumLargeByValueCopy)
9230      Diag(D->getLocation(), diag::warn_return_value_size)
9231          << D->getDeclName() << Size;
9232  }
9233
9234  // Warn if any parameter is pass-by-value and larger than the specified
9235  // threshold.
9236  for (; Param != ParamEnd; ++Param) {
9237    QualType T = (*Param)->getType();
9238    if (T->isDependentType() || !T.isPODType(Context))
9239      continue;
9240    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
9241    if (Size > LangOpts.NumLargeByValueCopy)
9242      Diag((*Param)->getLocation(), diag::warn_parameter_size)
9243          << (*Param)->getDeclName() << Size;
9244  }
9245}
9246
9247ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
9248                                  SourceLocation NameLoc, IdentifierInfo *Name,
9249                                  QualType T, TypeSourceInfo *TSInfo,
9250                                  VarDecl::StorageClass StorageClass) {
9251  // In ARC, infer a lifetime qualifier for appropriate parameter types.
9252  if (getLangOpts().ObjCAutoRefCount &&
9253      T.getObjCLifetime() == Qualifiers::OCL_None &&
9254      T->isObjCLifetimeType()) {
9255
9256    Qualifiers::ObjCLifetime lifetime;
9257
9258    // Special cases for arrays:
9259    //   - if it's const, use __unsafe_unretained
9260    //   - otherwise, it's an error
9261    if (T->isArrayType()) {
9262      if (!T.isConstQualified()) {
9263        DelayedDiagnostics.add(
9264            sema::DelayedDiagnostic::makeForbiddenType(
9265            NameLoc, diag::err_arc_array_param_no_ownership, T, false));
9266      }
9267      lifetime = Qualifiers::OCL_ExplicitNone;
9268    } else {
9269      lifetime = T->getObjCARCImplicitLifetime();
9270    }
9271    T = Context.getLifetimeQualifiedType(T, lifetime);
9272  }
9273
9274  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
9275                                         Context.getAdjustedParameterType(T),
9276                                         TSInfo,
9277                                         StorageClass, 0);
9278
9279  // Parameters can not be abstract class types.
9280  // For record types, this is done by the AbstractClassUsageDiagnoser once
9281  // the class has been completely parsed.
9282  if (!CurContext->isRecord() &&
9283      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
9284                             AbstractParamType))
9285    New->setInvalidDecl();
9286
9287  // Parameter declarators cannot be interface types. All ObjC objects are
9288  // passed by reference.
9289  if (T->isObjCObjectType()) {
9290    SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
9291    Diag(NameLoc,
9292         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
9293      << FixItHint::CreateInsertion(TypeEndLoc, "*");
9294    T = Context.getObjCObjectPointerType(T);
9295    New->setType(T);
9296  }
9297
9298  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
9299  // duration shall not be qualified by an address-space qualifier."
9300  // Since all parameters have automatic store duration, they can not have
9301  // an address space.
9302  if (T.getAddressSpace() != 0) {
9303    Diag(NameLoc, diag::err_arg_with_address_space);
9304    New->setInvalidDecl();
9305  }
9306
9307  return New;
9308}
9309
9310void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
9311                                           SourceLocation LocAfterDecls) {
9312  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
9313
9314  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
9315  // for a K&R function.
9316  if (!FTI.hasPrototype) {
9317    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
9318      --i;
9319      if (FTI.ArgInfo[i].Param == 0) {
9320        SmallString<256> Code;
9321        llvm::raw_svector_ostream(Code) << "  int "
9322                                        << FTI.ArgInfo[i].Ident->getName()
9323                                        << ";\n";
9324        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
9325          << FTI.ArgInfo[i].Ident
9326          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
9327
9328        // Implicitly declare the argument as type 'int' for lack of a better
9329        // type.
9330        AttributeFactory attrs;
9331        DeclSpec DS(attrs);
9332        const char* PrevSpec; // unused
9333        unsigned DiagID; // unused
9334        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
9335                           PrevSpec, DiagID);
9336        // Use the identifier location for the type source range.
9337        DS.SetRangeStart(FTI.ArgInfo[i].IdentLoc);
9338        DS.SetRangeEnd(FTI.ArgInfo[i].IdentLoc);
9339        Declarator ParamD(DS, Declarator::KNRTypeListContext);
9340        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
9341        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
9342      }
9343    }
9344  }
9345}
9346
9347Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
9348  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
9349  assert(D.isFunctionDeclarator() && "Not a function declarator!");
9350  Scope *ParentScope = FnBodyScope->getParent();
9351
9352  D.setFunctionDefinitionKind(FDK_Definition);
9353  Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg());
9354  return ActOnStartOfFunctionDef(FnBodyScope, DP);
9355}
9356
9357static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
9358                             const FunctionDecl*& PossibleZeroParamPrototype) {
9359  // Don't warn about invalid declarations.
9360  if (FD->isInvalidDecl())
9361    return false;
9362
9363  // Or declarations that aren't global.
9364  if (!FD->isGlobal())
9365    return false;
9366
9367  // Don't warn about C++ member functions.
9368  if (isa<CXXMethodDecl>(FD))
9369    return false;
9370
9371  // Don't warn about 'main'.
9372  if (FD->isMain())
9373    return false;
9374
9375  // Don't warn about inline functions.
9376  if (FD->isInlined())
9377    return false;
9378
9379  // Don't warn about function templates.
9380  if (FD->getDescribedFunctionTemplate())
9381    return false;
9382
9383  // Don't warn about function template specializations.
9384  if (FD->isFunctionTemplateSpecialization())
9385    return false;
9386
9387  // Don't warn for OpenCL kernels.
9388  if (FD->hasAttr<OpenCLKernelAttr>())
9389    return false;
9390
9391  bool MissingPrototype = true;
9392  for (const FunctionDecl *Prev = FD->getPreviousDecl();
9393       Prev; Prev = Prev->getPreviousDecl()) {
9394    // Ignore any declarations that occur in function or method
9395    // scope, because they aren't visible from the header.
9396    if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
9397      continue;
9398
9399    MissingPrototype = !Prev->getType()->isFunctionProtoType();
9400    if (FD->getNumParams() == 0)
9401      PossibleZeroParamPrototype = Prev;
9402    break;
9403  }
9404
9405  return MissingPrototype;
9406}
9407
9408void
9409Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
9410                                   const FunctionDecl *EffectiveDefinition) {
9411  // Don't complain if we're in GNU89 mode and the previous definition
9412  // was an extern inline function.
9413  const FunctionDecl *Definition = EffectiveDefinition;
9414  if (!Definition)
9415    if (!FD->isDefined(Definition))
9416      return;
9417
9418  if (canRedefineFunction(Definition, getLangOpts()))
9419    return;
9420
9421  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
9422      Definition->getStorageClass() == SC_Extern)
9423    Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
9424        << FD->getDeclName() << getLangOpts().CPlusPlus;
9425  else
9426    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
9427
9428  Diag(Definition->getLocation(), diag::note_previous_definition);
9429  FD->setInvalidDecl();
9430}
9431static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
9432                                   Sema &S) {
9433  CXXRecordDecl *const LambdaClass = CallOperator->getParent();
9434  S.PushLambdaScope();
9435  LambdaScopeInfo *LSI = S.getCurLambda();
9436  LSI->CallOperator = CallOperator;
9437  LSI->Lambda = LambdaClass;
9438  LSI->ReturnType = CallOperator->getResultType();
9439  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
9440
9441  if (LCD == LCD_None)
9442    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
9443  else if (LCD == LCD_ByCopy)
9444    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
9445  else if (LCD == LCD_ByRef)
9446    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
9447  DeclarationNameInfo DNI = CallOperator->getNameInfo();
9448
9449  LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
9450  LSI->Mutable = !CallOperator->isConst();
9451
9452  // FIXME: Add the captures to the LSI.
9453}
9454
9455Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) {
9456  // Clear the last template instantiation error context.
9457  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
9458
9459  if (!D)
9460    return D;
9461  FunctionDecl *FD = 0;
9462
9463  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
9464    FD = FunTmpl->getTemplatedDecl();
9465  else
9466    FD = cast<FunctionDecl>(D);
9467  // If we are instantiating a generic lambda call operator, push
9468  // a LambdaScopeInfo onto the function stack.  But use the information
9469  // that's already been calculated (ActOnLambdaExpr) to prime the current
9470  // LambdaScopeInfo.
9471  // When the template operator is being specialized, the LambdaScopeInfo,
9472  // has to be properly restored so that tryCaptureVariable doesn't try
9473  // and capture any new variables. In addition when calculating potential
9474  // captures during transformation of nested lambdas, it is necessary to
9475  // have the LSI properly restored.
9476  if (isGenericLambdaCallOperatorSpecialization(FD)) {
9477    assert(ActiveTemplateInstantiations.size() &&
9478      "There should be an active template instantiation on the stack "
9479      "when instantiating a generic lambda!");
9480    RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
9481  }
9482  else
9483    // Enter a new function scope
9484    PushFunctionScope();
9485
9486  // See if this is a redefinition.
9487  if (!FD->isLateTemplateParsed())
9488    CheckForFunctionRedefinition(FD);
9489
9490  // Builtin functions cannot be defined.
9491  if (unsigned BuiltinID = FD->getBuiltinID()) {
9492    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
9493        !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
9494      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
9495      FD->setInvalidDecl();
9496    }
9497  }
9498
9499  // The return type of a function definition must be complete
9500  // (C99 6.9.1p3, C++ [dcl.fct]p6).
9501  QualType ResultType = FD->getResultType();
9502  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
9503      !FD->isInvalidDecl() &&
9504      RequireCompleteType(FD->getLocation(), ResultType,
9505                          diag::err_func_def_incomplete_result))
9506    FD->setInvalidDecl();
9507
9508  // GNU warning -Wmissing-prototypes:
9509  //   Warn if a global function is defined without a previous
9510  //   prototype declaration. This warning is issued even if the
9511  //   definition itself provides a prototype. The aim is to detect
9512  //   global functions that fail to be declared in header files.
9513  const FunctionDecl *PossibleZeroParamPrototype = 0;
9514  if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
9515    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
9516
9517    if (PossibleZeroParamPrototype) {
9518      // We found a declaration that is not a prototype,
9519      // but that could be a zero-parameter prototype
9520      if (TypeSourceInfo *TI =
9521              PossibleZeroParamPrototype->getTypeSourceInfo()) {
9522        TypeLoc TL = TI->getTypeLoc();
9523        if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
9524          Diag(PossibleZeroParamPrototype->getLocation(),
9525               diag::note_declaration_not_a_prototype)
9526            << PossibleZeroParamPrototype
9527            << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
9528      }
9529    }
9530  }
9531
9532  if (FnBodyScope)
9533    PushDeclContext(FnBodyScope, FD);
9534
9535  // Check the validity of our function parameters
9536  CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
9537                           /*CheckParameterNames=*/true);
9538
9539  // Introduce our parameters into the function scope
9540  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
9541    ParmVarDecl *Param = FD->getParamDecl(p);
9542    Param->setOwningFunction(FD);
9543
9544    // If this has an identifier, add it to the scope stack.
9545    if (Param->getIdentifier() && FnBodyScope) {
9546      CheckShadow(FnBodyScope, Param);
9547
9548      PushOnScopeChains(Param, FnBodyScope);
9549    }
9550  }
9551
9552  // If we had any tags defined in the function prototype,
9553  // introduce them into the function scope.
9554  if (FnBodyScope) {
9555    for (ArrayRef<NamedDecl *>::iterator
9556             I = FD->getDeclsInPrototypeScope().begin(),
9557             E = FD->getDeclsInPrototypeScope().end();
9558         I != E; ++I) {
9559      NamedDecl *D = *I;
9560
9561      // Some of these decls (like enums) may have been pinned to the translation unit
9562      // for lack of a real context earlier. If so, remove from the translation unit
9563      // and reattach to the current context.
9564      if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
9565        // Is the decl actually in the context?
9566        for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(),
9567               DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) {
9568          if (*DI == D) {
9569            Context.getTranslationUnitDecl()->removeDecl(D);
9570            break;
9571          }
9572        }
9573        // Either way, reassign the lexical decl context to our FunctionDecl.
9574        D->setLexicalDeclContext(CurContext);
9575      }
9576
9577      // If the decl has a non-null name, make accessible in the current scope.
9578      if (!D->getName().empty())
9579        PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
9580
9581      // Similarly, dive into enums and fish their constants out, making them
9582      // accessible in this scope.
9583      if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
9584        for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(),
9585               EE = ED->enumerator_end(); EI != EE; ++EI)
9586          PushOnScopeChains(*EI, FnBodyScope, /*AddToContext=*/false);
9587      }
9588    }
9589  }
9590
9591  // Ensure that the function's exception specification is instantiated.
9592  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
9593    ResolveExceptionSpec(D->getLocation(), FPT);
9594
9595  // Checking attributes of current function definition
9596  // dllimport attribute.
9597  DLLImportAttr *DA = FD->getAttr<DLLImportAttr>();
9598  if (DA && (!FD->getAttr<DLLExportAttr>())) {
9599    // dllimport attribute cannot be directly applied to definition.
9600    // Microsoft accepts dllimport for functions defined within class scope.
9601    if (!DA->isInherited() &&
9602        !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) {
9603      Diag(FD->getLocation(),
9604           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
9605        << "dllimport";
9606      FD->setInvalidDecl();
9607      return D;
9608    }
9609
9610    // Visual C++ appears to not think this is an issue, so only issue
9611    // a warning when Microsoft extensions are disabled.
9612    if (!LangOpts.MicrosoftExt) {
9613      // If a symbol previously declared dllimport is later defined, the
9614      // attribute is ignored in subsequent references, and a warning is
9615      // emitted.
9616      Diag(FD->getLocation(),
9617           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
9618        << FD->getName() << "dllimport";
9619    }
9620  }
9621  // We want to attach documentation to original Decl (which might be
9622  // a function template).
9623  ActOnDocumentableDecl(D);
9624  return D;
9625}
9626
9627/// \brief Given the set of return statements within a function body,
9628/// compute the variables that are subject to the named return value
9629/// optimization.
9630///
9631/// Each of the variables that is subject to the named return value
9632/// optimization will be marked as NRVO variables in the AST, and any
9633/// return statement that has a marked NRVO variable as its NRVO candidate can
9634/// use the named return value optimization.
9635///
9636/// This function applies a very simplistic algorithm for NRVO: if every return
9637/// statement in the function has the same NRVO candidate, that candidate is
9638/// the NRVO variable.
9639///
9640/// FIXME: Employ a smarter algorithm that accounts for multiple return
9641/// statements and the lifetimes of the NRVO candidates. We should be able to
9642/// find a maximal set of NRVO variables.
9643void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
9644  ReturnStmt **Returns = Scope->Returns.data();
9645
9646  const VarDecl *NRVOCandidate = 0;
9647  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
9648    if (!Returns[I]->getNRVOCandidate())
9649      return;
9650
9651    if (!NRVOCandidate)
9652      NRVOCandidate = Returns[I]->getNRVOCandidate();
9653    else if (NRVOCandidate != Returns[I]->getNRVOCandidate())
9654      return;
9655  }
9656
9657  if (NRVOCandidate)
9658    const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true);
9659}
9660
9661bool Sema::canSkipFunctionBody(Decl *D) {
9662  if (!Consumer.shouldSkipFunctionBody(D))
9663    return false;
9664
9665  if (isa<ObjCMethodDecl>(D))
9666    return true;
9667
9668  FunctionDecl *FD = 0;
9669  if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
9670    FD = FTD->getTemplatedDecl();
9671  else
9672    FD = cast<FunctionDecl>(D);
9673
9674  // We cannot skip the body of a function (or function template) which is
9675  // constexpr, since we may need to evaluate its body in order to parse the
9676  // rest of the file.
9677  // We cannot skip the body of a function with an undeduced return type,
9678  // because any callers of that function need to know the type.
9679  return !FD->isConstexpr() && !FD->getResultType()->isUndeducedType();
9680}
9681
9682Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
9683  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
9684    FD->setHasSkippedBody();
9685  else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
9686    MD->setHasSkippedBody();
9687  return ActOnFinishFunctionBody(Decl, 0);
9688}
9689
9690Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
9691  return ActOnFinishFunctionBody(D, BodyArg, false);
9692}
9693
9694Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
9695                                    bool IsInstantiation) {
9696  FunctionDecl *FD = 0;
9697  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
9698  if (FunTmpl)
9699    FD = FunTmpl->getTemplatedDecl();
9700  else
9701    FD = dyn_cast_or_null<FunctionDecl>(dcl);
9702
9703  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
9704  sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0;
9705
9706  if (FD) {
9707    FD->setBody(Body);
9708
9709    if (getLangOpts().CPlusPlus1y && !FD->isInvalidDecl() && Body &&
9710        !FD->isDependentContext() && FD->getResultType()->isUndeducedType()) {
9711      // If the function has a deduced result type but contains no 'return'
9712      // statements, the result type as written must be exactly 'auto', and
9713      // the deduced result type is 'void'.
9714      if (!FD->getResultType()->getAs<AutoType>()) {
9715        Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
9716          << FD->getResultType();
9717        FD->setInvalidDecl();
9718      } else {
9719        // Substitute 'void' for the 'auto' in the type.
9720        TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc().
9721            IgnoreParens().castAs<FunctionProtoTypeLoc>().getResultLoc();
9722        Context.adjustDeducedFunctionResultType(
9723            FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
9724      }
9725    }
9726
9727    // The only way to be included in UndefinedButUsed is if there is an
9728    // ODR use before the definition. Avoid the expensive map lookup if this
9729    // is the first declaration.
9730    if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
9731      if (!FD->isExternallyVisible())
9732        UndefinedButUsed.erase(FD);
9733      else if (FD->isInlined() &&
9734               (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
9735               (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
9736        UndefinedButUsed.erase(FD);
9737    }
9738
9739    // If the function implicitly returns zero (like 'main') or is naked,
9740    // don't complain about missing return statements.
9741    if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
9742      WP.disableCheckFallThrough();
9743
9744    // MSVC permits the use of pure specifier (=0) on function definition,
9745    // defined at class scope, warn about this non standard construct.
9746    if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
9747      Diag(FD->getLocation(), diag::warn_pure_function_definition);
9748
9749    if (!FD->isInvalidDecl()) {
9750      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
9751      DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
9752                                             FD->getResultType(), FD);
9753
9754      // If this is a constructor, we need a vtable.
9755      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
9756        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
9757
9758      // Try to apply the named return value optimization. We have to check
9759      // if we can do this here because lambdas keep return statements around
9760      // to deduce an implicit return type.
9761      if (getLangOpts().CPlusPlus && FD->getResultType()->isRecordType() &&
9762          !FD->isDependentContext())
9763        computeNRVO(Body, getCurFunction());
9764    }
9765
9766    assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
9767           "Function parsing confused");
9768  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
9769    assert(MD == getCurMethodDecl() && "Method parsing confused");
9770    MD->setBody(Body);
9771    if (!MD->isInvalidDecl()) {
9772      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
9773      DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
9774                                             MD->getResultType(), MD);
9775
9776      if (Body)
9777        computeNRVO(Body, getCurFunction());
9778    }
9779    if (getCurFunction()->ObjCShouldCallSuper) {
9780      Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
9781        << MD->getSelector().getAsString();
9782      getCurFunction()->ObjCShouldCallSuper = false;
9783    }
9784  } else {
9785    return 0;
9786  }
9787
9788  assert(!getCurFunction()->ObjCShouldCallSuper &&
9789         "This should only be set for ObjC methods, which should have been "
9790         "handled in the block above.");
9791
9792  // Verify and clean out per-function state.
9793  if (Body) {
9794    // C++ constructors that have function-try-blocks can't have return
9795    // statements in the handlers of that block. (C++ [except.handle]p14)
9796    // Verify this.
9797    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
9798      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
9799
9800    // Verify that gotos and switch cases don't jump into scopes illegally.
9801    if (getCurFunction()->NeedsScopeChecking() &&
9802        !dcl->isInvalidDecl() &&
9803        !hasAnyUnrecoverableErrorsInThisFunction() &&
9804        !PP.isCodeCompletionEnabled())
9805      DiagnoseInvalidJumps(Body);
9806
9807    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
9808      if (!Destructor->getParent()->isDependentType())
9809        CheckDestructor(Destructor);
9810
9811      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
9812                                             Destructor->getParent());
9813    }
9814
9815    // If any errors have occurred, clear out any temporaries that may have
9816    // been leftover. This ensures that these temporaries won't be picked up for
9817    // deletion in some later function.
9818    if (PP.getDiagnostics().hasErrorOccurred() ||
9819        PP.getDiagnostics().getSuppressAllDiagnostics()) {
9820      DiscardCleanupsInEvaluationContext();
9821    }
9822    if (!PP.getDiagnostics().hasUncompilableErrorOccurred() &&
9823        !isa<FunctionTemplateDecl>(dcl)) {
9824      // Since the body is valid, issue any analysis-based warnings that are
9825      // enabled.
9826      ActivePolicy = &WP;
9827    }
9828
9829    if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
9830        (!CheckConstexprFunctionDecl(FD) ||
9831         !CheckConstexprFunctionBody(FD, Body)))
9832      FD->setInvalidDecl();
9833
9834    assert(ExprCleanupObjects.empty() && "Leftover temporaries in function");
9835    assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
9836    assert(MaybeODRUseExprs.empty() &&
9837           "Leftover expressions for odr-use checking");
9838  }
9839
9840  if (!IsInstantiation)
9841    PopDeclContext();
9842
9843  PopFunctionScopeInfo(ActivePolicy, dcl);
9844  // If any errors have occurred, clear out any temporaries that may have
9845  // been leftover. This ensures that these temporaries won't be picked up for
9846  // deletion in some later function.
9847  if (getDiagnostics().hasErrorOccurred()) {
9848    DiscardCleanupsInEvaluationContext();
9849  }
9850
9851  return dcl;
9852}
9853
9854
9855/// When we finish delayed parsing of an attribute, we must attach it to the
9856/// relevant Decl.
9857void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
9858                                       ParsedAttributes &Attrs) {
9859  // Always attach attributes to the underlying decl.
9860  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
9861    D = TD->getTemplatedDecl();
9862  ProcessDeclAttributeList(S, D, Attrs.getList());
9863
9864  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
9865    if (Method->isStatic())
9866      checkThisInStaticMemberFunctionAttributes(Method);
9867}
9868
9869
9870/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
9871/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
9872NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
9873                                          IdentifierInfo &II, Scope *S) {
9874  // Before we produce a declaration for an implicitly defined
9875  // function, see whether there was a locally-scoped declaration of
9876  // this name as a function or variable. If so, use that
9877  // (non-visible) declaration, and complain about it.
9878  if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
9879    Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
9880    Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
9881    return ExternCPrev;
9882  }
9883
9884  // Extension in C99.  Legal in C90, but warn about it.
9885  unsigned diag_id;
9886  if (II.getName().startswith("__builtin_"))
9887    diag_id = diag::warn_builtin_unknown;
9888  else if (getLangOpts().C99)
9889    diag_id = diag::ext_implicit_function_decl;
9890  else
9891    diag_id = diag::warn_implicit_function_decl;
9892  Diag(Loc, diag_id) << &II;
9893
9894  // Because typo correction is expensive, only do it if the implicit
9895  // function declaration is going to be treated as an error.
9896  if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
9897    TypoCorrection Corrected;
9898    DeclFilterCCC<FunctionDecl> Validator;
9899    if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc),
9900                                      LookupOrdinaryName, S, 0, Validator)))
9901      diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
9902                   /*ErrorRecovery*/false);
9903  }
9904
9905  // Set a Declarator for the implicit definition: int foo();
9906  const char *Dummy;
9907  AttributeFactory attrFactory;
9908  DeclSpec DS(attrFactory);
9909  unsigned DiagID;
9910  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
9911  (void)Error; // Silence warning.
9912  assert(!Error && "Error setting up implicit decl!");
9913  SourceLocation NoLoc;
9914  Declarator D(DS, Declarator::BlockContext);
9915  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
9916                                             /*IsAmbiguous=*/false,
9917                                             /*RParenLoc=*/NoLoc,
9918                                             /*ArgInfo=*/0,
9919                                             /*NumArgs=*/0,
9920                                             /*EllipsisLoc=*/NoLoc,
9921                                             /*RParenLoc=*/NoLoc,
9922                                             /*TypeQuals=*/0,
9923                                             /*RefQualifierIsLvalueRef=*/true,
9924                                             /*RefQualifierLoc=*/NoLoc,
9925                                             /*ConstQualifierLoc=*/NoLoc,
9926                                             /*VolatileQualifierLoc=*/NoLoc,
9927                                             /*MutableLoc=*/NoLoc,
9928                                             EST_None,
9929                                             /*ESpecLoc=*/NoLoc,
9930                                             /*Exceptions=*/0,
9931                                             /*ExceptionRanges=*/0,
9932                                             /*NumExceptions=*/0,
9933                                             /*NoexceptExpr=*/0,
9934                                             Loc, Loc, D),
9935                DS.getAttributes(),
9936                SourceLocation());
9937  D.SetIdentifier(&II, Loc);
9938
9939  // Insert this function into translation-unit scope.
9940
9941  DeclContext *PrevDC = CurContext;
9942  CurContext = Context.getTranslationUnitDecl();
9943
9944  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
9945  FD->setImplicit();
9946
9947  CurContext = PrevDC;
9948
9949  AddKnownFunctionAttributes(FD);
9950
9951  return FD;
9952}
9953
9954/// \brief Adds any function attributes that we know a priori based on
9955/// the declaration of this function.
9956///
9957/// These attributes can apply both to implicitly-declared builtins
9958/// (like __builtin___printf_chk) or to library-declared functions
9959/// like NSLog or printf.
9960///
9961/// We need to check for duplicate attributes both here and where user-written
9962/// attributes are applied to declarations.
9963void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
9964  if (FD->isInvalidDecl())
9965    return;
9966
9967  // If this is a built-in function, map its builtin attributes to
9968  // actual attributes.
9969  if (unsigned BuiltinID = FD->getBuiltinID()) {
9970    // Handle printf-formatting attributes.
9971    unsigned FormatIdx;
9972    bool HasVAListArg;
9973    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
9974      if (!FD->getAttr<FormatAttr>()) {
9975        const char *fmt = "printf";
9976        unsigned int NumParams = FD->getNumParams();
9977        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
9978            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
9979          fmt = "NSString";
9980        FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9981                                               &Context.Idents.get(fmt),
9982                                               FormatIdx+1,
9983                                               HasVAListArg ? 0 : FormatIdx+2));
9984      }
9985    }
9986    if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
9987                                             HasVAListArg)) {
9988     if (!FD->getAttr<FormatAttr>())
9989       FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
9990                                              &Context.Idents.get("scanf"),
9991                                              FormatIdx+1,
9992                                              HasVAListArg ? 0 : FormatIdx+2));
9993    }
9994
9995    // Mark const if we don't care about errno and that is the only
9996    // thing preventing the function from being const. This allows
9997    // IRgen to use LLVM intrinsics for such functions.
9998    if (!getLangOpts().MathErrno &&
9999        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
10000      if (!FD->getAttr<ConstAttr>())
10001        FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
10002    }
10003
10004    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
10005        !FD->getAttr<ReturnsTwiceAttr>())
10006      FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context));
10007    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>())
10008      FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context));
10009    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>())
10010      FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context));
10011  }
10012
10013  IdentifierInfo *Name = FD->getIdentifier();
10014  if (!Name)
10015    return;
10016  if ((!getLangOpts().CPlusPlus &&
10017       FD->getDeclContext()->isTranslationUnit()) ||
10018      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
10019       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
10020       LinkageSpecDecl::lang_c)) {
10021    // Okay: this could be a libc/libm/Objective-C function we know
10022    // about.
10023  } else
10024    return;
10025
10026  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
10027    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
10028    // target-specific builtins, perhaps?
10029    if (!FD->getAttr<FormatAttr>())
10030      FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context,
10031                                             &Context.Idents.get("printf"), 2,
10032                                             Name->isStr("vasprintf") ? 0 : 3));
10033  }
10034
10035  if (Name->isStr("__CFStringMakeConstantString")) {
10036    // We already have a __builtin___CFStringMakeConstantString,
10037    // but builds that use -fno-constant-cfstrings don't go through that.
10038    if (!FD->getAttr<FormatArgAttr>())
10039      FD->addAttr(::new (Context) FormatArgAttr(FD->getLocation(), Context, 1));
10040  }
10041}
10042
10043TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
10044                                    TypeSourceInfo *TInfo) {
10045  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
10046  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
10047
10048  if (!TInfo) {
10049    assert(D.isInvalidType() && "no declarator info for valid type");
10050    TInfo = Context.getTrivialTypeSourceInfo(T);
10051  }
10052
10053  // Scope manipulation handled by caller.
10054  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
10055                                           D.getLocStart(),
10056                                           D.getIdentifierLoc(),
10057                                           D.getIdentifier(),
10058                                           TInfo);
10059
10060  // Bail out immediately if we have an invalid declaration.
10061  if (D.isInvalidType()) {
10062    NewTD->setInvalidDecl();
10063    return NewTD;
10064  }
10065
10066  if (D.getDeclSpec().isModulePrivateSpecified()) {
10067    if (CurContext->isFunctionOrMethod())
10068      Diag(NewTD->getLocation(), diag::err_module_private_local)
10069        << 2 << NewTD->getDeclName()
10070        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10071        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10072    else
10073      NewTD->setModulePrivate();
10074  }
10075
10076  // C++ [dcl.typedef]p8:
10077  //   If the typedef declaration defines an unnamed class (or
10078  //   enum), the first typedef-name declared by the declaration
10079  //   to be that class type (or enum type) is used to denote the
10080  //   class type (or enum type) for linkage purposes only.
10081  // We need to check whether the type was declared in the declaration.
10082  switch (D.getDeclSpec().getTypeSpecType()) {
10083  case TST_enum:
10084  case TST_struct:
10085  case TST_interface:
10086  case TST_union:
10087  case TST_class: {
10088    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
10089
10090    // Do nothing if the tag is not anonymous or already has an
10091    // associated typedef (from an earlier typedef in this decl group).
10092    if (tagFromDeclSpec->getIdentifier()) break;
10093    if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break;
10094
10095    // A well-formed anonymous tag must always be a TUK_Definition.
10096    assert(tagFromDeclSpec->isThisDeclarationADefinition());
10097
10098    // The type must match the tag exactly;  no qualifiers allowed.
10099    if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec)))
10100      break;
10101
10102    // Otherwise, set this is the anon-decl typedef for the tag.
10103    tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
10104    break;
10105  }
10106
10107  default:
10108    break;
10109  }
10110
10111  return NewTD;
10112}
10113
10114
10115/// \brief Check that this is a valid underlying type for an enum declaration.
10116bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
10117  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
10118  QualType T = TI->getType();
10119
10120  if (T->isDependentType())
10121    return false;
10122
10123  if (const BuiltinType *BT = T->getAs<BuiltinType>())
10124    if (BT->isInteger())
10125      return false;
10126
10127  Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
10128  return true;
10129}
10130
10131/// Check whether this is a valid redeclaration of a previous enumeration.
10132/// \return true if the redeclaration was invalid.
10133bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
10134                                  QualType EnumUnderlyingTy,
10135                                  const EnumDecl *Prev) {
10136  bool IsFixed = !EnumUnderlyingTy.isNull();
10137
10138  if (IsScoped != Prev->isScoped()) {
10139    Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
10140      << Prev->isScoped();
10141    Diag(Prev->getLocation(), diag::note_previous_use);
10142    return true;
10143  }
10144
10145  if (IsFixed && Prev->isFixed()) {
10146    if (!EnumUnderlyingTy->isDependentType() &&
10147        !Prev->getIntegerType()->isDependentType() &&
10148        !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
10149                                        Prev->getIntegerType())) {
10150      Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
10151        << EnumUnderlyingTy << Prev->getIntegerType();
10152      Diag(Prev->getLocation(), diag::note_previous_use);
10153      return true;
10154    }
10155  } else if (IsFixed != Prev->isFixed()) {
10156    Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
10157      << Prev->isFixed();
10158    Diag(Prev->getLocation(), diag::note_previous_use);
10159    return true;
10160  }
10161
10162  return false;
10163}
10164
10165/// \brief Get diagnostic %select index for tag kind for
10166/// redeclaration diagnostic message.
10167/// WARNING: Indexes apply to particular diagnostics only!
10168///
10169/// \returns diagnostic %select index.
10170static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
10171  switch (Tag) {
10172  case TTK_Struct: return 0;
10173  case TTK_Interface: return 1;
10174  case TTK_Class:  return 2;
10175  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
10176  }
10177}
10178
10179/// \brief Determine if tag kind is a class-key compatible with
10180/// class for redeclaration (class, struct, or __interface).
10181///
10182/// \returns true iff the tag kind is compatible.
10183static bool isClassCompatTagKind(TagTypeKind Tag)
10184{
10185  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
10186}
10187
10188/// \brief Determine whether a tag with a given kind is acceptable
10189/// as a redeclaration of the given tag declaration.
10190///
10191/// \returns true if the new tag kind is acceptable, false otherwise.
10192bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
10193                                        TagTypeKind NewTag, bool isDefinition,
10194                                        SourceLocation NewTagLoc,
10195                                        const IdentifierInfo &Name) {
10196  // C++ [dcl.type.elab]p3:
10197  //   The class-key or enum keyword present in the
10198  //   elaborated-type-specifier shall agree in kind with the
10199  //   declaration to which the name in the elaborated-type-specifier
10200  //   refers. This rule also applies to the form of
10201  //   elaborated-type-specifier that declares a class-name or
10202  //   friend class since it can be construed as referring to the
10203  //   definition of the class. Thus, in any
10204  //   elaborated-type-specifier, the enum keyword shall be used to
10205  //   refer to an enumeration (7.2), the union class-key shall be
10206  //   used to refer to a union (clause 9), and either the class or
10207  //   struct class-key shall be used to refer to a class (clause 9)
10208  //   declared using the class or struct class-key.
10209  TagTypeKind OldTag = Previous->getTagKind();
10210  if (!isDefinition || !isClassCompatTagKind(NewTag))
10211    if (OldTag == NewTag)
10212      return true;
10213
10214  if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
10215    // Warn about the struct/class tag mismatch.
10216    bool isTemplate = false;
10217    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
10218      isTemplate = Record->getDescribedClassTemplate();
10219
10220    if (!ActiveTemplateInstantiations.empty()) {
10221      // In a template instantiation, do not offer fix-its for tag mismatches
10222      // since they usually mess up the template instead of fixing the problem.
10223      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10224        << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10225        << getRedeclDiagFromTagKind(OldTag);
10226      return true;
10227    }
10228
10229    if (isDefinition) {
10230      // On definitions, check previous tags and issue a fix-it for each
10231      // one that doesn't match the current tag.
10232      if (Previous->getDefinition()) {
10233        // Don't suggest fix-its for redefinitions.
10234        return true;
10235      }
10236
10237      bool previousMismatch = false;
10238      for (TagDecl::redecl_iterator I(Previous->redecls_begin()),
10239           E(Previous->redecls_end()); I != E; ++I) {
10240        if (I->getTagKind() != NewTag) {
10241          if (!previousMismatch) {
10242            previousMismatch = true;
10243            Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
10244              << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10245              << getRedeclDiagFromTagKind(I->getTagKind());
10246          }
10247          Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
10248            << getRedeclDiagFromTagKind(NewTag)
10249            << FixItHint::CreateReplacement(I->getInnerLocStart(),
10250                 TypeWithKeyword::getTagTypeKindName(NewTag));
10251        }
10252      }
10253      return true;
10254    }
10255
10256    // Check for a previous definition.  If current tag and definition
10257    // are same type, do nothing.  If no definition, but disagree with
10258    // with previous tag type, give a warning, but no fix-it.
10259    const TagDecl *Redecl = Previous->getDefinition() ?
10260                            Previous->getDefinition() : Previous;
10261    if (Redecl->getTagKind() == NewTag) {
10262      return true;
10263    }
10264
10265    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
10266      << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name
10267      << getRedeclDiagFromTagKind(OldTag);
10268    Diag(Redecl->getLocation(), diag::note_previous_use);
10269
10270    // If there is a previous defintion, suggest a fix-it.
10271    if (Previous->getDefinition()) {
10272        Diag(NewTagLoc, diag::note_struct_class_suggestion)
10273          << getRedeclDiagFromTagKind(Redecl->getTagKind())
10274          << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
10275               TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
10276    }
10277
10278    return true;
10279  }
10280  return false;
10281}
10282
10283/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
10284/// former case, Name will be non-null.  In the later case, Name will be null.
10285/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
10286/// reference/declaration/definition of a tag.
10287Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10288                     SourceLocation KWLoc, CXXScopeSpec &SS,
10289                     IdentifierInfo *Name, SourceLocation NameLoc,
10290                     AttributeList *Attr, AccessSpecifier AS,
10291                     SourceLocation ModulePrivateLoc,
10292                     MultiTemplateParamsArg TemplateParameterLists,
10293                     bool &OwnedDecl, bool &IsDependent,
10294                     SourceLocation ScopedEnumKWLoc,
10295                     bool ScopedEnumUsesClassTag,
10296                     TypeResult UnderlyingType) {
10297  // If this is not a definition, it must have a name.
10298  IdentifierInfo *OrigName = Name;
10299  assert((Name != 0 || TUK == TUK_Definition) &&
10300         "Nameless record must be a definition!");
10301  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
10302
10303  OwnedDecl = false;
10304  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10305  bool ScopedEnum = ScopedEnumKWLoc.isValid();
10306
10307  // FIXME: Check explicit specializations more carefully.
10308  bool isExplicitSpecialization = false;
10309  bool Invalid = false;
10310
10311  // We only need to do this matching if we have template parameters
10312  // or a scope specifier, which also conveniently avoids this work
10313  // for non-C++ cases.
10314  if (TemplateParameterLists.size() > 0 ||
10315      (SS.isNotEmpty() && TUK != TUK_Reference)) {
10316    if (TemplateParameterList *TemplateParams =
10317            MatchTemplateParametersToScopeSpecifier(
10318                KWLoc, NameLoc, SS, TemplateParameterLists, TUK == TUK_Friend,
10319                isExplicitSpecialization, Invalid)) {
10320      if (Kind == TTK_Enum) {
10321        Diag(KWLoc, diag::err_enum_template);
10322        return 0;
10323      }
10324
10325      if (TemplateParams->size() > 0) {
10326        // This is a declaration or definition of a class template (which may
10327        // be a member of another template).
10328
10329        if (Invalid)
10330          return 0;
10331
10332        OwnedDecl = false;
10333        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
10334                                               SS, Name, NameLoc, Attr,
10335                                               TemplateParams, AS,
10336                                               ModulePrivateLoc,
10337                                               TemplateParameterLists.size()-1,
10338                                               TemplateParameterLists.data());
10339        return Result.get();
10340      } else {
10341        // The "template<>" header is extraneous.
10342        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10343          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10344        isExplicitSpecialization = true;
10345      }
10346    }
10347  }
10348
10349  // Figure out the underlying type if this a enum declaration. We need to do
10350  // this early, because it's needed to detect if this is an incompatible
10351  // redeclaration.
10352  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
10353
10354  if (Kind == TTK_Enum) {
10355    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
10356      // No underlying type explicitly specified, or we failed to parse the
10357      // type, default to int.
10358      EnumUnderlying = Context.IntTy.getTypePtr();
10359    else if (UnderlyingType.get()) {
10360      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
10361      // integral type; any cv-qualification is ignored.
10362      TypeSourceInfo *TI = 0;
10363      GetTypeFromParser(UnderlyingType.get(), &TI);
10364      EnumUnderlying = TI;
10365
10366      if (CheckEnumUnderlyingType(TI))
10367        // Recover by falling back to int.
10368        EnumUnderlying = Context.IntTy.getTypePtr();
10369
10370      if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
10371                                          UPPC_FixedUnderlyingType))
10372        EnumUnderlying = Context.IntTy.getTypePtr();
10373
10374    } else if (getLangOpts().MicrosoftMode)
10375      // Microsoft enums are always of int type.
10376      EnumUnderlying = Context.IntTy.getTypePtr();
10377  }
10378
10379  DeclContext *SearchDC = CurContext;
10380  DeclContext *DC = CurContext;
10381  bool isStdBadAlloc = false;
10382
10383  RedeclarationKind Redecl = ForRedeclaration;
10384  if (TUK == TUK_Friend || TUK == TUK_Reference)
10385    Redecl = NotForRedeclaration;
10386
10387  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
10388  bool FriendSawTagOutsideEnclosingNamespace = false;
10389  if (Name && SS.isNotEmpty()) {
10390    // We have a nested-name tag ('struct foo::bar').
10391
10392    // Check for invalid 'foo::'.
10393    if (SS.isInvalid()) {
10394      Name = 0;
10395      goto CreateNewDecl;
10396    }
10397
10398    // If this is a friend or a reference to a class in a dependent
10399    // context, don't try to make a decl for it.
10400    if (TUK == TUK_Friend || TUK == TUK_Reference) {
10401      DC = computeDeclContext(SS, false);
10402      if (!DC) {
10403        IsDependent = true;
10404        return 0;
10405      }
10406    } else {
10407      DC = computeDeclContext(SS, true);
10408      if (!DC) {
10409        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
10410          << SS.getRange();
10411        return 0;
10412      }
10413    }
10414
10415    if (RequireCompleteDeclContext(SS, DC))
10416      return 0;
10417
10418    SearchDC = DC;
10419    // Look-up name inside 'foo::'.
10420    LookupQualifiedName(Previous, DC);
10421
10422    if (Previous.isAmbiguous())
10423      return 0;
10424
10425    if (Previous.empty()) {
10426      // Name lookup did not find anything. However, if the
10427      // nested-name-specifier refers to the current instantiation,
10428      // and that current instantiation has any dependent base
10429      // classes, we might find something at instantiation time: treat
10430      // this as a dependent elaborated-type-specifier.
10431      // But this only makes any sense for reference-like lookups.
10432      if (Previous.wasNotFoundInCurrentInstantiation() &&
10433          (TUK == TUK_Reference || TUK == TUK_Friend)) {
10434        IsDependent = true;
10435        return 0;
10436      }
10437
10438      // A tag 'foo::bar' must already exist.
10439      Diag(NameLoc, diag::err_not_tag_in_scope)
10440        << Kind << Name << DC << SS.getRange();
10441      Name = 0;
10442      Invalid = true;
10443      goto CreateNewDecl;
10444    }
10445  } else if (Name) {
10446    // If this is a named struct, check to see if there was a previous forward
10447    // declaration or definition.
10448    // FIXME: We're looking into outer scopes here, even when we
10449    // shouldn't be. Doing so can result in ambiguities that we
10450    // shouldn't be diagnosing.
10451    LookupName(Previous, S);
10452
10453    // When declaring or defining a tag, ignore ambiguities introduced
10454    // by types using'ed into this scope.
10455    if (Previous.isAmbiguous() &&
10456        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
10457      LookupResult::Filter F = Previous.makeFilter();
10458      while (F.hasNext()) {
10459        NamedDecl *ND = F.next();
10460        if (ND->getDeclContext()->getRedeclContext() != SearchDC)
10461          F.erase();
10462      }
10463      F.done();
10464    }
10465
10466    // C++11 [namespace.memdef]p3:
10467    //   If the name in a friend declaration is neither qualified nor
10468    //   a template-id and the declaration is a function or an
10469    //   elaborated-type-specifier, the lookup to determine whether
10470    //   the entity has been previously declared shall not consider
10471    //   any scopes outside the innermost enclosing namespace.
10472    //
10473    // Does it matter that this should be by scope instead of by
10474    // semantic context?
10475    if (!Previous.empty() && TUK == TUK_Friend) {
10476      DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
10477      LookupResult::Filter F = Previous.makeFilter();
10478      while (F.hasNext()) {
10479        NamedDecl *ND = F.next();
10480        DeclContext *DC = ND->getDeclContext()->getRedeclContext();
10481        if (DC->isFileContext() &&
10482            !EnclosingNS->Encloses(ND->getDeclContext())) {
10483          F.erase();
10484          FriendSawTagOutsideEnclosingNamespace = true;
10485        }
10486      }
10487      F.done();
10488    }
10489
10490    // Note:  there used to be some attempt at recovery here.
10491    if (Previous.isAmbiguous())
10492      return 0;
10493
10494    if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
10495      // FIXME: This makes sure that we ignore the contexts associated
10496      // with C structs, unions, and enums when looking for a matching
10497      // tag declaration or definition. See the similar lookup tweak
10498      // in Sema::LookupName; is there a better way to deal with this?
10499      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
10500        SearchDC = SearchDC->getParent();
10501    }
10502  } else if (S->isFunctionPrototypeScope()) {
10503    // If this is an enum declaration in function prototype scope, set its
10504    // initial context to the translation unit.
10505    // FIXME: [citation needed]
10506    SearchDC = Context.getTranslationUnitDecl();
10507  }
10508
10509  if (Previous.isSingleResult() &&
10510      Previous.getFoundDecl()->isTemplateParameter()) {
10511    // Maybe we will complain about the shadowed template parameter.
10512    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
10513    // Just pretend that we didn't see the previous declaration.
10514    Previous.clear();
10515  }
10516
10517  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
10518      DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
10519    // This is a declaration of or a reference to "std::bad_alloc".
10520    isStdBadAlloc = true;
10521
10522    if (Previous.empty() && StdBadAlloc) {
10523      // std::bad_alloc has been implicitly declared (but made invisible to
10524      // name lookup). Fill in this implicit declaration as the previous
10525      // declaration, so that the declarations get chained appropriately.
10526      Previous.addDecl(getStdBadAlloc());
10527    }
10528  }
10529
10530  // If we didn't find a previous declaration, and this is a reference
10531  // (or friend reference), move to the correct scope.  In C++, we
10532  // also need to do a redeclaration lookup there, just in case
10533  // there's a shadow friend decl.
10534  if (Name && Previous.empty() &&
10535      (TUK == TUK_Reference || TUK == TUK_Friend)) {
10536    if (Invalid) goto CreateNewDecl;
10537    assert(SS.isEmpty());
10538
10539    if (TUK == TUK_Reference) {
10540      // C++ [basic.scope.pdecl]p5:
10541      //   -- for an elaborated-type-specifier of the form
10542      //
10543      //          class-key identifier
10544      //
10545      //      if the elaborated-type-specifier is used in the
10546      //      decl-specifier-seq or parameter-declaration-clause of a
10547      //      function defined in namespace scope, the identifier is
10548      //      declared as a class-name in the namespace that contains
10549      //      the declaration; otherwise, except as a friend
10550      //      declaration, the identifier is declared in the smallest
10551      //      non-class, non-function-prototype scope that contains the
10552      //      declaration.
10553      //
10554      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
10555      // C structs and unions.
10556      //
10557      // It is an error in C++ to declare (rather than define) an enum
10558      // type, including via an elaborated type specifier.  We'll
10559      // diagnose that later; for now, declare the enum in the same
10560      // scope as we would have picked for any other tag type.
10561      //
10562      // GNU C also supports this behavior as part of its incomplete
10563      // enum types extension, while GNU C++ does not.
10564      //
10565      // Find the context where we'll be declaring the tag.
10566      // FIXME: We would like to maintain the current DeclContext as the
10567      // lexical context,
10568      while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
10569        SearchDC = SearchDC->getParent();
10570
10571      // Find the scope where we'll be declaring the tag.
10572      while (S->isClassScope() ||
10573             (getLangOpts().CPlusPlus &&
10574              S->isFunctionPrototypeScope()) ||
10575             ((S->getFlags() & Scope::DeclScope) == 0) ||
10576             (S->getEntity() && S->getEntity()->isTransparentContext()))
10577        S = S->getParent();
10578    } else {
10579      assert(TUK == TUK_Friend);
10580      // C++ [namespace.memdef]p3:
10581      //   If a friend declaration in a non-local class first declares a
10582      //   class or function, the friend class or function is a member of
10583      //   the innermost enclosing namespace.
10584      SearchDC = SearchDC->getEnclosingNamespaceContext();
10585    }
10586
10587    // In C++, we need to do a redeclaration lookup to properly
10588    // diagnose some problems.
10589    if (getLangOpts().CPlusPlus) {
10590      Previous.setRedeclarationKind(ForRedeclaration);
10591      LookupQualifiedName(Previous, SearchDC);
10592    }
10593  }
10594
10595  if (!Previous.empty()) {
10596    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
10597
10598    // It's okay to have a tag decl in the same scope as a typedef
10599    // which hides a tag decl in the same scope.  Finding this
10600    // insanity with a redeclaration lookup can only actually happen
10601    // in C++.
10602    //
10603    // This is also okay for elaborated-type-specifiers, which is
10604    // technically forbidden by the current standard but which is
10605    // okay according to the likely resolution of an open issue;
10606    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
10607    if (getLangOpts().CPlusPlus) {
10608      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10609        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
10610          TagDecl *Tag = TT->getDecl();
10611          if (Tag->getDeclName() == Name &&
10612              Tag->getDeclContext()->getRedeclContext()
10613                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
10614            PrevDecl = Tag;
10615            Previous.clear();
10616            Previous.addDecl(Tag);
10617            Previous.resolveKind();
10618          }
10619        }
10620      }
10621    }
10622
10623    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
10624      // If this is a use of a previous tag, or if the tag is already declared
10625      // in the same scope (so that the definition/declaration completes or
10626      // rementions the tag), reuse the decl.
10627      if (TUK == TUK_Reference || TUK == TUK_Friend ||
10628          isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) {
10629        // Make sure that this wasn't declared as an enum and now used as a
10630        // struct or something similar.
10631        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
10632                                          TUK == TUK_Definition, KWLoc,
10633                                          *Name)) {
10634          bool SafeToContinue
10635            = (PrevTagDecl->getTagKind() != TTK_Enum &&
10636               Kind != TTK_Enum);
10637          if (SafeToContinue)
10638            Diag(KWLoc, diag::err_use_with_wrong_tag)
10639              << Name
10640              << FixItHint::CreateReplacement(SourceRange(KWLoc),
10641                                              PrevTagDecl->getKindName());
10642          else
10643            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
10644          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
10645
10646          if (SafeToContinue)
10647            Kind = PrevTagDecl->getTagKind();
10648          else {
10649            // Recover by making this an anonymous redefinition.
10650            Name = 0;
10651            Previous.clear();
10652            Invalid = true;
10653          }
10654        }
10655
10656        if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
10657          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
10658
10659          // If this is an elaborated-type-specifier for a scoped enumeration,
10660          // the 'class' keyword is not necessary and not permitted.
10661          if (TUK == TUK_Reference || TUK == TUK_Friend) {
10662            if (ScopedEnum)
10663              Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
10664                << PrevEnum->isScoped()
10665                << FixItHint::CreateRemoval(ScopedEnumKWLoc);
10666            return PrevTagDecl;
10667          }
10668
10669          QualType EnumUnderlyingTy;
10670          if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10671            EnumUnderlyingTy = TI->getType();
10672          else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
10673            EnumUnderlyingTy = QualType(T, 0);
10674
10675          // All conflicts with previous declarations are recovered by
10676          // returning the previous declaration, unless this is a definition,
10677          // in which case we want the caller to bail out.
10678          if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
10679                                     ScopedEnum, EnumUnderlyingTy, PrevEnum))
10680            return TUK == TUK_Declaration ? PrevTagDecl : 0;
10681        }
10682
10683        // C++11 [class.mem]p1:
10684        //   A member shall not be declared twice in the member-specification,
10685        //   except that a nested class or member class template can be declared
10686        //   and then later defined.
10687        if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
10688            S->isDeclScope(PrevDecl)) {
10689          Diag(NameLoc, diag::ext_member_redeclared);
10690          Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
10691        }
10692
10693        if (!Invalid) {
10694          // If this is a use, just return the declaration we found.
10695
10696          // FIXME: In the future, return a variant or some other clue
10697          // for the consumer of this Decl to know it doesn't own it.
10698          // For our current ASTs this shouldn't be a problem, but will
10699          // need to be changed with DeclGroups.
10700          if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() ||
10701               getLangOpts().MicrosoftExt)) || TUK == TUK_Friend)
10702            return PrevTagDecl;
10703
10704          // Diagnose attempts to redefine a tag.
10705          if (TUK == TUK_Definition) {
10706            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
10707              // If we're defining a specialization and the previous definition
10708              // is from an implicit instantiation, don't emit an error
10709              // here; we'll catch this in the general case below.
10710              bool IsExplicitSpecializationAfterInstantiation = false;
10711              if (isExplicitSpecialization) {
10712                if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
10713                  IsExplicitSpecializationAfterInstantiation =
10714                    RD->getTemplateSpecializationKind() !=
10715                    TSK_ExplicitSpecialization;
10716                else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
10717                  IsExplicitSpecializationAfterInstantiation =
10718                    ED->getTemplateSpecializationKind() !=
10719                    TSK_ExplicitSpecialization;
10720              }
10721
10722              if (!IsExplicitSpecializationAfterInstantiation) {
10723                // A redeclaration in function prototype scope in C isn't
10724                // visible elsewhere, so merely issue a warning.
10725                if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
10726                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
10727                else
10728                  Diag(NameLoc, diag::err_redefinition) << Name;
10729                Diag(Def->getLocation(), diag::note_previous_definition);
10730                // If this is a redefinition, recover by making this
10731                // struct be anonymous, which will make any later
10732                // references get the previous definition.
10733                Name = 0;
10734                Previous.clear();
10735                Invalid = true;
10736              }
10737            } else {
10738              // If the type is currently being defined, complain
10739              // about a nested redefinition.
10740              const TagType *Tag
10741                = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
10742              if (Tag->isBeingDefined()) {
10743                Diag(NameLoc, diag::err_nested_redefinition) << Name;
10744                Diag(PrevTagDecl->getLocation(),
10745                     diag::note_previous_definition);
10746                Name = 0;
10747                Previous.clear();
10748                Invalid = true;
10749              }
10750            }
10751
10752            // Okay, this is definition of a previously declared or referenced
10753            // tag PrevDecl. We're going to create a new Decl for it.
10754          }
10755        }
10756        // If we get here we have (another) forward declaration or we
10757        // have a definition.  Just create a new decl.
10758
10759      } else {
10760        // If we get here, this is a definition of a new tag type in a nested
10761        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
10762        // new decl/type.  We set PrevDecl to NULL so that the entities
10763        // have distinct types.
10764        Previous.clear();
10765      }
10766      // If we get here, we're going to create a new Decl. If PrevDecl
10767      // is non-NULL, it's a definition of the tag declared by
10768      // PrevDecl. If it's NULL, we have a new definition.
10769
10770
10771    // Otherwise, PrevDecl is not a tag, but was found with tag
10772    // lookup.  This is only actually possible in C++, where a few
10773    // things like templates still live in the tag namespace.
10774    } else {
10775      // Use a better diagnostic if an elaborated-type-specifier
10776      // found the wrong kind of type on the first
10777      // (non-redeclaration) lookup.
10778      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
10779          !Previous.isForRedeclaration()) {
10780        unsigned Kind = 0;
10781        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10782        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10783        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10784        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
10785        Diag(PrevDecl->getLocation(), diag::note_declared_at);
10786        Invalid = true;
10787
10788      // Otherwise, only diagnose if the declaration is in scope.
10789      } else if (!isDeclInScope(PrevDecl, SearchDC, S,
10790                                isExplicitSpecialization)) {
10791        // do nothing
10792
10793      // Diagnose implicit declarations introduced by elaborated types.
10794      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
10795        unsigned Kind = 0;
10796        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
10797        else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
10798        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
10799        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
10800        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10801        Invalid = true;
10802
10803      // Otherwise it's a declaration.  Call out a particularly common
10804      // case here.
10805      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
10806        unsigned Kind = 0;
10807        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
10808        Diag(NameLoc, diag::err_tag_definition_of_typedef)
10809          << Name << Kind << TND->getUnderlyingType();
10810        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
10811        Invalid = true;
10812
10813      // Otherwise, diagnose.
10814      } else {
10815        // The tag name clashes with something else in the target scope,
10816        // issue an error and recover by making this tag be anonymous.
10817        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
10818        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10819        Name = 0;
10820        Invalid = true;
10821      }
10822
10823      // The existing declaration isn't relevant to us; we're in a
10824      // new scope, so clear out the previous declaration.
10825      Previous.clear();
10826    }
10827  }
10828
10829CreateNewDecl:
10830
10831  TagDecl *PrevDecl = 0;
10832  if (Previous.isSingleResult())
10833    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
10834
10835  // If there is an identifier, use the location of the identifier as the
10836  // location of the decl, otherwise use the location of the struct/union
10837  // keyword.
10838  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
10839
10840  // Otherwise, create a new declaration. If there is a previous
10841  // declaration of the same entity, the two will be linked via
10842  // PrevDecl.
10843  TagDecl *New;
10844
10845  bool IsForwardReference = false;
10846  if (Kind == TTK_Enum) {
10847    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10848    // enum X { A, B, C } D;    D should chain to X.
10849    New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
10850                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
10851                           ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
10852    // If this is an undefined enum, warn.
10853    if (TUK != TUK_Definition && !Invalid) {
10854      TagDecl *Def;
10855      if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
10856          cast<EnumDecl>(New)->isFixed()) {
10857        // C++0x: 7.2p2: opaque-enum-declaration.
10858        // Conflicts are diagnosed above. Do nothing.
10859      }
10860      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
10861        Diag(Loc, diag::ext_forward_ref_enum_def)
10862          << New;
10863        Diag(Def->getLocation(), diag::note_previous_definition);
10864      } else {
10865        unsigned DiagID = diag::ext_forward_ref_enum;
10866        if (getLangOpts().MicrosoftMode)
10867          DiagID = diag::ext_ms_forward_ref_enum;
10868        else if (getLangOpts().CPlusPlus)
10869          DiagID = diag::err_forward_ref_enum;
10870        Diag(Loc, DiagID);
10871
10872        // If this is a forward-declared reference to an enumeration, make a
10873        // note of it; we won't actually be introducing the declaration into
10874        // the declaration context.
10875        if (TUK == TUK_Reference)
10876          IsForwardReference = true;
10877      }
10878    }
10879
10880    if (EnumUnderlying) {
10881      EnumDecl *ED = cast<EnumDecl>(New);
10882      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
10883        ED->setIntegerTypeSourceInfo(TI);
10884      else
10885        ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
10886      ED->setPromotionType(ED->getIntegerType());
10887    }
10888
10889  } else {
10890    // struct/union/class
10891
10892    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
10893    // struct X { int A; } D;    D should chain to X.
10894    if (getLangOpts().CPlusPlus) {
10895      // FIXME: Look for a way to use RecordDecl for simple structs.
10896      New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10897                                  cast_or_null<CXXRecordDecl>(PrevDecl));
10898
10899      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
10900        StdBadAlloc = cast<CXXRecordDecl>(New);
10901    } else
10902      New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
10903                               cast_or_null<RecordDecl>(PrevDecl));
10904  }
10905
10906  // Maybe add qualifier info.
10907  if (SS.isNotEmpty()) {
10908    if (SS.isSet()) {
10909      // If this is either a declaration or a definition, check the
10910      // nested-name-specifier against the current context. We don't do this
10911      // for explicit specializations, because they have similar checking
10912      // (with more specific diagnostics) in the call to
10913      // CheckMemberSpecialization, below.
10914      if (!isExplicitSpecialization &&
10915          (TUK == TUK_Definition || TUK == TUK_Declaration) &&
10916          diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc))
10917        Invalid = true;
10918
10919      New->setQualifierInfo(SS.getWithLocInContext(Context));
10920      if (TemplateParameterLists.size() > 0) {
10921        New->setTemplateParameterListsInfo(Context,
10922                                           TemplateParameterLists.size(),
10923                                           TemplateParameterLists.data());
10924      }
10925    }
10926    else
10927      Invalid = true;
10928  }
10929
10930  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
10931    // Add alignment attributes if necessary; these attributes are checked when
10932    // the ASTContext lays out the structure.
10933    //
10934    // It is important for implementing the correct semantics that this
10935    // happen here (in act on tag decl). The #pragma pack stack is
10936    // maintained as a result of parser callbacks which can occur at
10937    // many points during the parsing of a struct declaration (because
10938    // the #pragma tokens are effectively skipped over during the
10939    // parsing of the struct).
10940    if (TUK == TUK_Definition) {
10941      AddAlignmentAttributesForRecord(RD);
10942      AddMsStructLayoutForRecord(RD);
10943    }
10944  }
10945
10946  if (ModulePrivateLoc.isValid()) {
10947    if (isExplicitSpecialization)
10948      Diag(New->getLocation(), diag::err_module_private_specialization)
10949        << 2
10950        << FixItHint::CreateRemoval(ModulePrivateLoc);
10951    // __module_private__ does not apply to local classes. However, we only
10952    // diagnose this as an error when the declaration specifiers are
10953    // freestanding. Here, we just ignore the __module_private__.
10954    else if (!SearchDC->isFunctionOrMethod())
10955      New->setModulePrivate();
10956  }
10957
10958  // If this is a specialization of a member class (of a class template),
10959  // check the specialization.
10960  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
10961    Invalid = true;
10962
10963  if (Invalid)
10964    New->setInvalidDecl();
10965
10966  if (Attr)
10967    ProcessDeclAttributeList(S, New, Attr);
10968
10969  // If we're declaring or defining a tag in function prototype scope
10970  // in C, note that this type can only be used within the function.
10971  if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus)
10972    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
10973
10974  // Set the lexical context. If the tag has a C++ scope specifier, the
10975  // lexical context will be different from the semantic context.
10976  New->setLexicalDeclContext(CurContext);
10977
10978  // Mark this as a friend decl if applicable.
10979  // In Microsoft mode, a friend declaration also acts as a forward
10980  // declaration so we always pass true to setObjectOfFriendDecl to make
10981  // the tag name visible.
10982  if (TUK == TUK_Friend)
10983    New->setObjectOfFriendDecl(!FriendSawTagOutsideEnclosingNamespace &&
10984                               getLangOpts().MicrosoftExt);
10985
10986  // Set the access specifier.
10987  if (!Invalid && SearchDC->isRecord())
10988    SetMemberAccessSpecifier(New, PrevDecl, AS);
10989
10990  if (TUK == TUK_Definition)
10991    New->startDefinition();
10992
10993  // If this has an identifier, add it to the scope stack.
10994  if (TUK == TUK_Friend) {
10995    // We might be replacing an existing declaration in the lookup tables;
10996    // if so, borrow its access specifier.
10997    if (PrevDecl)
10998      New->setAccess(PrevDecl->getAccess());
10999
11000    DeclContext *DC = New->getDeclContext()->getRedeclContext();
11001    DC->makeDeclVisibleInContext(New);
11002    if (Name) // can be null along some error paths
11003      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
11004        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
11005  } else if (Name) {
11006    S = getNonFieldDeclScope(S);
11007    PushOnScopeChains(New, S, !IsForwardReference);
11008    if (IsForwardReference)
11009      SearchDC->makeDeclVisibleInContext(New);
11010
11011  } else {
11012    CurContext->addDecl(New);
11013  }
11014
11015  // If this is the C FILE type, notify the AST context.
11016  if (IdentifierInfo *II = New->getIdentifier())
11017    if (!New->isInvalidDecl() &&
11018        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
11019        II->isStr("FILE"))
11020      Context.setFILEDecl(New);
11021
11022  // If we were in function prototype scope (and not in C++ mode), add this
11023  // tag to the list of decls to inject into the function definition scope.
11024  if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus &&
11025      InFunctionDeclarator && Name)
11026    DeclsInPrototypeScope.push_back(New);
11027
11028  if (PrevDecl)
11029    mergeDeclAttributes(New, PrevDecl);
11030
11031  // If there's a #pragma GCC visibility in scope, set the visibility of this
11032  // record.
11033  AddPushedVisibilityAttribute(New);
11034
11035  OwnedDecl = true;
11036  // In C++, don't return an invalid declaration. We can't recover well from
11037  // the cases where we make the type anonymous.
11038  return (Invalid && getLangOpts().CPlusPlus) ? 0 : New;
11039}
11040
11041void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
11042  AdjustDeclIfTemplate(TagD);
11043  TagDecl *Tag = cast<TagDecl>(TagD);
11044
11045  // Enter the tag context.
11046  PushDeclContext(S, Tag);
11047
11048  ActOnDocumentableDecl(TagD);
11049
11050  // If there's a #pragma GCC visibility in scope, set the visibility of this
11051  // record.
11052  AddPushedVisibilityAttribute(Tag);
11053}
11054
11055Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
11056  assert(isa<ObjCContainerDecl>(IDecl) &&
11057         "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
11058  DeclContext *OCD = cast<DeclContext>(IDecl);
11059  assert(getContainingDC(OCD) == CurContext &&
11060      "The next DeclContext should be lexically contained in the current one.");
11061  CurContext = OCD;
11062  return IDecl;
11063}
11064
11065void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
11066                                           SourceLocation FinalLoc,
11067                                           bool IsFinalSpelledSealed,
11068                                           SourceLocation LBraceLoc) {
11069  AdjustDeclIfTemplate(TagD);
11070  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
11071
11072  FieldCollector->StartClass();
11073
11074  if (!Record->getIdentifier())
11075    return;
11076
11077  if (FinalLoc.isValid())
11078    Record->addAttr(new (Context)
11079                    FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
11080
11081  // C++ [class]p2:
11082  //   [...] The class-name is also inserted into the scope of the
11083  //   class itself; this is known as the injected-class-name. For
11084  //   purposes of access checking, the injected-class-name is treated
11085  //   as if it were a public member name.
11086  CXXRecordDecl *InjectedClassName
11087    = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
11088                            Record->getLocStart(), Record->getLocation(),
11089                            Record->getIdentifier(),
11090                            /*PrevDecl=*/0,
11091                            /*DelayTypeCreation=*/true);
11092  Context.getTypeDeclType(InjectedClassName, Record);
11093  InjectedClassName->setImplicit();
11094  InjectedClassName->setAccess(AS_public);
11095  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
11096      InjectedClassName->setDescribedClassTemplate(Template);
11097  PushOnScopeChains(InjectedClassName, S);
11098  assert(InjectedClassName->isInjectedClassName() &&
11099         "Broken injected-class-name");
11100}
11101
11102void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
11103                                    SourceLocation RBraceLoc) {
11104  AdjustDeclIfTemplate(TagD);
11105  TagDecl *Tag = cast<TagDecl>(TagD);
11106  Tag->setRBraceLoc(RBraceLoc);
11107
11108  // Make sure we "complete" the definition even it is invalid.
11109  if (Tag->isBeingDefined()) {
11110    assert(Tag->isInvalidDecl() && "We should already have completed it");
11111    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11112      RD->completeDefinition();
11113  }
11114
11115  if (isa<CXXRecordDecl>(Tag))
11116    FieldCollector->FinishClass();
11117
11118  // Exit this scope of this tag's definition.
11119  PopDeclContext();
11120
11121  if (getCurLexicalContext()->isObjCContainer() &&
11122      Tag->getDeclContext()->isFileContext())
11123    Tag->setTopLevelDeclInObjCContainer();
11124
11125  // Notify the consumer that we've defined a tag.
11126  if (!Tag->isInvalidDecl())
11127    Consumer.HandleTagDeclDefinition(Tag);
11128}
11129
11130void Sema::ActOnObjCContainerFinishDefinition() {
11131  // Exit this scope of this interface definition.
11132  PopDeclContext();
11133}
11134
11135void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
11136  assert(DC == CurContext && "Mismatch of container contexts");
11137  OriginalLexicalContext = DC;
11138  ActOnObjCContainerFinishDefinition();
11139}
11140
11141void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
11142  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
11143  OriginalLexicalContext = 0;
11144}
11145
11146void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
11147  AdjustDeclIfTemplate(TagD);
11148  TagDecl *Tag = cast<TagDecl>(TagD);
11149  Tag->setInvalidDecl();
11150
11151  // Make sure we "complete" the definition even it is invalid.
11152  if (Tag->isBeingDefined()) {
11153    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
11154      RD->completeDefinition();
11155  }
11156
11157  // We're undoing ActOnTagStartDefinition here, not
11158  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
11159  // the FieldCollector.
11160
11161  PopDeclContext();
11162}
11163
11164// Note that FieldName may be null for anonymous bitfields.
11165ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
11166                                IdentifierInfo *FieldName,
11167                                QualType FieldTy, bool IsMsStruct,
11168                                Expr *BitWidth, bool *ZeroWidth) {
11169  // Default to true; that shouldn't confuse checks for emptiness
11170  if (ZeroWidth)
11171    *ZeroWidth = true;
11172
11173  // C99 6.7.2.1p4 - verify the field type.
11174  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
11175  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
11176    // Handle incomplete types with specific error.
11177    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
11178      return ExprError();
11179    if (FieldName)
11180      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
11181        << FieldName << FieldTy << BitWidth->getSourceRange();
11182    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
11183      << FieldTy << BitWidth->getSourceRange();
11184  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
11185                                             UPPC_BitFieldWidth))
11186    return ExprError();
11187
11188  // If the bit-width is type- or value-dependent, don't try to check
11189  // it now.
11190  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
11191    return Owned(BitWidth);
11192
11193  llvm::APSInt Value;
11194  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
11195  if (ICE.isInvalid())
11196    return ICE;
11197  BitWidth = ICE.take();
11198
11199  if (Value != 0 && ZeroWidth)
11200    *ZeroWidth = false;
11201
11202  // Zero-width bitfield is ok for anonymous field.
11203  if (Value == 0 && FieldName)
11204    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
11205
11206  if (Value.isSigned() && Value.isNegative()) {
11207    if (FieldName)
11208      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
11209               << FieldName << Value.toString(10);
11210    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
11211      << Value.toString(10);
11212  }
11213
11214  if (!FieldTy->isDependentType()) {
11215    uint64_t TypeSize = Context.getTypeSize(FieldTy);
11216    if (Value.getZExtValue() > TypeSize) {
11217      if (!getLangOpts().CPlusPlus || IsMsStruct) {
11218        if (FieldName)
11219          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
11220            << FieldName << (unsigned)Value.getZExtValue()
11221            << (unsigned)TypeSize;
11222
11223        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
11224          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11225      }
11226
11227      if (FieldName)
11228        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
11229          << FieldName << (unsigned)Value.getZExtValue()
11230          << (unsigned)TypeSize;
11231      else
11232        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
11233          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
11234    }
11235  }
11236
11237  return Owned(BitWidth);
11238}
11239
11240/// ActOnField - Each field of a C struct/union is passed into this in order
11241/// to create a FieldDecl object for it.
11242Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
11243                       Declarator &D, Expr *BitfieldWidth) {
11244  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
11245                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
11246                               /*InitStyle=*/ICIS_NoInit, AS_public);
11247  return Res;
11248}
11249
11250/// HandleField - Analyze a field of a C struct or a C++ data member.
11251///
11252FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
11253                             SourceLocation DeclStart,
11254                             Declarator &D, Expr *BitWidth,
11255                             InClassInitStyle InitStyle,
11256                             AccessSpecifier AS) {
11257  IdentifierInfo *II = D.getIdentifier();
11258  SourceLocation Loc = DeclStart;
11259  if (II) Loc = D.getIdentifierLoc();
11260
11261  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11262  QualType T = TInfo->getType();
11263  if (getLangOpts().CPlusPlus) {
11264    CheckExtraCXXDefaultArguments(D);
11265
11266    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
11267                                        UPPC_DataMemberType)) {
11268      D.setInvalidType();
11269      T = Context.IntTy;
11270      TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
11271    }
11272  }
11273
11274  // TR 18037 does not allow fields to be declared with address spaces.
11275  if (T.getQualifiers().hasAddressSpace()) {
11276    Diag(Loc, diag::err_field_with_address_space);
11277    D.setInvalidType();
11278  }
11279
11280  // OpenCL 1.2 spec, s6.9 r:
11281  // The event type cannot be used to declare a structure or union field.
11282  if (LangOpts.OpenCL && T->isEventT()) {
11283    Diag(Loc, diag::err_event_t_struct_field);
11284    D.setInvalidType();
11285  }
11286
11287  DiagnoseFunctionSpecifiers(D.getDeclSpec());
11288
11289  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
11290    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
11291         diag::err_invalid_thread)
11292      << DeclSpec::getSpecifierName(TSCS);
11293
11294  // Check to see if this name was declared as a member previously
11295  NamedDecl *PrevDecl = 0;
11296  LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
11297  LookupName(Previous, S);
11298  switch (Previous.getResultKind()) {
11299    case LookupResult::Found:
11300    case LookupResult::FoundUnresolvedValue:
11301      PrevDecl = Previous.getAsSingle<NamedDecl>();
11302      break;
11303
11304    case LookupResult::FoundOverloaded:
11305      PrevDecl = Previous.getRepresentativeDecl();
11306      break;
11307
11308    case LookupResult::NotFound:
11309    case LookupResult::NotFoundInCurrentInstantiation:
11310    case LookupResult::Ambiguous:
11311      break;
11312  }
11313  Previous.suppressDiagnostics();
11314
11315  if (PrevDecl && PrevDecl->isTemplateParameter()) {
11316    // Maybe we will complain about the shadowed template parameter.
11317    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11318    // Just pretend that we didn't see the previous declaration.
11319    PrevDecl = 0;
11320  }
11321
11322  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
11323    PrevDecl = 0;
11324
11325  bool Mutable
11326    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
11327  SourceLocation TSSL = D.getLocStart();
11328  FieldDecl *NewFD
11329    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
11330                     TSSL, AS, PrevDecl, &D);
11331
11332  if (NewFD->isInvalidDecl())
11333    Record->setInvalidDecl();
11334
11335  if (D.getDeclSpec().isModulePrivateSpecified())
11336    NewFD->setModulePrivate();
11337
11338  if (NewFD->isInvalidDecl() && PrevDecl) {
11339    // Don't introduce NewFD into scope; there's already something
11340    // with the same name in the same scope.
11341  } else if (II) {
11342    PushOnScopeChains(NewFD, S);
11343  } else
11344    Record->addDecl(NewFD);
11345
11346  return NewFD;
11347}
11348
11349/// \brief Build a new FieldDecl and check its well-formedness.
11350///
11351/// This routine builds a new FieldDecl given the fields name, type,
11352/// record, etc. \p PrevDecl should refer to any previous declaration
11353/// with the same name and in the same scope as the field to be
11354/// created.
11355///
11356/// \returns a new FieldDecl.
11357///
11358/// \todo The Declarator argument is a hack. It will be removed once
11359FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
11360                                TypeSourceInfo *TInfo,
11361                                RecordDecl *Record, SourceLocation Loc,
11362                                bool Mutable, Expr *BitWidth,
11363                                InClassInitStyle InitStyle,
11364                                SourceLocation TSSL,
11365                                AccessSpecifier AS, NamedDecl *PrevDecl,
11366                                Declarator *D) {
11367  IdentifierInfo *II = Name.getAsIdentifierInfo();
11368  bool InvalidDecl = false;
11369  if (D) InvalidDecl = D->isInvalidType();
11370
11371  // If we receive a broken type, recover by assuming 'int' and
11372  // marking this declaration as invalid.
11373  if (T.isNull()) {
11374    InvalidDecl = true;
11375    T = Context.IntTy;
11376  }
11377
11378  QualType EltTy = Context.getBaseElementType(T);
11379  if (!EltTy->isDependentType()) {
11380    if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
11381      // Fields of incomplete type force their record to be invalid.
11382      Record->setInvalidDecl();
11383      InvalidDecl = true;
11384    } else {
11385      NamedDecl *Def;
11386      EltTy->isIncompleteType(&Def);
11387      if (Def && Def->isInvalidDecl()) {
11388        Record->setInvalidDecl();
11389        InvalidDecl = true;
11390      }
11391    }
11392  }
11393
11394  // OpenCL v1.2 s6.9.c: bitfields are not supported.
11395  if (BitWidth && getLangOpts().OpenCL) {
11396    Diag(Loc, diag::err_opencl_bitfields);
11397    InvalidDecl = true;
11398  }
11399
11400  // C99 6.7.2.1p8: A member of a structure or union may have any type other
11401  // than a variably modified type.
11402  if (!InvalidDecl && T->isVariablyModifiedType()) {
11403    bool SizeIsNegative;
11404    llvm::APSInt Oversized;
11405
11406    TypeSourceInfo *FixedTInfo =
11407      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
11408                                                    SizeIsNegative,
11409                                                    Oversized);
11410    if (FixedTInfo) {
11411      Diag(Loc, diag::warn_illegal_constant_array_size);
11412      TInfo = FixedTInfo;
11413      T = FixedTInfo->getType();
11414    } else {
11415      if (SizeIsNegative)
11416        Diag(Loc, diag::err_typecheck_negative_array_size);
11417      else if (Oversized.getBoolValue())
11418        Diag(Loc, diag::err_array_too_large)
11419          << Oversized.toString(10);
11420      else
11421        Diag(Loc, diag::err_typecheck_field_variable_size);
11422      InvalidDecl = true;
11423    }
11424  }
11425
11426  // Fields can not have abstract class types
11427  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
11428                                             diag::err_abstract_type_in_decl,
11429                                             AbstractFieldType))
11430    InvalidDecl = true;
11431
11432  bool ZeroWidth = false;
11433  // If this is declared as a bit-field, check the bit-field.
11434  if (!InvalidDecl && BitWidth) {
11435    BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
11436                              &ZeroWidth).take();
11437    if (!BitWidth) {
11438      InvalidDecl = true;
11439      BitWidth = 0;
11440      ZeroWidth = false;
11441    }
11442  }
11443
11444  // Check that 'mutable' is consistent with the type of the declaration.
11445  if (!InvalidDecl && Mutable) {
11446    unsigned DiagID = 0;
11447    if (T->isReferenceType())
11448      DiagID = diag::err_mutable_reference;
11449    else if (T.isConstQualified())
11450      DiagID = diag::err_mutable_const;
11451
11452    if (DiagID) {
11453      SourceLocation ErrLoc = Loc;
11454      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
11455        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
11456      Diag(ErrLoc, DiagID);
11457      Mutable = false;
11458      InvalidDecl = true;
11459    }
11460  }
11461
11462  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
11463                                       BitWidth, Mutable, InitStyle);
11464  if (InvalidDecl)
11465    NewFD->setInvalidDecl();
11466
11467  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
11468    Diag(Loc, diag::err_duplicate_member) << II;
11469    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11470    NewFD->setInvalidDecl();
11471  }
11472
11473  if (!InvalidDecl && getLangOpts().CPlusPlus) {
11474    if (Record->isUnion()) {
11475      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11476        CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
11477        if (RDecl->getDefinition()) {
11478          // C++ [class.union]p1: An object of a class with a non-trivial
11479          // constructor, a non-trivial copy constructor, a non-trivial
11480          // destructor, or a non-trivial copy assignment operator
11481          // cannot be a member of a union, nor can an array of such
11482          // objects.
11483          if (CheckNontrivialField(NewFD))
11484            NewFD->setInvalidDecl();
11485        }
11486      }
11487
11488      // C++ [class.union]p1: If a union contains a member of reference type,
11489      // the program is ill-formed, except when compiling with MSVC extensions
11490      // enabled.
11491      if (EltTy->isReferenceType()) {
11492        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
11493                                    diag::ext_union_member_of_reference_type :
11494                                    diag::err_union_member_of_reference_type)
11495          << NewFD->getDeclName() << EltTy;
11496        if (!getLangOpts().MicrosoftExt)
11497          NewFD->setInvalidDecl();
11498      }
11499    }
11500  }
11501
11502  // FIXME: We need to pass in the attributes given an AST
11503  // representation, not a parser representation.
11504  if (D) {
11505    // FIXME: The current scope is almost... but not entirely... correct here.
11506    ProcessDeclAttributes(getCurScope(), NewFD, *D);
11507
11508    if (NewFD->hasAttrs())
11509      CheckAlignasUnderalignment(NewFD);
11510  }
11511
11512  // In auto-retain/release, infer strong retension for fields of
11513  // retainable type.
11514  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
11515    NewFD->setInvalidDecl();
11516
11517  if (T.isObjCGCWeak())
11518    Diag(Loc, diag::warn_attribute_weak_on_field);
11519
11520  NewFD->setAccess(AS);
11521  return NewFD;
11522}
11523
11524bool Sema::CheckNontrivialField(FieldDecl *FD) {
11525  assert(FD);
11526  assert(getLangOpts().CPlusPlus && "valid check only for C++");
11527
11528  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
11529    return false;
11530
11531  QualType EltTy = Context.getBaseElementType(FD->getType());
11532  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
11533    CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
11534    if (RDecl->getDefinition()) {
11535      // We check for copy constructors before constructors
11536      // because otherwise we'll never get complaints about
11537      // copy constructors.
11538
11539      CXXSpecialMember member = CXXInvalid;
11540      // We're required to check for any non-trivial constructors. Since the
11541      // implicit default constructor is suppressed if there are any
11542      // user-declared constructors, we just need to check that there is a
11543      // trivial default constructor and a trivial copy constructor. (We don't
11544      // worry about move constructors here, since this is a C++98 check.)
11545      if (RDecl->hasNonTrivialCopyConstructor())
11546        member = CXXCopyConstructor;
11547      else if (!RDecl->hasTrivialDefaultConstructor())
11548        member = CXXDefaultConstructor;
11549      else if (RDecl->hasNonTrivialCopyAssignment())
11550        member = CXXCopyAssignment;
11551      else if (RDecl->hasNonTrivialDestructor())
11552        member = CXXDestructor;
11553
11554      if (member != CXXInvalid) {
11555        if (!getLangOpts().CPlusPlus11 &&
11556            getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
11557          // Objective-C++ ARC: it is an error to have a non-trivial field of
11558          // a union. However, system headers in Objective-C programs
11559          // occasionally have Objective-C lifetime objects within unions,
11560          // and rather than cause the program to fail, we make those
11561          // members unavailable.
11562          SourceLocation Loc = FD->getLocation();
11563          if (getSourceManager().isInSystemHeader(Loc)) {
11564            if (!FD->hasAttr<UnavailableAttr>())
11565              FD->addAttr(new (Context) UnavailableAttr(Loc, Context,
11566                                  "this system field has retaining ownership"));
11567            return false;
11568          }
11569        }
11570
11571        Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
11572               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
11573               diag::err_illegal_union_or_anon_struct_member)
11574          << (int)FD->getParent()->isUnion() << FD->getDeclName() << member;
11575        DiagnoseNontrivial(RDecl, member);
11576        return !getLangOpts().CPlusPlus11;
11577      }
11578    }
11579  }
11580
11581  return false;
11582}
11583
11584/// TranslateIvarVisibility - Translate visibility from a token ID to an
11585///  AST enum value.
11586static ObjCIvarDecl::AccessControl
11587TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
11588  switch (ivarVisibility) {
11589  default: llvm_unreachable("Unknown visitibility kind");
11590  case tok::objc_private: return ObjCIvarDecl::Private;
11591  case tok::objc_public: return ObjCIvarDecl::Public;
11592  case tok::objc_protected: return ObjCIvarDecl::Protected;
11593  case tok::objc_package: return ObjCIvarDecl::Package;
11594  }
11595}
11596
11597/// ActOnIvar - Each ivar field of an objective-c class is passed into this
11598/// in order to create an IvarDecl object for it.
11599Decl *Sema::ActOnIvar(Scope *S,
11600                                SourceLocation DeclStart,
11601                                Declarator &D, Expr *BitfieldWidth,
11602                                tok::ObjCKeywordKind Visibility) {
11603
11604  IdentifierInfo *II = D.getIdentifier();
11605  Expr *BitWidth = (Expr*)BitfieldWidth;
11606  SourceLocation Loc = DeclStart;
11607  if (II) Loc = D.getIdentifierLoc();
11608
11609  // FIXME: Unnamed fields can be handled in various different ways, for
11610  // example, unnamed unions inject all members into the struct namespace!
11611
11612  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11613  QualType T = TInfo->getType();
11614
11615  if (BitWidth) {
11616    // 6.7.2.1p3, 6.7.2.1p4
11617    BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).take();
11618    if (!BitWidth)
11619      D.setInvalidType();
11620  } else {
11621    // Not a bitfield.
11622
11623    // validate II.
11624
11625  }
11626  if (T->isReferenceType()) {
11627    Diag(Loc, diag::err_ivar_reference_type);
11628    D.setInvalidType();
11629  }
11630  // C99 6.7.2.1p8: A member of a structure or union may have any type other
11631  // than a variably modified type.
11632  else if (T->isVariablyModifiedType()) {
11633    Diag(Loc, diag::err_typecheck_ivar_variable_size);
11634    D.setInvalidType();
11635  }
11636
11637  // Get the visibility (access control) for this ivar.
11638  ObjCIvarDecl::AccessControl ac =
11639    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
11640                                        : ObjCIvarDecl::None;
11641  // Must set ivar's DeclContext to its enclosing interface.
11642  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
11643  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
11644    return 0;
11645  ObjCContainerDecl *EnclosingContext;
11646  if (ObjCImplementationDecl *IMPDecl =
11647      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
11648    if (LangOpts.ObjCRuntime.isFragile()) {
11649    // Case of ivar declared in an implementation. Context is that of its class.
11650      EnclosingContext = IMPDecl->getClassInterface();
11651      assert(EnclosingContext && "Implementation has no class interface!");
11652    }
11653    else
11654      EnclosingContext = EnclosingDecl;
11655  } else {
11656    if (ObjCCategoryDecl *CDecl =
11657        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
11658      if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
11659        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
11660        return 0;
11661      }
11662    }
11663    EnclosingContext = EnclosingDecl;
11664  }
11665
11666  // Construct the decl.
11667  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
11668                                             DeclStart, Loc, II, T,
11669                                             TInfo, ac, (Expr *)BitfieldWidth);
11670
11671  if (II) {
11672    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
11673                                           ForRedeclaration);
11674    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
11675        && !isa<TagDecl>(PrevDecl)) {
11676      Diag(Loc, diag::err_duplicate_member) << II;
11677      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11678      NewID->setInvalidDecl();
11679    }
11680  }
11681
11682  // Process attributes attached to the ivar.
11683  ProcessDeclAttributes(S, NewID, D);
11684
11685  if (D.isInvalidType())
11686    NewID->setInvalidDecl();
11687
11688  // In ARC, infer 'retaining' for ivars of retainable type.
11689  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
11690    NewID->setInvalidDecl();
11691
11692  if (D.getDeclSpec().isModulePrivateSpecified())
11693    NewID->setModulePrivate();
11694
11695  if (II) {
11696    // FIXME: When interfaces are DeclContexts, we'll need to add
11697    // these to the interface.
11698    S->AddDecl(NewID);
11699    IdResolver.AddDecl(NewID);
11700  }
11701
11702  if (LangOpts.ObjCRuntime.isNonFragile() &&
11703      !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
11704    Diag(Loc, diag::warn_ivars_in_interface);
11705
11706  return NewID;
11707}
11708
11709/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
11710/// class and class extensions. For every class \@interface and class
11711/// extension \@interface, if the last ivar is a bitfield of any type,
11712/// then add an implicit `char :0` ivar to the end of that interface.
11713void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
11714                             SmallVectorImpl<Decl *> &AllIvarDecls) {
11715  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
11716    return;
11717
11718  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
11719  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
11720
11721  if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
11722    return;
11723  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
11724  if (!ID) {
11725    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
11726      if (!CD->IsClassExtension())
11727        return;
11728    }
11729    // No need to add this to end of @implementation.
11730    else
11731      return;
11732  }
11733  // All conditions are met. Add a new bitfield to the tail end of ivars.
11734  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
11735  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
11736
11737  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
11738                              DeclLoc, DeclLoc, 0,
11739                              Context.CharTy,
11740                              Context.getTrivialTypeSourceInfo(Context.CharTy,
11741                                                               DeclLoc),
11742                              ObjCIvarDecl::Private, BW,
11743                              true);
11744  AllIvarDecls.push_back(Ivar);
11745}
11746
11747void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
11748                       ArrayRef<Decl *> Fields, SourceLocation LBrac,
11749                       SourceLocation RBrac, AttributeList *Attr) {
11750  assert(EnclosingDecl && "missing record or interface decl");
11751
11752  // If this is an Objective-C @implementation or category and we have
11753  // new fields here we should reset the layout of the interface since
11754  // it will now change.
11755  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
11756    ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
11757    switch (DC->getKind()) {
11758    default: break;
11759    case Decl::ObjCCategory:
11760      Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
11761      break;
11762    case Decl::ObjCImplementation:
11763      Context.
11764        ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
11765      break;
11766    }
11767  }
11768
11769  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
11770
11771  // Start counting up the number of named members; make sure to include
11772  // members of anonymous structs and unions in the total.
11773  unsigned NumNamedMembers = 0;
11774  if (Record) {
11775    for (RecordDecl::decl_iterator i = Record->decls_begin(),
11776                                   e = Record->decls_end(); i != e; i++) {
11777      if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i))
11778        if (IFD->getDeclName())
11779          ++NumNamedMembers;
11780    }
11781  }
11782
11783  // Verify that all the fields are okay.
11784  SmallVector<FieldDecl*, 32> RecFields;
11785
11786  bool ARCErrReported = false;
11787  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
11788       i != end; ++i) {
11789    FieldDecl *FD = cast<FieldDecl>(*i);
11790
11791    // Get the type for the field.
11792    const Type *FDTy = FD->getType().getTypePtr();
11793
11794    if (!FD->isAnonymousStructOrUnion()) {
11795      // Remember all fields written by the user.
11796      RecFields.push_back(FD);
11797    }
11798
11799    // If the field is already invalid for some reason, don't emit more
11800    // diagnostics about it.
11801    if (FD->isInvalidDecl()) {
11802      EnclosingDecl->setInvalidDecl();
11803      continue;
11804    }
11805
11806    // C99 6.7.2.1p2:
11807    //   A structure or union shall not contain a member with
11808    //   incomplete or function type (hence, a structure shall not
11809    //   contain an instance of itself, but may contain a pointer to
11810    //   an instance of itself), except that the last member of a
11811    //   structure with more than one named member may have incomplete
11812    //   array type; such a structure (and any union containing,
11813    //   possibly recursively, a member that is such a structure)
11814    //   shall not be a member of a structure or an element of an
11815    //   array.
11816    if (FDTy->isFunctionType()) {
11817      // Field declared as a function.
11818      Diag(FD->getLocation(), diag::err_field_declared_as_function)
11819        << FD->getDeclName();
11820      FD->setInvalidDecl();
11821      EnclosingDecl->setInvalidDecl();
11822      continue;
11823    } else if (FDTy->isIncompleteArrayType() && Record &&
11824               ((i + 1 == Fields.end() && !Record->isUnion()) ||
11825                ((getLangOpts().MicrosoftExt ||
11826                  getLangOpts().CPlusPlus) &&
11827                 (i + 1 == Fields.end() || Record->isUnion())))) {
11828      // Flexible array member.
11829      // Microsoft and g++ is more permissive regarding flexible array.
11830      // It will accept flexible array in union and also
11831      // as the sole element of a struct/class.
11832      unsigned DiagID = 0;
11833      if (Record->isUnion())
11834        DiagID = getLangOpts().MicrosoftExt
11835                     ? diag::ext_flexible_array_union_ms
11836                     : getLangOpts().CPlusPlus
11837                           ? diag::ext_flexible_array_union_gnu
11838                           : diag::err_flexible_array_union;
11839      else if (Fields.size() == 1)
11840        DiagID = getLangOpts().MicrosoftExt
11841                     ? diag::ext_flexible_array_empty_aggregate_ms
11842                     : getLangOpts().CPlusPlus
11843                           ? diag::ext_flexible_array_empty_aggregate_gnu
11844                           : NumNamedMembers < 1
11845                                 ? diag::err_flexible_array_empty_aggregate
11846                                 : 0;
11847
11848      if (DiagID)
11849        Diag(FD->getLocation(), DiagID) << FD->getDeclName()
11850                                        << Record->getTagKind();
11851      // While the layout of types that contain virtual bases is not specified
11852      // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
11853      // virtual bases after the derived members.  This would make a flexible
11854      // array member declared at the end of an object not adjacent to the end
11855      // of the type.
11856      if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
11857        if (RD->getNumVBases() != 0)
11858          Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
11859            << FD->getDeclName() << Record->getTagKind();
11860      if (!getLangOpts().C99)
11861        Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
11862          << FD->getDeclName() << Record->getTagKind();
11863
11864      if (!FD->getType()->isDependentType() &&
11865          !Context.getBaseElementType(FD->getType()).isPODType(Context)) {
11866        Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type)
11867          << FD->getDeclName() << FD->getType();
11868        FD->setInvalidDecl();
11869        EnclosingDecl->setInvalidDecl();
11870        continue;
11871      }
11872      // Okay, we have a legal flexible array member at the end of the struct.
11873      if (Record)
11874        Record->setHasFlexibleArrayMember(true);
11875    } else if (!FDTy->isDependentType() &&
11876               RequireCompleteType(FD->getLocation(), FD->getType(),
11877                                   diag::err_field_incomplete)) {
11878      // Incomplete type
11879      FD->setInvalidDecl();
11880      EnclosingDecl->setInvalidDecl();
11881      continue;
11882    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
11883      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
11884        // If this is a member of a union, then entire union becomes "flexible".
11885        if (Record && Record->isUnion()) {
11886          Record->setHasFlexibleArrayMember(true);
11887        } else {
11888          // If this is a struct/class and this is not the last element, reject
11889          // it.  Note that GCC supports variable sized arrays in the middle of
11890          // structures.
11891          if (i + 1 != Fields.end())
11892            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
11893              << FD->getDeclName() << FD->getType();
11894          else {
11895            // We support flexible arrays at the end of structs in
11896            // other structs as an extension.
11897            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
11898              << FD->getDeclName();
11899            if (Record)
11900              Record->setHasFlexibleArrayMember(true);
11901          }
11902        }
11903      }
11904      if (isa<ObjCContainerDecl>(EnclosingDecl) &&
11905          RequireNonAbstractType(FD->getLocation(), FD->getType(),
11906                                 diag::err_abstract_type_in_decl,
11907                                 AbstractIvarType)) {
11908        // Ivars can not have abstract class types
11909        FD->setInvalidDecl();
11910      }
11911      if (Record && FDTTy->getDecl()->hasObjectMember())
11912        Record->setHasObjectMember(true);
11913      if (Record && FDTTy->getDecl()->hasVolatileMember())
11914        Record->setHasVolatileMember(true);
11915    } else if (FDTy->isObjCObjectType()) {
11916      /// A field cannot be an Objective-c object
11917      Diag(FD->getLocation(), diag::err_statically_allocated_object)
11918        << FixItHint::CreateInsertion(FD->getLocation(), "*");
11919      QualType T = Context.getObjCObjectPointerType(FD->getType());
11920      FD->setType(T);
11921    } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
11922               (!getLangOpts().CPlusPlus || Record->isUnion())) {
11923      // It's an error in ARC if a field has lifetime.
11924      // We don't want to report this in a system header, though,
11925      // so we just make the field unavailable.
11926      // FIXME: that's really not sufficient; we need to make the type
11927      // itself invalid to, say, initialize or copy.
11928      QualType T = FD->getType();
11929      Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
11930      if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
11931        SourceLocation loc = FD->getLocation();
11932        if (getSourceManager().isInSystemHeader(loc)) {
11933          if (!FD->hasAttr<UnavailableAttr>()) {
11934            FD->addAttr(new (Context) UnavailableAttr(loc, Context,
11935                              "this system field has retaining ownership"));
11936          }
11937        } else {
11938          Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
11939            << T->isBlockPointerType() << Record->getTagKind();
11940        }
11941        ARCErrReported = true;
11942      }
11943    } else if (getLangOpts().ObjC1 &&
11944               getLangOpts().getGC() != LangOptions::NonGC &&
11945               Record && !Record->hasObjectMember()) {
11946      if (FD->getType()->isObjCObjectPointerType() ||
11947          FD->getType().isObjCGCStrong())
11948        Record->setHasObjectMember(true);
11949      else if (Context.getAsArrayType(FD->getType())) {
11950        QualType BaseType = Context.getBaseElementType(FD->getType());
11951        if (BaseType->isRecordType() &&
11952            BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
11953          Record->setHasObjectMember(true);
11954        else if (BaseType->isObjCObjectPointerType() ||
11955                 BaseType.isObjCGCStrong())
11956               Record->setHasObjectMember(true);
11957      }
11958    }
11959    if (Record && FD->getType().isVolatileQualified())
11960      Record->setHasVolatileMember(true);
11961    // Keep track of the number of named members.
11962    if (FD->getIdentifier())
11963      ++NumNamedMembers;
11964  }
11965
11966  // Okay, we successfully defined 'Record'.
11967  if (Record) {
11968    bool Completed = false;
11969    if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
11970      if (!CXXRecord->isInvalidDecl()) {
11971        // Set access bits correctly on the directly-declared conversions.
11972        for (CXXRecordDecl::conversion_iterator
11973               I = CXXRecord->conversion_begin(),
11974               E = CXXRecord->conversion_end(); I != E; ++I)
11975          I.setAccess((*I)->getAccess());
11976
11977        if (!CXXRecord->isDependentType()) {
11978          if (CXXRecord->hasUserDeclaredDestructor()) {
11979            // Adjust user-defined destructor exception spec.
11980            if (getLangOpts().CPlusPlus11)
11981              AdjustDestructorExceptionSpec(CXXRecord,
11982                                            CXXRecord->getDestructor());
11983
11984            // The Microsoft ABI requires that we perform the destructor body
11985            // checks (i.e. operator delete() lookup) at every declaration, as
11986            // any translation unit may need to emit a deleting destructor.
11987            if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11988              CheckDestructor(CXXRecord->getDestructor());
11989          }
11990
11991          // Add any implicitly-declared members to this class.
11992          AddImplicitlyDeclaredMembersToClass(CXXRecord);
11993
11994          // If we have virtual base classes, we may end up finding multiple
11995          // final overriders for a given virtual function. Check for this
11996          // problem now.
11997          if (CXXRecord->getNumVBases()) {
11998            CXXFinalOverriderMap FinalOverriders;
11999            CXXRecord->getFinalOverriders(FinalOverriders);
12000
12001            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
12002                                             MEnd = FinalOverriders.end();
12003                 M != MEnd; ++M) {
12004              for (OverridingMethods::iterator SO = M->second.begin(),
12005                                            SOEnd = M->second.end();
12006                   SO != SOEnd; ++SO) {
12007                assert(SO->second.size() > 0 &&
12008                       "Virtual function without overridding functions?");
12009                if (SO->second.size() == 1)
12010                  continue;
12011
12012                // C++ [class.virtual]p2:
12013                //   In a derived class, if a virtual member function of a base
12014                //   class subobject has more than one final overrider the
12015                //   program is ill-formed.
12016                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
12017                  << (const NamedDecl *)M->first << Record;
12018                Diag(M->first->getLocation(),
12019                     diag::note_overridden_virtual_function);
12020                for (OverridingMethods::overriding_iterator
12021                          OM = SO->second.begin(),
12022                       OMEnd = SO->second.end();
12023                     OM != OMEnd; ++OM)
12024                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
12025                    << (const NamedDecl *)M->first << OM->Method->getParent();
12026
12027                Record->setInvalidDecl();
12028              }
12029            }
12030            CXXRecord->completeDefinition(&FinalOverriders);
12031            Completed = true;
12032          }
12033        }
12034      }
12035    }
12036
12037    if (!Completed)
12038      Record->completeDefinition();
12039
12040    if (Record->hasAttrs())
12041      CheckAlignasUnderalignment(Record);
12042
12043    // Check if the structure/union declaration is a language extension.
12044    if (!getLangOpts().CPlusPlus) {
12045      bool ZeroSize = true;
12046      bool IsEmpty = true;
12047      unsigned NonBitFields = 0;
12048      for (RecordDecl::field_iterator I = Record->field_begin(),
12049                                      E = Record->field_end();
12050           (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
12051        IsEmpty = false;
12052        if (I->isUnnamedBitfield()) {
12053          if (I->getBitWidthValue(Context) > 0)
12054            ZeroSize = false;
12055        } else {
12056          ++NonBitFields;
12057          QualType FieldType = I->getType();
12058          if (FieldType->isIncompleteType() ||
12059              !Context.getTypeSizeInChars(FieldType).isZero())
12060            ZeroSize = false;
12061        }
12062      }
12063
12064      // Empty structs are an extension in C (C99 6.7.2.1p7), but are allowed in
12065      // C++.
12066      if (ZeroSize)
12067        Diag(RecLoc, diag::warn_zero_size_struct_union_compat) << IsEmpty
12068            << Record->isUnion() << (NonBitFields > 1);
12069
12070      // Structs without named members are extension in C (C99 6.7.2.1p7), but
12071      // are accepted by GCC.
12072      if (NonBitFields == 0) {
12073        if (IsEmpty)
12074          Diag(RecLoc, diag::ext_empty_struct_union) << Record->isUnion();
12075        else
12076          Diag(RecLoc, diag::ext_no_named_members_in_struct_union) << Record->isUnion();
12077      }
12078    }
12079  } else {
12080    ObjCIvarDecl **ClsFields =
12081      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
12082    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
12083      ID->setEndOfDefinitionLoc(RBrac);
12084      // Add ivar's to class's DeclContext.
12085      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12086        ClsFields[i]->setLexicalDeclContext(ID);
12087        ID->addDecl(ClsFields[i]);
12088      }
12089      // Must enforce the rule that ivars in the base classes may not be
12090      // duplicates.
12091      if (ID->getSuperClass())
12092        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
12093    } else if (ObjCImplementationDecl *IMPDecl =
12094                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
12095      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
12096      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
12097        // Ivar declared in @implementation never belongs to the implementation.
12098        // Only it is in implementation's lexical context.
12099        ClsFields[I]->setLexicalDeclContext(IMPDecl);
12100      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
12101      IMPDecl->setIvarLBraceLoc(LBrac);
12102      IMPDecl->setIvarRBraceLoc(RBrac);
12103    } else if (ObjCCategoryDecl *CDecl =
12104                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
12105      // case of ivars in class extension; all other cases have been
12106      // reported as errors elsewhere.
12107      // FIXME. Class extension does not have a LocEnd field.
12108      // CDecl->setLocEnd(RBrac);
12109      // Add ivar's to class extension's DeclContext.
12110      // Diagnose redeclaration of private ivars.
12111      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
12112      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
12113        if (IDecl) {
12114          if (const ObjCIvarDecl *ClsIvar =
12115              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
12116            Diag(ClsFields[i]->getLocation(),
12117                 diag::err_duplicate_ivar_declaration);
12118            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
12119            continue;
12120          }
12121          for (ObjCInterfaceDecl::known_extensions_iterator
12122                 Ext = IDecl->known_extensions_begin(),
12123                 ExtEnd = IDecl->known_extensions_end();
12124               Ext != ExtEnd; ++Ext) {
12125            if (const ObjCIvarDecl *ClsExtIvar
12126                  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
12127              Diag(ClsFields[i]->getLocation(),
12128                   diag::err_duplicate_ivar_declaration);
12129              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
12130              continue;
12131            }
12132          }
12133        }
12134        ClsFields[i]->setLexicalDeclContext(CDecl);
12135        CDecl->addDecl(ClsFields[i]);
12136      }
12137      CDecl->setIvarLBraceLoc(LBrac);
12138      CDecl->setIvarRBraceLoc(RBrac);
12139    }
12140  }
12141
12142  if (Attr)
12143    ProcessDeclAttributeList(S, Record, Attr);
12144}
12145
12146/// \brief Determine whether the given integral value is representable within
12147/// the given type T.
12148static bool isRepresentableIntegerValue(ASTContext &Context,
12149                                        llvm::APSInt &Value,
12150                                        QualType T) {
12151  assert(T->isIntegralType(Context) && "Integral type required!");
12152  unsigned BitWidth = Context.getIntWidth(T);
12153
12154  if (Value.isUnsigned() || Value.isNonNegative()) {
12155    if (T->isSignedIntegerOrEnumerationType())
12156      --BitWidth;
12157    return Value.getActiveBits() <= BitWidth;
12158  }
12159  return Value.getMinSignedBits() <= BitWidth;
12160}
12161
12162// \brief Given an integral type, return the next larger integral type
12163// (or a NULL type of no such type exists).
12164static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
12165  // FIXME: Int128/UInt128 support, which also needs to be introduced into
12166  // enum checking below.
12167  assert(T->isIntegralType(Context) && "Integral type required!");
12168  const unsigned NumTypes = 4;
12169  QualType SignedIntegralTypes[NumTypes] = {
12170    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
12171  };
12172  QualType UnsignedIntegralTypes[NumTypes] = {
12173    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
12174    Context.UnsignedLongLongTy
12175  };
12176
12177  unsigned BitWidth = Context.getTypeSize(T);
12178  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
12179                                                        : UnsignedIntegralTypes;
12180  for (unsigned I = 0; I != NumTypes; ++I)
12181    if (Context.getTypeSize(Types[I]) > BitWidth)
12182      return Types[I];
12183
12184  return QualType();
12185}
12186
12187EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
12188                                          EnumConstantDecl *LastEnumConst,
12189                                          SourceLocation IdLoc,
12190                                          IdentifierInfo *Id,
12191                                          Expr *Val) {
12192  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12193  llvm::APSInt EnumVal(IntWidth);
12194  QualType EltTy;
12195
12196  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
12197    Val = 0;
12198
12199  if (Val)
12200    Val = DefaultLvalueConversion(Val).take();
12201
12202  if (Val) {
12203    if (Enum->isDependentType() || Val->isTypeDependent())
12204      EltTy = Context.DependentTy;
12205    else {
12206      SourceLocation ExpLoc;
12207      if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
12208          !getLangOpts().MicrosoftMode) {
12209        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
12210        // constant-expression in the enumerator-definition shall be a converted
12211        // constant expression of the underlying type.
12212        EltTy = Enum->getIntegerType();
12213        ExprResult Converted =
12214          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
12215                                           CCEK_Enumerator);
12216        if (Converted.isInvalid())
12217          Val = 0;
12218        else
12219          Val = Converted.take();
12220      } else if (!Val->isValueDependent() &&
12221                 !(Val = VerifyIntegerConstantExpression(Val,
12222                                                         &EnumVal).take())) {
12223        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
12224      } else {
12225        if (Enum->isFixed()) {
12226          EltTy = Enum->getIntegerType();
12227
12228          // In Obj-C and Microsoft mode, require the enumeration value to be
12229          // representable in the underlying type of the enumeration. In C++11,
12230          // we perform a non-narrowing conversion as part of converted constant
12231          // expression checking.
12232          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12233            if (getLangOpts().MicrosoftMode) {
12234              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
12235              Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12236            } else
12237              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
12238          } else
12239            Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take();
12240        } else if (getLangOpts().CPlusPlus) {
12241          // C++11 [dcl.enum]p5:
12242          //   If the underlying type is not fixed, the type of each enumerator
12243          //   is the type of its initializing value:
12244          //     - If an initializer is specified for an enumerator, the
12245          //       initializing value has the same type as the expression.
12246          EltTy = Val->getType();
12247        } else {
12248          // C99 6.7.2.2p2:
12249          //   The expression that defines the value of an enumeration constant
12250          //   shall be an integer constant expression that has a value
12251          //   representable as an int.
12252
12253          // Complain if the value is not representable in an int.
12254          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
12255            Diag(IdLoc, diag::ext_enum_value_not_int)
12256              << EnumVal.toString(10) << Val->getSourceRange()
12257              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
12258          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
12259            // Force the type of the expression to 'int'.
12260            Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take();
12261          }
12262          EltTy = Val->getType();
12263        }
12264      }
12265    }
12266  }
12267
12268  if (!Val) {
12269    if (Enum->isDependentType())
12270      EltTy = Context.DependentTy;
12271    else if (!LastEnumConst) {
12272      // C++0x [dcl.enum]p5:
12273      //   If the underlying type is not fixed, the type of each enumerator
12274      //   is the type of its initializing value:
12275      //     - If no initializer is specified for the first enumerator, the
12276      //       initializing value has an unspecified integral type.
12277      //
12278      // GCC uses 'int' for its unspecified integral type, as does
12279      // C99 6.7.2.2p3.
12280      if (Enum->isFixed()) {
12281        EltTy = Enum->getIntegerType();
12282      }
12283      else {
12284        EltTy = Context.IntTy;
12285      }
12286    } else {
12287      // Assign the last value + 1.
12288      EnumVal = LastEnumConst->getInitVal();
12289      ++EnumVal;
12290      EltTy = LastEnumConst->getType();
12291
12292      // Check for overflow on increment.
12293      if (EnumVal < LastEnumConst->getInitVal()) {
12294        // C++0x [dcl.enum]p5:
12295        //   If the underlying type is not fixed, the type of each enumerator
12296        //   is the type of its initializing value:
12297        //
12298        //     - Otherwise the type of the initializing value is the same as
12299        //       the type of the initializing value of the preceding enumerator
12300        //       unless the incremented value is not representable in that type,
12301        //       in which case the type is an unspecified integral type
12302        //       sufficient to contain the incremented value. If no such type
12303        //       exists, the program is ill-formed.
12304        QualType T = getNextLargerIntegralType(Context, EltTy);
12305        if (T.isNull() || Enum->isFixed()) {
12306          // There is no integral type larger enough to represent this
12307          // value. Complain, then allow the value to wrap around.
12308          EnumVal = LastEnumConst->getInitVal();
12309          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
12310          ++EnumVal;
12311          if (Enum->isFixed())
12312            // When the underlying type is fixed, this is ill-formed.
12313            Diag(IdLoc, diag::err_enumerator_wrapped)
12314              << EnumVal.toString(10)
12315              << EltTy;
12316          else
12317            Diag(IdLoc, diag::warn_enumerator_too_large)
12318              << EnumVal.toString(10);
12319        } else {
12320          EltTy = T;
12321        }
12322
12323        // Retrieve the last enumerator's value, extent that type to the
12324        // type that is supposed to be large enough to represent the incremented
12325        // value, then increment.
12326        EnumVal = LastEnumConst->getInitVal();
12327        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12328        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
12329        ++EnumVal;
12330
12331        // If we're not in C++, diagnose the overflow of enumerator values,
12332        // which in C99 means that the enumerator value is not representable in
12333        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
12334        // permits enumerator values that are representable in some larger
12335        // integral type.
12336        if (!getLangOpts().CPlusPlus && !T.isNull())
12337          Diag(IdLoc, diag::warn_enum_value_overflow);
12338      } else if (!getLangOpts().CPlusPlus &&
12339                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
12340        // Enforce C99 6.7.2.2p2 even when we compute the next value.
12341        Diag(IdLoc, diag::ext_enum_value_not_int)
12342          << EnumVal.toString(10) << 1;
12343      }
12344    }
12345  }
12346
12347  if (!EltTy->isDependentType()) {
12348    // Make the enumerator value match the signedness and size of the
12349    // enumerator's type.
12350    EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
12351    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
12352  }
12353
12354  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
12355                                  Val, EnumVal);
12356}
12357
12358
12359Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
12360                              SourceLocation IdLoc, IdentifierInfo *Id,
12361                              AttributeList *Attr,
12362                              SourceLocation EqualLoc, Expr *Val) {
12363  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
12364  EnumConstantDecl *LastEnumConst =
12365    cast_or_null<EnumConstantDecl>(lastEnumConst);
12366
12367  // The scope passed in may not be a decl scope.  Zip up the scope tree until
12368  // we find one that is.
12369  S = getNonFieldDeclScope(S);
12370
12371  // Verify that there isn't already something declared with this name in this
12372  // scope.
12373  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
12374                                         ForRedeclaration);
12375  if (PrevDecl && PrevDecl->isTemplateParameter()) {
12376    // Maybe we will complain about the shadowed template parameter.
12377    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
12378    // Just pretend that we didn't see the previous declaration.
12379    PrevDecl = 0;
12380  }
12381
12382  if (PrevDecl) {
12383    // When in C++, we may get a TagDecl with the same name; in this case the
12384    // enum constant will 'hide' the tag.
12385    assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
12386           "Received TagDecl when not in C++!");
12387    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
12388      if (isa<EnumConstantDecl>(PrevDecl))
12389        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
12390      else
12391        Diag(IdLoc, diag::err_redefinition) << Id;
12392      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12393      return 0;
12394    }
12395  }
12396
12397  // C++ [class.mem]p15:
12398  // If T is the name of a class, then each of the following shall have a name
12399  // different from T:
12400  // - every enumerator of every member of class T that is an unscoped
12401  // enumerated type
12402  if (CXXRecordDecl *Record
12403                      = dyn_cast<CXXRecordDecl>(
12404                             TheEnumDecl->getDeclContext()->getRedeclContext()))
12405    if (!TheEnumDecl->isScoped() &&
12406        Record->getIdentifier() && Record->getIdentifier() == Id)
12407      Diag(IdLoc, diag::err_member_name_of_class) << Id;
12408
12409  EnumConstantDecl *New =
12410    CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
12411
12412  if (New) {
12413    // Process attributes.
12414    if (Attr) ProcessDeclAttributeList(S, New, Attr);
12415
12416    // Register this decl in the current scope stack.
12417    New->setAccess(TheEnumDecl->getAccess());
12418    PushOnScopeChains(New, S);
12419  }
12420
12421  ActOnDocumentableDecl(New);
12422
12423  return New;
12424}
12425
12426// Returns true when the enum initial expression does not trigger the
12427// duplicate enum warning.  A few common cases are exempted as follows:
12428// Element2 = Element1
12429// Element2 = Element1 + 1
12430// Element2 = Element1 - 1
12431// Where Element2 and Element1 are from the same enum.
12432static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
12433  Expr *InitExpr = ECD->getInitExpr();
12434  if (!InitExpr)
12435    return true;
12436  InitExpr = InitExpr->IgnoreImpCasts();
12437
12438  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
12439    if (!BO->isAdditiveOp())
12440      return true;
12441    IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
12442    if (!IL)
12443      return true;
12444    if (IL->getValue() != 1)
12445      return true;
12446
12447    InitExpr = BO->getLHS();
12448  }
12449
12450  // This checks if the elements are from the same enum.
12451  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
12452  if (!DRE)
12453    return true;
12454
12455  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
12456  if (!EnumConstant)
12457    return true;
12458
12459  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
12460      Enum)
12461    return true;
12462
12463  return false;
12464}
12465
12466struct DupKey {
12467  int64_t val;
12468  bool isTombstoneOrEmptyKey;
12469  DupKey(int64_t val, bool isTombstoneOrEmptyKey)
12470    : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
12471};
12472
12473static DupKey GetDupKey(const llvm::APSInt& Val) {
12474  return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
12475                false);
12476}
12477
12478struct DenseMapInfoDupKey {
12479  static DupKey getEmptyKey() { return DupKey(0, true); }
12480  static DupKey getTombstoneKey() { return DupKey(1, true); }
12481  static unsigned getHashValue(const DupKey Key) {
12482    return (unsigned)(Key.val * 37);
12483  }
12484  static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
12485    return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
12486           LHS.val == RHS.val;
12487  }
12488};
12489
12490// Emits a warning when an element is implicitly set a value that
12491// a previous element has already been set to.
12492static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
12493                                        EnumDecl *Enum,
12494                                        QualType EnumType) {
12495  if (S.Diags.getDiagnosticLevel(diag::warn_duplicate_enum_values,
12496                                 Enum->getLocation()) ==
12497      DiagnosticsEngine::Ignored)
12498    return;
12499  // Avoid anonymous enums
12500  if (!Enum->getIdentifier())
12501    return;
12502
12503  // Only check for small enums.
12504  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
12505    return;
12506
12507  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
12508  typedef SmallVector<ECDVector *, 3> DuplicatesVector;
12509
12510  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
12511  typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
12512          ValueToVectorMap;
12513
12514  DuplicatesVector DupVector;
12515  ValueToVectorMap EnumMap;
12516
12517  // Populate the EnumMap with all values represented by enum constants without
12518  // an initialier.
12519  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12520    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12521
12522    // Null EnumConstantDecl means a previous diagnostic has been emitted for
12523    // this constant.  Skip this enum since it may be ill-formed.
12524    if (!ECD) {
12525      return;
12526    }
12527
12528    if (ECD->getInitExpr())
12529      continue;
12530
12531    DupKey Key = GetDupKey(ECD->getInitVal());
12532    DeclOrVector &Entry = EnumMap[Key];
12533
12534    // First time encountering this value.
12535    if (Entry.isNull())
12536      Entry = ECD;
12537  }
12538
12539  // Create vectors for any values that has duplicates.
12540  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12541    EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
12542    if (!ValidDuplicateEnum(ECD, Enum))
12543      continue;
12544
12545    DupKey Key = GetDupKey(ECD->getInitVal());
12546
12547    DeclOrVector& Entry = EnumMap[Key];
12548    if (Entry.isNull())
12549      continue;
12550
12551    if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
12552      // Ensure constants are different.
12553      if (D == ECD)
12554        continue;
12555
12556      // Create new vector and push values onto it.
12557      ECDVector *Vec = new ECDVector();
12558      Vec->push_back(D);
12559      Vec->push_back(ECD);
12560
12561      // Update entry to point to the duplicates vector.
12562      Entry = Vec;
12563
12564      // Store the vector somewhere we can consult later for quick emission of
12565      // diagnostics.
12566      DupVector.push_back(Vec);
12567      continue;
12568    }
12569
12570    ECDVector *Vec = Entry.get<ECDVector*>();
12571    // Make sure constants are not added more than once.
12572    if (*Vec->begin() == ECD)
12573      continue;
12574
12575    Vec->push_back(ECD);
12576  }
12577
12578  // Emit diagnostics.
12579  for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
12580                                  DupVectorEnd = DupVector.end();
12581       DupVectorIter != DupVectorEnd; ++DupVectorIter) {
12582    ECDVector *Vec = *DupVectorIter;
12583    assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
12584
12585    // Emit warning for one enum constant.
12586    ECDVector::iterator I = Vec->begin();
12587    S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
12588      << (*I)->getName() << (*I)->getInitVal().toString(10)
12589      << (*I)->getSourceRange();
12590    ++I;
12591
12592    // Emit one note for each of the remaining enum constants with
12593    // the same value.
12594    for (ECDVector::iterator E = Vec->end(); I != E; ++I)
12595      S.Diag((*I)->getLocation(), diag::note_duplicate_element)
12596        << (*I)->getName() << (*I)->getInitVal().toString(10)
12597        << (*I)->getSourceRange();
12598    delete Vec;
12599  }
12600}
12601
12602void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
12603                         SourceLocation RBraceLoc, Decl *EnumDeclX,
12604                         ArrayRef<Decl *> Elements,
12605                         Scope *S, AttributeList *Attr) {
12606  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
12607  QualType EnumType = Context.getTypeDeclType(Enum);
12608
12609  if (Attr)
12610    ProcessDeclAttributeList(S, Enum, Attr);
12611
12612  if (Enum->isDependentType()) {
12613    for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12614      EnumConstantDecl *ECD =
12615        cast_or_null<EnumConstantDecl>(Elements[i]);
12616      if (!ECD) continue;
12617
12618      ECD->setType(EnumType);
12619    }
12620
12621    Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
12622    return;
12623  }
12624
12625  // TODO: If the result value doesn't fit in an int, it must be a long or long
12626  // long value.  ISO C does not support this, but GCC does as an extension,
12627  // emit a warning.
12628  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
12629  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
12630  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
12631
12632  // Verify that all the values are okay, compute the size of the values, and
12633  // reverse the list.
12634  unsigned NumNegativeBits = 0;
12635  unsigned NumPositiveBits = 0;
12636
12637  // Keep track of whether all elements have type int.
12638  bool AllElementsInt = true;
12639
12640  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12641    EnumConstantDecl *ECD =
12642      cast_or_null<EnumConstantDecl>(Elements[i]);
12643    if (!ECD) continue;  // Already issued a diagnostic.
12644
12645    const llvm::APSInt &InitVal = ECD->getInitVal();
12646
12647    // Keep track of the size of positive and negative values.
12648    if (InitVal.isUnsigned() || InitVal.isNonNegative())
12649      NumPositiveBits = std::max(NumPositiveBits,
12650                                 (unsigned)InitVal.getActiveBits());
12651    else
12652      NumNegativeBits = std::max(NumNegativeBits,
12653                                 (unsigned)InitVal.getMinSignedBits());
12654
12655    // Keep track of whether every enum element has type int (very commmon).
12656    if (AllElementsInt)
12657      AllElementsInt = ECD->getType() == Context.IntTy;
12658  }
12659
12660  // Figure out the type that should be used for this enum.
12661  QualType BestType;
12662  unsigned BestWidth;
12663
12664  // C++0x N3000 [conv.prom]p3:
12665  //   An rvalue of an unscoped enumeration type whose underlying
12666  //   type is not fixed can be converted to an rvalue of the first
12667  //   of the following types that can represent all the values of
12668  //   the enumeration: int, unsigned int, long int, unsigned long
12669  //   int, long long int, or unsigned long long int.
12670  // C99 6.4.4.3p2:
12671  //   An identifier declared as an enumeration constant has type int.
12672  // The C99 rule is modified by a gcc extension
12673  QualType BestPromotionType;
12674
12675  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
12676  // -fshort-enums is the equivalent to specifying the packed attribute on all
12677  // enum definitions.
12678  if (LangOpts.ShortEnums)
12679    Packed = true;
12680
12681  if (Enum->isFixed()) {
12682    BestType = Enum->getIntegerType();
12683    if (BestType->isPromotableIntegerType())
12684      BestPromotionType = Context.getPromotedIntegerType(BestType);
12685    else
12686      BestPromotionType = BestType;
12687    // We don't need to set BestWidth, because BestType is going to be the type
12688    // of the enumerators, but we do anyway because otherwise some compilers
12689    // warn that it might be used uninitialized.
12690    BestWidth = CharWidth;
12691  }
12692  else if (NumNegativeBits) {
12693    // If there is a negative value, figure out the smallest integer type (of
12694    // int/long/longlong) that fits.
12695    // If it's packed, check also if it fits a char or a short.
12696    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
12697      BestType = Context.SignedCharTy;
12698      BestWidth = CharWidth;
12699    } else if (Packed && NumNegativeBits <= ShortWidth &&
12700               NumPositiveBits < ShortWidth) {
12701      BestType = Context.ShortTy;
12702      BestWidth = ShortWidth;
12703    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
12704      BestType = Context.IntTy;
12705      BestWidth = IntWidth;
12706    } else {
12707      BestWidth = Context.getTargetInfo().getLongWidth();
12708
12709      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
12710        BestType = Context.LongTy;
12711      } else {
12712        BestWidth = Context.getTargetInfo().getLongLongWidth();
12713
12714        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
12715          Diag(Enum->getLocation(), diag::warn_enum_too_large);
12716        BestType = Context.LongLongTy;
12717      }
12718    }
12719    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
12720  } else {
12721    // If there is no negative value, figure out the smallest type that fits
12722    // all of the enumerator values.
12723    // If it's packed, check also if it fits a char or a short.
12724    if (Packed && NumPositiveBits <= CharWidth) {
12725      BestType = Context.UnsignedCharTy;
12726      BestPromotionType = Context.IntTy;
12727      BestWidth = CharWidth;
12728    } else if (Packed && NumPositiveBits <= ShortWidth) {
12729      BestType = Context.UnsignedShortTy;
12730      BestPromotionType = Context.IntTy;
12731      BestWidth = ShortWidth;
12732    } else if (NumPositiveBits <= IntWidth) {
12733      BestType = Context.UnsignedIntTy;
12734      BestWidth = IntWidth;
12735      BestPromotionType
12736        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12737                           ? Context.UnsignedIntTy : Context.IntTy;
12738    } else if (NumPositiveBits <=
12739               (BestWidth = Context.getTargetInfo().getLongWidth())) {
12740      BestType = Context.UnsignedLongTy;
12741      BestPromotionType
12742        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12743                           ? Context.UnsignedLongTy : Context.LongTy;
12744    } else {
12745      BestWidth = Context.getTargetInfo().getLongLongWidth();
12746      assert(NumPositiveBits <= BestWidth &&
12747             "How could an initializer get larger than ULL?");
12748      BestType = Context.UnsignedLongLongTy;
12749      BestPromotionType
12750        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
12751                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
12752    }
12753  }
12754
12755  // Loop over all of the enumerator constants, changing their types to match
12756  // the type of the enum if needed.
12757  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
12758    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
12759    if (!ECD) continue;  // Already issued a diagnostic.
12760
12761    // Standard C says the enumerators have int type, but we allow, as an
12762    // extension, the enumerators to be larger than int size.  If each
12763    // enumerator value fits in an int, type it as an int, otherwise type it the
12764    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
12765    // that X has type 'int', not 'unsigned'.
12766
12767    // Determine whether the value fits into an int.
12768    llvm::APSInt InitVal = ECD->getInitVal();
12769
12770    // If it fits into an integer type, force it.  Otherwise force it to match
12771    // the enum decl type.
12772    QualType NewTy;
12773    unsigned NewWidth;
12774    bool NewSign;
12775    if (!getLangOpts().CPlusPlus &&
12776        !Enum->isFixed() &&
12777        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
12778      NewTy = Context.IntTy;
12779      NewWidth = IntWidth;
12780      NewSign = true;
12781    } else if (ECD->getType() == BestType) {
12782      // Already the right type!
12783      if (getLangOpts().CPlusPlus)
12784        // C++ [dcl.enum]p4: Following the closing brace of an
12785        // enum-specifier, each enumerator has the type of its
12786        // enumeration.
12787        ECD->setType(EnumType);
12788      continue;
12789    } else {
12790      NewTy = BestType;
12791      NewWidth = BestWidth;
12792      NewSign = BestType->isSignedIntegerOrEnumerationType();
12793    }
12794
12795    // Adjust the APSInt value.
12796    InitVal = InitVal.extOrTrunc(NewWidth);
12797    InitVal.setIsSigned(NewSign);
12798    ECD->setInitVal(InitVal);
12799
12800    // Adjust the Expr initializer and type.
12801    if (ECD->getInitExpr() &&
12802        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
12803      ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
12804                                                CK_IntegralCast,
12805                                                ECD->getInitExpr(),
12806                                                /*base paths*/ 0,
12807                                                VK_RValue));
12808    if (getLangOpts().CPlusPlus)
12809      // C++ [dcl.enum]p4: Following the closing brace of an
12810      // enum-specifier, each enumerator has the type of its
12811      // enumeration.
12812      ECD->setType(EnumType);
12813    else
12814      ECD->setType(NewTy);
12815  }
12816
12817  Enum->completeDefinition(BestType, BestPromotionType,
12818                           NumPositiveBits, NumNegativeBits);
12819
12820  // If we're declaring a function, ensure this decl isn't forgotten about -
12821  // it needs to go into the function scope.
12822  if (InFunctionDeclarator)
12823    DeclsInPrototypeScope.push_back(Enum);
12824
12825  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
12826
12827  // Now that the enum type is defined, ensure it's not been underaligned.
12828  if (Enum->hasAttrs())
12829    CheckAlignasUnderalignment(Enum);
12830}
12831
12832Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
12833                                  SourceLocation StartLoc,
12834                                  SourceLocation EndLoc) {
12835  StringLiteral *AsmString = cast<StringLiteral>(expr);
12836
12837  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
12838                                                   AsmString, StartLoc,
12839                                                   EndLoc);
12840  CurContext->addDecl(New);
12841  return New;
12842}
12843
12844DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
12845                                   SourceLocation ImportLoc,
12846                                   ModuleIdPath Path) {
12847  Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
12848                                                Module::AllVisible,
12849                                                /*IsIncludeDirective=*/false);
12850  if (!Mod)
12851    return true;
12852
12853  SmallVector<SourceLocation, 2> IdentifierLocs;
12854  Module *ModCheck = Mod;
12855  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
12856    // If we've run out of module parents, just drop the remaining identifiers.
12857    // We need the length to be consistent.
12858    if (!ModCheck)
12859      break;
12860    ModCheck = ModCheck->Parent;
12861
12862    IdentifierLocs.push_back(Path[I].second);
12863  }
12864
12865  ImportDecl *Import = ImportDecl::Create(Context,
12866                                          Context.getTranslationUnitDecl(),
12867                                          AtLoc.isValid()? AtLoc : ImportLoc,
12868                                          Mod, IdentifierLocs);
12869  Context.getTranslationUnitDecl()->addDecl(Import);
12870  return Import;
12871}
12872
12873void Sema::createImplicitModuleImport(SourceLocation Loc, Module *Mod) {
12874  // Create the implicit import declaration.
12875  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
12876  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
12877                                                   Loc, Mod, Loc);
12878  TU->addDecl(ImportD);
12879  Consumer.HandleImplicitImportDecl(ImportD);
12880
12881  // Make the module visible.
12882  PP.getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc,
12883                                         /*Complain=*/false);
12884}
12885
12886void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
12887                                      IdentifierInfo* AliasName,
12888                                      SourceLocation PragmaLoc,
12889                                      SourceLocation NameLoc,
12890                                      SourceLocation AliasNameLoc) {
12891  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
12892                                    LookupOrdinaryName);
12893  AsmLabelAttr *Attr =
12894     ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName());
12895
12896  if (PrevDecl)
12897    PrevDecl->addAttr(Attr);
12898  else
12899    (void)ExtnameUndeclaredIdentifiers.insert(
12900      std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr));
12901}
12902
12903void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
12904                             SourceLocation PragmaLoc,
12905                             SourceLocation NameLoc) {
12906  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
12907
12908  if (PrevDecl) {
12909    PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context));
12910  } else {
12911    (void)WeakUndeclaredIdentifiers.insert(
12912      std::pair<IdentifierInfo*,WeakInfo>
12913        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
12914  }
12915}
12916
12917void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
12918                                IdentifierInfo* AliasName,
12919                                SourceLocation PragmaLoc,
12920                                SourceLocation NameLoc,
12921                                SourceLocation AliasNameLoc) {
12922  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
12923                                    LookupOrdinaryName);
12924  WeakInfo W = WeakInfo(Name, NameLoc);
12925
12926  if (PrevDecl) {
12927    if (!PrevDecl->hasAttr<AliasAttr>())
12928      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
12929        DeclApplyPragmaWeak(TUScope, ND, W);
12930  } else {
12931    (void)WeakUndeclaredIdentifiers.insert(
12932      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
12933  }
12934}
12935
12936Decl *Sema::getObjCDeclContext() const {
12937  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
12938}
12939
12940AvailabilityResult Sema::getCurContextAvailability() const {
12941  const Decl *D = cast<Decl>(getCurObjCLexicalContext());
12942  return D->getAvailability();
12943}
12944