SemaDecl.cpp revision 11148974368f811dd0822885300f3fb39192c2f5
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 "Sema.h"
15#include "SemaInit.h"
16#include "Lookup.h"
17#include "clang/AST/APValue.h"
18#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/ParseDiagnostic.h"
26#include "clang/Parse/Template.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Lex/HeaderSearch.h"
33#include "llvm/ADT/Triple.h"
34#include <algorithm>
35#include <cstring>
36#include <functional>
37using namespace clang;
38
39/// getDeclName - Return a pretty name for the specified decl if possible, or
40/// an empty string if not.  This is used for pretty crash reporting.
41std::string Sema::getDeclName(DeclPtrTy d) {
42  Decl *D = d.getAs<Decl>();
43  if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
44    return DN->getQualifiedNameAsString();
45  return "";
46}
47
48Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(DeclPtrTy Ptr) {
49  return DeclGroupPtrTy::make(DeclGroupRef(Ptr.getAs<Decl>()));
50}
51
52/// \brief If the identifier refers to a type name within this scope,
53/// return the declaration of that type.
54///
55/// This routine performs ordinary name lookup of the identifier II
56/// within the given scope, with optional C++ scope specifier SS, to
57/// determine whether the name refers to a type. If so, returns an
58/// opaque pointer (actually a QualType) corresponding to that
59/// type. Otherwise, returns NULL.
60///
61/// If name lookup results in an ambiguity, this routine will complain
62/// and then return NULL.
63Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
64                                Scope *S, CXXScopeSpec *SS,
65                                bool isClassName,
66                                TypeTy *ObjectTypePtr) {
67  // Determine where we will perform name lookup.
68  DeclContext *LookupCtx = 0;
69  if (ObjectTypePtr) {
70    QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
71    if (ObjectType->isRecordType())
72      LookupCtx = computeDeclContext(ObjectType);
73  } else if (SS && SS->isNotEmpty()) {
74    LookupCtx = computeDeclContext(*SS, false);
75
76    if (!LookupCtx) {
77      if (isDependentScopeSpecifier(*SS)) {
78        // C++ [temp.res]p3:
79        //   A qualified-id that refers to a type and in which the
80        //   nested-name-specifier depends on a template-parameter (14.6.2)
81        //   shall be prefixed by the keyword typename to indicate that the
82        //   qualified-id denotes a type, forming an
83        //   elaborated-type-specifier (7.1.5.3).
84        //
85        // We therefore do not perform any name lookup if the result would
86        // refer to a member of an unknown specialization.
87        if (!isClassName)
88          return 0;
89
90        // We know from the grammar that this name refers to a type, so build a
91        // DependentNameType node to describe the type.
92        return CheckTypenameType(ETK_None,
93                                 (NestedNameSpecifier *)SS->getScopeRep(),
94                                 II, SS->getRange()).getAsOpaquePtr();
95      }
96
97      return 0;
98    }
99
100    if (!LookupCtx->isDependentContext() && RequireCompleteDeclContext(*SS))
101      return 0;
102  }
103
104  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
105  // lookup for class-names.
106  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
107                                      LookupOrdinaryName;
108  LookupResult Result(*this, &II, NameLoc, Kind);
109  if (LookupCtx) {
110    // Perform "qualified" name lookup into the declaration context we
111    // computed, which is either the type of the base of a member access
112    // expression or the declaration context associated with a prior
113    // nested-name-specifier.
114    LookupQualifiedName(Result, LookupCtx);
115
116    if (ObjectTypePtr && Result.empty()) {
117      // C++ [basic.lookup.classref]p3:
118      //   If the unqualified-id is ~type-name, the type-name is looked up
119      //   in the context of the entire postfix-expression. If the type T of
120      //   the object expression is of a class type C, the type-name is also
121      //   looked up in the scope of class C. At least one of the lookups shall
122      //   find a name that refers to (possibly cv-qualified) T.
123      LookupName(Result, S);
124    }
125  } else {
126    // Perform unqualified name lookup.
127    LookupName(Result, S);
128  }
129
130  NamedDecl *IIDecl = 0;
131  switch (Result.getResultKind()) {
132  case LookupResult::NotFound:
133  case LookupResult::NotFoundInCurrentInstantiation:
134  case LookupResult::FoundOverloaded:
135  case LookupResult::FoundUnresolvedValue:
136    Result.suppressDiagnostics();
137    return 0;
138
139  case LookupResult::Ambiguous:
140    // Recover from type-hiding ambiguities by hiding the type.  We'll
141    // do the lookup again when looking for an object, and we can
142    // diagnose the error then.  If we don't do this, then the error
143    // about hiding the type will be immediately followed by an error
144    // that only makes sense if the identifier was treated like a type.
145    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
146      Result.suppressDiagnostics();
147      return 0;
148    }
149
150    // Look to see if we have a type anywhere in the list of results.
151    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
152         Res != ResEnd; ++Res) {
153      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
154        if (!IIDecl ||
155            (*Res)->getLocation().getRawEncoding() <
156              IIDecl->getLocation().getRawEncoding())
157          IIDecl = *Res;
158      }
159    }
160
161    if (!IIDecl) {
162      // None of the entities we found is a type, so there is no way
163      // to even assume that the result is a type. In this case, don't
164      // complain about the ambiguity. The parser will either try to
165      // perform this lookup again (e.g., as an object name), which
166      // will produce the ambiguity, or will complain that it expected
167      // a type name.
168      Result.suppressDiagnostics();
169      return 0;
170    }
171
172    // We found a type within the ambiguous lookup; diagnose the
173    // ambiguity and then return that type. This might be the right
174    // answer, or it might not be, but it suppresses any attempt to
175    // perform the name lookup again.
176    break;
177
178  case LookupResult::Found:
179    IIDecl = Result.getFoundDecl();
180    break;
181  }
182
183  assert(IIDecl && "Didn't find decl");
184
185  QualType T;
186  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
187    DiagnoseUseOfDecl(IIDecl, NameLoc);
188
189    if (T.isNull())
190      T = Context.getTypeDeclType(TD);
191
192    if (SS)
193      T = getQualifiedNameType(*SS, T);
194
195  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
196    T = Context.getObjCInterfaceType(IDecl);
197  } else if (UnresolvedUsingTypenameDecl *UUDecl =
198               dyn_cast<UnresolvedUsingTypenameDecl>(IIDecl)) {
199    // FIXME: preserve source structure information.
200    T = Context.getDependentNameType(ETK_None,
201                                     UUDecl->getTargetNestedNameSpecifier(),
202                                     &II);
203  } else {
204    // If it's not plausibly a type, suppress diagnostics.
205    Result.suppressDiagnostics();
206    return 0;
207  }
208
209  return T.getAsOpaquePtr();
210}
211
212/// isTagName() - This method is called *for error recovery purposes only*
213/// to determine if the specified name is a valid tag name ("struct foo").  If
214/// so, this returns the TST for the tag corresponding to it (TST_enum,
215/// TST_union, TST_struct, TST_class).  This is used to diagnose cases in C
216/// where the user forgot to specify the tag.
217DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
218  // Do a tag name lookup in this scope.
219  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
220  LookupName(R, S, false);
221  R.suppressDiagnostics();
222  if (R.getResultKind() == LookupResult::Found)
223    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
224      switch (TD->getTagKind()) {
225      case TagDecl::TK_struct: return DeclSpec::TST_struct;
226      case TagDecl::TK_union:  return DeclSpec::TST_union;
227      case TagDecl::TK_class:  return DeclSpec::TST_class;
228      case TagDecl::TK_enum:   return DeclSpec::TST_enum;
229      }
230    }
231
232  return DeclSpec::TST_unspecified;
233}
234
235bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II,
236                                   SourceLocation IILoc,
237                                   Scope *S,
238                                   CXXScopeSpec *SS,
239                                   TypeTy *&SuggestedType) {
240  // We don't have anything to suggest (yet).
241  SuggestedType = 0;
242
243  // There may have been a typo in the name of the type. Look up typo
244  // results, in case we have something that we can suggest.
245  LookupResult Lookup(*this, &II, IILoc, LookupOrdinaryName,
246                      NotForRedeclaration);
247
248  if (DeclarationName Corrected = CorrectTypo(Lookup, S, SS, 0, 0, CTC_Type)) {
249    if (NamedDecl *Result = Lookup.getAsSingle<NamedDecl>()) {
250      if ((isa<TypeDecl>(Result) || isa<ObjCInterfaceDecl>(Result)) &&
251          !Result->isInvalidDecl()) {
252        // We found a similarly-named type or interface; suggest that.
253        if (!SS || !SS->isSet())
254          Diag(IILoc, diag::err_unknown_typename_suggest)
255            << &II << Lookup.getLookupName()
256            << FixItHint::CreateReplacement(SourceRange(IILoc),
257                                            Result->getNameAsString());
258        else if (DeclContext *DC = computeDeclContext(*SS, false))
259          Diag(IILoc, diag::err_unknown_nested_typename_suggest)
260            << &II << DC << Lookup.getLookupName() << SS->getRange()
261            << FixItHint::CreateReplacement(SourceRange(IILoc),
262                                            Result->getNameAsString());
263        else
264          llvm_unreachable("could not have corrected a typo here");
265
266        Diag(Result->getLocation(), diag::note_previous_decl)
267          << Result->getDeclName();
268
269        SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS);
270        return true;
271      }
272    } else if (Lookup.empty()) {
273      // We corrected to a keyword.
274      // FIXME: Actually recover with the keyword we suggest, and emit a fix-it.
275      Diag(IILoc, diag::err_unknown_typename_suggest)
276        << &II << Corrected;
277      return true;
278    }
279  }
280
281  if (getLangOptions().CPlusPlus) {
282    // See if II is a class template that the user forgot to pass arguments to.
283    UnqualifiedId Name;
284    Name.setIdentifier(&II, IILoc);
285    CXXScopeSpec EmptySS;
286    TemplateTy TemplateResult;
287    if (isTemplateName(S, SS ? *SS : EmptySS, Name, 0, true, TemplateResult)
288        == TNK_Type_template) {
289      TemplateName TplName = TemplateResult.getAsVal<TemplateName>();
290      Diag(IILoc, diag::err_template_missing_args) << TplName;
291      if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
292        Diag(TplDecl->getLocation(), diag::note_template_decl_here)
293          << TplDecl->getTemplateParameters()->getSourceRange();
294      }
295      return true;
296    }
297  }
298
299  // FIXME: Should we move the logic that tries to recover from a missing tag
300  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
301
302  if (!SS || (!SS->isSet() && !SS->isInvalid()))
303    Diag(IILoc, diag::err_unknown_typename) << &II;
304  else if (DeclContext *DC = computeDeclContext(*SS, false))
305    Diag(IILoc, diag::err_typename_nested_not_found)
306      << &II << DC << SS->getRange();
307  else if (isDependentScopeSpecifier(*SS)) {
308    Diag(SS->getRange().getBegin(), diag::err_typename_missing)
309      << (NestedNameSpecifier *)SS->getScopeRep() << II.getName()
310      << SourceRange(SS->getRange().getBegin(), IILoc)
311      << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
312    SuggestedType = ActOnTypenameType(SourceLocation(), *SS, II, IILoc).get();
313  } else {
314    assert(SS && SS->isInvalid() &&
315           "Invalid scope specifier has already been diagnosed");
316  }
317
318  return true;
319}
320
321// Determines the context to return to after temporarily entering a
322// context.  This depends in an unnecessarily complicated way on the
323// exact ordering of callbacks from the parser.
324DeclContext *Sema::getContainingDC(DeclContext *DC) {
325
326  // Functions defined inline within classes aren't parsed until we've
327  // finished parsing the top-level class, so the top-level class is
328  // the context we'll need to return to.
329  if (isa<FunctionDecl>(DC)) {
330    DC = DC->getLexicalParent();
331
332    // A function not defined within a class will always return to its
333    // lexical context.
334    if (!isa<CXXRecordDecl>(DC))
335      return DC;
336
337    // A C++ inline method/friend is parsed *after* the topmost class
338    // it was declared in is fully parsed ("complete");  the topmost
339    // class is the context we need to return to.
340    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
341      DC = RD;
342
343    // Return the declaration context of the topmost class the inline method is
344    // declared in.
345    return DC;
346  }
347
348  if (isa<ObjCMethodDecl>(DC))
349    return Context.getTranslationUnitDecl();
350
351  return DC->getLexicalParent();
352}
353
354void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
355  assert(getContainingDC(DC) == CurContext &&
356      "The next DeclContext should be lexically contained in the current one.");
357  CurContext = DC;
358  S->setEntity(DC);
359}
360
361void Sema::PopDeclContext() {
362  assert(CurContext && "DeclContext imbalance!");
363
364  CurContext = getContainingDC(CurContext);
365}
366
367/// EnterDeclaratorContext - Used when we must lookup names in the context
368/// of a declarator's nested name specifier.
369///
370void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
371  // C++0x [basic.lookup.unqual]p13:
372  //   A name used in the definition of a static data member of class
373  //   X (after the qualified-id of the static member) is looked up as
374  //   if the name was used in a member function of X.
375  // C++0x [basic.lookup.unqual]p14:
376  //   If a variable member of a namespace is defined outside of the
377  //   scope of its namespace then any name used in the definition of
378  //   the variable member (after the declarator-id) is looked up as
379  //   if the definition of the variable member occurred in its
380  //   namespace.
381  // Both of these imply that we should push a scope whose context
382  // is the semantic context of the declaration.  We can't use
383  // PushDeclContext here because that context is not necessarily
384  // lexically contained in the current context.  Fortunately,
385  // the containing scope should have the appropriate information.
386
387  assert(!S->getEntity() && "scope already has entity");
388
389#ifndef NDEBUG
390  Scope *Ancestor = S->getParent();
391  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
392  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
393#endif
394
395  CurContext = DC;
396  S->setEntity(DC);
397}
398
399void Sema::ExitDeclaratorContext(Scope *S) {
400  assert(S->getEntity() == CurContext && "Context imbalance!");
401
402  // Switch back to the lexical context.  The safety of this is
403  // enforced by an assert in EnterDeclaratorContext.
404  Scope *Ancestor = S->getParent();
405  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
406  CurContext = (DeclContext*) Ancestor->getEntity();
407
408  // We don't need to do anything with the scope, which is going to
409  // disappear.
410}
411
412/// \brief Determine whether we allow overloading of the function
413/// PrevDecl with another declaration.
414///
415/// This routine determines whether overloading is possible, not
416/// whether some new function is actually an overload. It will return
417/// true in C++ (where we can always provide overloads) or, as an
418/// extension, in C when the previous function is already an
419/// overloaded function declaration or has the "overloadable"
420/// attribute.
421static bool AllowOverloadingOfFunction(LookupResult &Previous,
422                                       ASTContext &Context) {
423  if (Context.getLangOptions().CPlusPlus)
424    return true;
425
426  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
427    return true;
428
429  return (Previous.getResultKind() == LookupResult::Found
430          && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
431}
432
433/// Add this decl to the scope shadowed decl chains.
434void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
435  // Move up the scope chain until we find the nearest enclosing
436  // non-transparent context. The declaration will be introduced into this
437  // scope.
438  while (S->getEntity() &&
439         ((DeclContext *)S->getEntity())->isTransparentContext())
440    S = S->getParent();
441
442  // Add scoped declarations into their context, so that they can be
443  // found later. Declarations without a context won't be inserted
444  // into any context.
445  if (AddToContext)
446    CurContext->addDecl(D);
447
448  // Out-of-line definitions shouldn't be pushed into scope in C++.
449  // Out-of-line variable and function definitions shouldn't even in C.
450  if ((getLangOptions().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) &&
451      D->isOutOfLine())
452    return;
453
454  // Template instantiations should also not be pushed into scope.
455  if (isa<FunctionDecl>(D) &&
456      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
457    return;
458
459  // If this replaces anything in the current scope,
460  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
461                               IEnd = IdResolver.end();
462  for (; I != IEnd; ++I) {
463    if (S->isDeclScope(DeclPtrTy::make(*I)) && D->declarationReplaces(*I)) {
464      S->RemoveDecl(DeclPtrTy::make(*I));
465      IdResolver.RemoveDecl(*I);
466
467      // Should only need to replace one decl.
468      break;
469    }
470  }
471
472  S->AddDecl(DeclPtrTy::make(D));
473  IdResolver.AddDecl(D);
474}
475
476bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S) {
477  return IdResolver.isDeclInScope(D, Ctx, Context, S);
478}
479
480static bool isOutOfScopePreviousDeclaration(NamedDecl *,
481                                            DeclContext*,
482                                            ASTContext&);
483
484/// Filters out lookup results that don't fall within the given scope
485/// as determined by isDeclInScope.
486static void FilterLookupForScope(Sema &SemaRef, LookupResult &R,
487                                 DeclContext *Ctx, Scope *S,
488                                 bool ConsiderLinkage) {
489  LookupResult::Filter F = R.makeFilter();
490  while (F.hasNext()) {
491    NamedDecl *D = F.next();
492
493    if (SemaRef.isDeclInScope(D, Ctx, S))
494      continue;
495
496    if (ConsiderLinkage &&
497        isOutOfScopePreviousDeclaration(D, Ctx, SemaRef.Context))
498      continue;
499
500    F.erase();
501  }
502
503  F.done();
504}
505
506static bool isUsingDecl(NamedDecl *D) {
507  return isa<UsingShadowDecl>(D) ||
508         isa<UnresolvedUsingTypenameDecl>(D) ||
509         isa<UnresolvedUsingValueDecl>(D);
510}
511
512/// Removes using shadow declarations from the lookup results.
513static void RemoveUsingDecls(LookupResult &R) {
514  LookupResult::Filter F = R.makeFilter();
515  while (F.hasNext())
516    if (isUsingDecl(F.next()))
517      F.erase();
518
519  F.done();
520}
521
522static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
523  if (D->isInvalidDecl())
524    return false;
525
526  if (D->isUsed() || D->hasAttr<UnusedAttr>())
527    return false;
528
529  // White-list anything that isn't a local variable.
530  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) ||
531      !D->getDeclContext()->isFunctionOrMethod())
532    return false;
533
534  // Types of valid local variables should be complete, so this should succeed.
535  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
536
537    // White-list anything with an __attribute__((unused)) type.
538    QualType Ty = VD->getType();
539
540    // Only look at the outermost level of typedef.
541    if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) {
542      if (TT->getDecl()->hasAttr<UnusedAttr>())
543        return false;
544    }
545
546    // If we failed to complete the type for some reason, don't
547    // diagnose the variable.
548    if (Ty->isIncompleteType())
549      return false;
550
551    if (const TagType *TT = Ty->getAs<TagType>()) {
552      const TagDecl *Tag = TT->getDecl();
553      if (Tag->hasAttr<UnusedAttr>())
554        return false;
555
556      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
557        if (!RD->hasTrivialConstructor())
558          return false;
559        if (!RD->hasTrivialDestructor())
560          return false;
561      }
562    }
563
564    // TODO: __attribute__((unused)) templates?
565  }
566
567  return true;
568}
569
570void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
571  if (S->decl_empty()) return;
572  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
573         "Scope shouldn't contain decls!");
574
575  for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
576       I != E; ++I) {
577    Decl *TmpD = (*I).getAs<Decl>();
578    assert(TmpD && "This decl didn't get pushed??");
579
580    assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
581    NamedDecl *D = cast<NamedDecl>(TmpD);
582
583    if (!D->getDeclName()) continue;
584
585    // Diagnose unused variables in this scope.
586    if (ShouldDiagnoseUnusedDecl(D) &&
587        S->getNumErrorsAtStart() == getDiagnostics().getNumErrors())
588      Diag(D->getLocation(), diag::warn_unused_variable) << D->getDeclName();
589
590    // Remove this name from our lexical scope.
591    IdResolver.RemoveDecl(D);
592  }
593}
594
595/// \brief Look for an Objective-C class in the translation unit.
596///
597/// \param Id The name of the Objective-C class we're looking for. If
598/// typo-correction fixes this name, the Id will be updated
599/// to the fixed name.
600///
601/// \param IdLoc The location of the name in the translation unit.
602///
603/// \param TypoCorrection If true, this routine will attempt typo correction
604/// if there is no class with the given name.
605///
606/// \returns The declaration of the named Objective-C class, or NULL if the
607/// class could not be found.
608ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
609                                              SourceLocation IdLoc,
610                                              bool TypoCorrection) {
611  // The third "scope" argument is 0 since we aren't enabling lazy built-in
612  // creation from this context.
613  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
614
615  if (!IDecl && TypoCorrection) {
616    // Perform typo correction at the given location, but only if we
617    // find an Objective-C class name.
618    LookupResult R(*this, Id, IdLoc, LookupOrdinaryName);
619    if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
620        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
621      Diag(IdLoc, diag::err_undef_interface_suggest)
622        << Id << IDecl->getDeclName()
623        << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString());
624      Diag(IDecl->getLocation(), diag::note_previous_decl)
625        << IDecl->getDeclName();
626
627      Id = IDecl->getIdentifier();
628    }
629  }
630
631  return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
632}
633
634/// getNonFieldDeclScope - Retrieves the innermost scope, starting
635/// from S, where a non-field would be declared. This routine copes
636/// with the difference between C and C++ scoping rules in structs and
637/// unions. For example, the following code is well-formed in C but
638/// ill-formed in C++:
639/// @code
640/// struct S6 {
641///   enum { BAR } e;
642/// };
643///
644/// void test_S6() {
645///   struct S6 a;
646///   a.e = BAR;
647/// }
648/// @endcode
649/// For the declaration of BAR, this routine will return a different
650/// scope. The scope S will be the scope of the unnamed enumeration
651/// within S6. In C++, this routine will return the scope associated
652/// with S6, because the enumeration's scope is a transparent
653/// context but structures can contain non-field names. In C, this
654/// routine will return the translation unit scope, since the
655/// enumeration's scope is a transparent context and structures cannot
656/// contain non-field names.
657Scope *Sema::getNonFieldDeclScope(Scope *S) {
658  while (((S->getFlags() & Scope::DeclScope) == 0) ||
659         (S->getEntity() &&
660          ((DeclContext *)S->getEntity())->isTransparentContext()) ||
661         (S->isClassScope() && !getLangOptions().CPlusPlus))
662    S = S->getParent();
663  return S;
664}
665
666void Sema::InitBuiltinVaListType() {
667  if (!Context.getBuiltinVaListType().isNull())
668    return;
669
670  IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
671  NamedDecl *VaDecl = LookupSingleName(TUScope, VaIdent, SourceLocation(),
672                                       LookupOrdinaryName, ForRedeclaration);
673  TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
674  Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
675}
676
677/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
678/// file scope.  lazily create a decl for it. ForRedeclaration is true
679/// if we're creating this built-in in anticipation of redeclaring the
680/// built-in.
681NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
682                                     Scope *S, bool ForRedeclaration,
683                                     SourceLocation Loc) {
684  Builtin::ID BID = (Builtin::ID)bid;
685
686  if (Context.BuiltinInfo.hasVAListUse(BID))
687    InitBuiltinVaListType();
688
689  ASTContext::GetBuiltinTypeError Error;
690  QualType R = Context.GetBuiltinType(BID, Error);
691  switch (Error) {
692  case ASTContext::GE_None:
693    // Okay
694    break;
695
696  case ASTContext::GE_Missing_stdio:
697    if (ForRedeclaration)
698      Diag(Loc, diag::err_implicit_decl_requires_stdio)
699        << Context.BuiltinInfo.GetName(BID);
700    return 0;
701
702  case ASTContext::GE_Missing_setjmp:
703    if (ForRedeclaration)
704      Diag(Loc, diag::err_implicit_decl_requires_setjmp)
705        << Context.BuiltinInfo.GetName(BID);
706    return 0;
707  }
708
709  if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
710    Diag(Loc, diag::ext_implicit_lib_function_decl)
711      << Context.BuiltinInfo.GetName(BID)
712      << R;
713    if (Context.BuiltinInfo.getHeaderName(BID) &&
714        Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl)
715          != Diagnostic::Ignored)
716      Diag(Loc, diag::note_please_include_header)
717        << Context.BuiltinInfo.getHeaderName(BID)
718        << Context.BuiltinInfo.GetName(BID);
719  }
720
721  FunctionDecl *New = FunctionDecl::Create(Context,
722                                           Context.getTranslationUnitDecl(),
723                                           Loc, II, R, /*TInfo=*/0,
724                                           FunctionDecl::Extern,
725                                           FunctionDecl::None, false,
726                                           /*hasPrototype=*/true);
727  New->setImplicit();
728
729  // Create Decl objects for each parameter, adding them to the
730  // FunctionDecl.
731  if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
732    llvm::SmallVector<ParmVarDecl*, 16> Params;
733    for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
734      Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
735                                           FT->getArgType(i), /*TInfo=*/0,
736                                           VarDecl::None, VarDecl::None, 0));
737    New->setParams(Params.data(), Params.size());
738  }
739
740  AddKnownFunctionAttributes(New);
741
742  // TUScope is the translation-unit scope to insert this function into.
743  // FIXME: This is hideous. We need to teach PushOnScopeChains to
744  // relate Scopes to DeclContexts, and probably eliminate CurContext
745  // entirely, but we're not there yet.
746  DeclContext *SavedContext = CurContext;
747  CurContext = Context.getTranslationUnitDecl();
748  PushOnScopeChains(New, TUScope);
749  CurContext = SavedContext;
750  return New;
751}
752
753/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
754/// same name and scope as a previous declaration 'Old'.  Figure out
755/// how to resolve this situation, merging decls or emitting
756/// diagnostics as appropriate. If there was an error, set New to be invalid.
757///
758void Sema::MergeTypeDefDecl(TypedefDecl *New, LookupResult &OldDecls) {
759  // If the new decl is known invalid already, don't bother doing any
760  // merging checks.
761  if (New->isInvalidDecl()) return;
762
763  // Allow multiple definitions for ObjC built-in typedefs.
764  // FIXME: Verify the underlying types are equivalent!
765  if (getLangOptions().ObjC1) {
766    const IdentifierInfo *TypeID = New->getIdentifier();
767    switch (TypeID->getLength()) {
768    default: break;
769    case 2:
770      if (!TypeID->isStr("id"))
771        break;
772      Context.ObjCIdRedefinitionType = New->getUnderlyingType();
773      // Install the built-in type for 'id', ignoring the current definition.
774      New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
775      return;
776    case 5:
777      if (!TypeID->isStr("Class"))
778        break;
779      Context.ObjCClassRedefinitionType = New->getUnderlyingType();
780      // Install the built-in type for 'Class', ignoring the current definition.
781      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
782      return;
783    case 3:
784      if (!TypeID->isStr("SEL"))
785        break;
786      Context.ObjCSelRedefinitionType = New->getUnderlyingType();
787      // Install the built-in type for 'SEL', ignoring the current definition.
788      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
789      return;
790    case 8:
791      if (!TypeID->isStr("Protocol"))
792        break;
793      Context.setObjCProtoType(New->getUnderlyingType());
794      return;
795    }
796    // Fall through - the typedef name was not a builtin type.
797  }
798
799  // Verify the old decl was also a type.
800  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
801  if (!Old) {
802    Diag(New->getLocation(), diag::err_redefinition_different_kind)
803      << New->getDeclName();
804
805    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
806    if (OldD->getLocation().isValid())
807      Diag(OldD->getLocation(), diag::note_previous_definition);
808
809    return New->setInvalidDecl();
810  }
811
812  // If the old declaration is invalid, just give up here.
813  if (Old->isInvalidDecl())
814    return New->setInvalidDecl();
815
816  // Determine the "old" type we'll use for checking and diagnostics.
817  QualType OldType;
818  if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
819    OldType = OldTypedef->getUnderlyingType();
820  else
821    OldType = Context.getTypeDeclType(Old);
822
823  // If the typedef types are not identical, reject them in all languages and
824  // with any extensions enabled.
825
826  if (OldType != New->getUnderlyingType() &&
827      Context.getCanonicalType(OldType) !=
828      Context.getCanonicalType(New->getUnderlyingType())) {
829    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
830      << New->getUnderlyingType() << OldType;
831    if (Old->getLocation().isValid())
832      Diag(Old->getLocation(), diag::note_previous_definition);
833    return New->setInvalidDecl();
834  }
835
836  // The types match.  Link up the redeclaration chain if the old
837  // declaration was a typedef.
838  // FIXME: this is a potential source of wierdness if the type
839  // spellings don't match exactly.
840  if (isa<TypedefDecl>(Old))
841    New->setPreviousDeclaration(cast<TypedefDecl>(Old));
842
843  if (getLangOptions().Microsoft)
844    return;
845
846  if (getLangOptions().CPlusPlus) {
847    // C++ [dcl.typedef]p2:
848    //   In a given non-class scope, a typedef specifier can be used to
849    //   redefine the name of any type declared in that scope to refer
850    //   to the type to which it already refers.
851    if (!isa<CXXRecordDecl>(CurContext))
852      return;
853
854    // C++0x [dcl.typedef]p4:
855    //   In a given class scope, a typedef specifier can be used to redefine
856    //   any class-name declared in that scope that is not also a typedef-name
857    //   to refer to the type to which it already refers.
858    //
859    // This wording came in via DR424, which was a correction to the
860    // wording in DR56, which accidentally banned code like:
861    //
862    //   struct S {
863    //     typedef struct A { } A;
864    //   };
865    //
866    // in the C++03 standard. We implement the C++0x semantics, which
867    // allow the above but disallow
868    //
869    //   struct S {
870    //     typedef int I;
871    //     typedef int I;
872    //   };
873    //
874    // since that was the intent of DR56.
875    if (!isa<TypedefDecl >(Old))
876      return;
877
878    Diag(New->getLocation(), diag::err_redefinition)
879      << New->getDeclName();
880    Diag(Old->getLocation(), diag::note_previous_definition);
881    return New->setInvalidDecl();
882  }
883
884  // If we have a redefinition of a typedef in C, emit a warning.  This warning
885  // is normally mapped to an error, but can be controlled with
886  // -Wtypedef-redefinition.  If either the original or the redefinition is
887  // in a system header, don't emit this for compatibility with GCC.
888  if (getDiagnostics().getSuppressSystemWarnings() &&
889      (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
890       Context.getSourceManager().isInSystemHeader(New->getLocation())))
891    return;
892
893  Diag(New->getLocation(), diag::warn_redefinition_of_typedef)
894    << New->getDeclName();
895  Diag(Old->getLocation(), diag::note_previous_definition);
896  return;
897}
898
899/// DeclhasAttr - returns true if decl Declaration already has the target
900/// attribute.
901static bool
902DeclHasAttr(const Decl *decl, const Attr *target) {
903  for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
904    if (attr->getKind() == target->getKind())
905      return true;
906
907  return false;
908}
909
910/// MergeAttributes - append attributes from the Old decl to the New one.
911static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
912  for (const Attr *attr = Old->getAttrs(); attr; attr = attr->getNext()) {
913    if (!DeclHasAttr(New, attr) && attr->isMerged()) {
914      Attr *NewAttr = attr->clone(C);
915      NewAttr->setInherited(true);
916      New->addAttr(NewAttr);
917    }
918  }
919}
920
921/// Used in MergeFunctionDecl to keep track of function parameters in
922/// C.
923struct GNUCompatibleParamWarning {
924  ParmVarDecl *OldParm;
925  ParmVarDecl *NewParm;
926  QualType PromotedType;
927};
928
929
930/// getSpecialMember - get the special member enum for a method.
931Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
932  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
933    if (Ctor->isCopyConstructor())
934      return Sema::CXXCopyConstructor;
935
936    return Sema::CXXConstructor;
937  }
938
939  if (isa<CXXDestructorDecl>(MD))
940    return Sema::CXXDestructor;
941
942  assert(MD->isCopyAssignment() && "Must have copy assignment operator");
943  return Sema::CXXCopyAssignment;
944}
945
946/// canREdefineFunction - checks if a function can be redefined. Currently,
947/// only extern inline functions can be redefined, and even then only in
948/// GNU89 mode.
949static bool canRedefineFunction(const FunctionDecl *FD,
950                                const LangOptions& LangOpts) {
951  return (LangOpts.GNUMode && !LangOpts.C99 && !LangOpts.CPlusPlus &&
952          FD->isInlineSpecified() &&
953          FD->getStorageClass() == FunctionDecl::Extern);
954}
955
956/// MergeFunctionDecl - We just parsed a function 'New' from
957/// declarator D which has the same name and scope as a previous
958/// declaration 'Old'.  Figure out how to resolve this situation,
959/// merging decls or emitting diagnostics as appropriate.
960///
961/// In C++, New and Old must be declarations that are not
962/// overloaded. Use IsOverload to determine whether New and Old are
963/// overloaded, and to select the Old declaration that New should be
964/// merged with.
965///
966/// Returns true if there was an error, false otherwise.
967bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
968  // Verify the old decl was also a function.
969  FunctionDecl *Old = 0;
970  if (FunctionTemplateDecl *OldFunctionTemplate
971        = dyn_cast<FunctionTemplateDecl>(OldD))
972    Old = OldFunctionTemplate->getTemplatedDecl();
973  else
974    Old = dyn_cast<FunctionDecl>(OldD);
975  if (!Old) {
976    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
977      Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
978      Diag(Shadow->getTargetDecl()->getLocation(),
979           diag::note_using_decl_target);
980      Diag(Shadow->getUsingDecl()->getLocation(),
981           diag::note_using_decl) << 0;
982      return true;
983    }
984
985    Diag(New->getLocation(), diag::err_redefinition_different_kind)
986      << New->getDeclName();
987    Diag(OldD->getLocation(), diag::note_previous_definition);
988    return true;
989  }
990
991  // Determine whether the previous declaration was a definition,
992  // implicit declaration, or a declaration.
993  diag::kind PrevDiag;
994  if (Old->isThisDeclarationADefinition())
995    PrevDiag = diag::note_previous_definition;
996  else if (Old->isImplicit())
997    PrevDiag = diag::note_previous_implicit_declaration;
998  else
999    PrevDiag = diag::note_previous_declaration;
1000
1001  QualType OldQType = Context.getCanonicalType(Old->getType());
1002  QualType NewQType = Context.getCanonicalType(New->getType());
1003
1004  // Don't complain about this if we're in GNU89 mode and the old function
1005  // is an extern inline function.
1006  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
1007      New->getStorageClass() == FunctionDecl::Static &&
1008      Old->getStorageClass() != FunctionDecl::Static &&
1009      !canRedefineFunction(Old, getLangOptions())) {
1010    Diag(New->getLocation(), diag::err_static_non_static)
1011      << New;
1012    Diag(Old->getLocation(), PrevDiag);
1013    return true;
1014  }
1015
1016  // If a function is first declared with a calling convention, but is
1017  // later declared or defined without one, the second decl assumes the
1018  // calling convention of the first.
1019  //
1020  // For the new decl, we have to look at the NON-canonical type to tell the
1021  // difference between a function that really doesn't have a calling
1022  // convention and one that is declared cdecl. That's because in
1023  // canonicalization (see ASTContext.cpp), cdecl is canonicalized away
1024  // because it is the default calling convention.
1025  //
1026  // Note also that we DO NOT return at this point, because we still have
1027  // other tests to run.
1028  const FunctionType *OldType = OldQType->getAs<FunctionType>();
1029  const FunctionType *NewType = New->getType()->getAs<FunctionType>();
1030  const FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
1031  const FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
1032  if (OldTypeInfo.getCC() != CC_Default &&
1033      NewTypeInfo.getCC() == CC_Default) {
1034    NewQType = Context.getCallConvType(NewQType, OldTypeInfo.getCC());
1035    New->setType(NewQType);
1036    NewQType = Context.getCanonicalType(NewQType);
1037  } else if (!Context.isSameCallConv(OldTypeInfo.getCC(),
1038                                     NewTypeInfo.getCC())) {
1039    // Calling conventions really aren't compatible, so complain.
1040    Diag(New->getLocation(), diag::err_cconv_change)
1041      << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
1042      << (OldTypeInfo.getCC() == CC_Default)
1043      << (OldTypeInfo.getCC() == CC_Default ? "" :
1044          FunctionType::getNameForCallConv(OldTypeInfo.getCC()));
1045    Diag(Old->getLocation(), diag::note_previous_declaration);
1046    return true;
1047  }
1048
1049  // FIXME: diagnose the other way around?
1050  if (OldType->getNoReturnAttr() &&
1051      !NewType->getNoReturnAttr()) {
1052    NewQType = Context.getNoReturnType(NewQType);
1053    New->setType(NewQType);
1054    assert(NewQType.isCanonical());
1055  }
1056
1057  if (getLangOptions().CPlusPlus) {
1058    // (C++98 13.1p2):
1059    //   Certain function declarations cannot be overloaded:
1060    //     -- Function declarations that differ only in the return type
1061    //        cannot be overloaded.
1062    QualType OldReturnType
1063      = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
1064    QualType NewReturnType
1065      = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
1066    if (OldReturnType != NewReturnType) {
1067      Diag(New->getLocation(), diag::err_ovl_diff_return_type);
1068      Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1069      return true;
1070    }
1071
1072    const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1073    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1074    if (OldMethod && NewMethod) {
1075      // Preserve triviality.
1076      NewMethod->setTrivial(OldMethod->isTrivial());
1077
1078      bool isFriend = NewMethod->getFriendObjectKind();
1079
1080      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord()) {
1081        //    -- Member function declarations with the same name and the
1082        //       same parameter types cannot be overloaded if any of them
1083        //       is a static member function declaration.
1084        if (OldMethod->isStatic() || NewMethod->isStatic()) {
1085          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
1086          Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1087          return true;
1088        }
1089
1090        // C++ [class.mem]p1:
1091        //   [...] A member shall not be declared twice in the
1092        //   member-specification, except that a nested class or member
1093        //   class template can be declared and then later defined.
1094        unsigned NewDiag;
1095        if (isa<CXXConstructorDecl>(OldMethod))
1096          NewDiag = diag::err_constructor_redeclared;
1097        else if (isa<CXXDestructorDecl>(NewMethod))
1098          NewDiag = diag::err_destructor_redeclared;
1099        else if (isa<CXXConversionDecl>(NewMethod))
1100          NewDiag = diag::err_conv_function_redeclared;
1101        else
1102          NewDiag = diag::err_member_redeclared;
1103
1104        Diag(New->getLocation(), NewDiag);
1105        Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1106
1107      // Complain if this is an explicit declaration of a special
1108      // member that was initially declared implicitly.
1109      //
1110      // As an exception, it's okay to befriend such methods in order
1111      // to permit the implicit constructor/destructor/operator calls.
1112      } else if (OldMethod->isImplicit()) {
1113        if (isFriend) {
1114          NewMethod->setImplicit();
1115        } else {
1116          Diag(NewMethod->getLocation(),
1117               diag::err_definition_of_implicitly_declared_member)
1118            << New << getSpecialMember(OldMethod);
1119          return true;
1120        }
1121      }
1122    }
1123
1124    // (C++98 8.3.5p3):
1125    //   All declarations for a function shall agree exactly in both the
1126    //   return type and the parameter-type-list.
1127    // attributes should be ignored when comparing.
1128    if (Context.getNoReturnType(OldQType, false) ==
1129        Context.getNoReturnType(NewQType, false))
1130      return MergeCompatibleFunctionDecls(New, Old);
1131
1132    // Fall through for conflicting redeclarations and redefinitions.
1133  }
1134
1135  // C: Function types need to be compatible, not identical. This handles
1136  // duplicate function decls like "void f(int); void f(enum X);" properly.
1137  if (!getLangOptions().CPlusPlus &&
1138      Context.typesAreCompatible(OldQType, NewQType)) {
1139    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
1140    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
1141    const FunctionProtoType *OldProto = 0;
1142    if (isa<FunctionNoProtoType>(NewFuncType) &&
1143        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
1144      // The old declaration provided a function prototype, but the
1145      // new declaration does not. Merge in the prototype.
1146      assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
1147      llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
1148                                                 OldProto->arg_type_end());
1149      NewQType = Context.getFunctionType(NewFuncType->getResultType(),
1150                                         ParamTypes.data(), ParamTypes.size(),
1151                                         OldProto->isVariadic(),
1152                                         OldProto->getTypeQuals(),
1153                                         false, false, 0, 0,
1154                                         OldProto->getExtInfo());
1155      New->setType(NewQType);
1156      New->setHasInheritedPrototype();
1157
1158      // Synthesize a parameter for each argument type.
1159      llvm::SmallVector<ParmVarDecl*, 16> Params;
1160      for (FunctionProtoType::arg_type_iterator
1161             ParamType = OldProto->arg_type_begin(),
1162             ParamEnd = OldProto->arg_type_end();
1163           ParamType != ParamEnd; ++ParamType) {
1164        ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
1165                                                 SourceLocation(), 0,
1166                                                 *ParamType, /*TInfo=*/0,
1167                                                 VarDecl::None, VarDecl::None,
1168                                                 0);
1169        Param->setImplicit();
1170        Params.push_back(Param);
1171      }
1172
1173      New->setParams(Params.data(), Params.size());
1174    }
1175
1176    return MergeCompatibleFunctionDecls(New, Old);
1177  }
1178
1179  // GNU C permits a K&R definition to follow a prototype declaration
1180  // if the declared types of the parameters in the K&R definition
1181  // match the types in the prototype declaration, even when the
1182  // promoted types of the parameters from the K&R definition differ
1183  // from the types in the prototype. GCC then keeps the types from
1184  // the prototype.
1185  //
1186  // If a variadic prototype is followed by a non-variadic K&R definition,
1187  // the K&R definition becomes variadic.  This is sort of an edge case, but
1188  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
1189  // C99 6.9.1p8.
1190  if (!getLangOptions().CPlusPlus &&
1191      Old->hasPrototype() && !New->hasPrototype() &&
1192      New->getType()->getAs<FunctionProtoType>() &&
1193      Old->getNumParams() == New->getNumParams()) {
1194    llvm::SmallVector<QualType, 16> ArgTypes;
1195    llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
1196    const FunctionProtoType *OldProto
1197      = Old->getType()->getAs<FunctionProtoType>();
1198    const FunctionProtoType *NewProto
1199      = New->getType()->getAs<FunctionProtoType>();
1200
1201    // Determine whether this is the GNU C extension.
1202    QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(),
1203                                               NewProto->getResultType());
1204    bool LooseCompatible = !MergedReturn.isNull();
1205    for (unsigned Idx = 0, End = Old->getNumParams();
1206         LooseCompatible && Idx != End; ++Idx) {
1207      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
1208      ParmVarDecl *NewParm = New->getParamDecl(Idx);
1209      if (Context.typesAreCompatible(OldParm->getType(),
1210                                     NewProto->getArgType(Idx))) {
1211        ArgTypes.push_back(NewParm->getType());
1212      } else if (Context.typesAreCompatible(OldParm->getType(),
1213                                            NewParm->getType())) {
1214        GNUCompatibleParamWarning Warn
1215          = { OldParm, NewParm, NewProto->getArgType(Idx) };
1216        Warnings.push_back(Warn);
1217        ArgTypes.push_back(NewParm->getType());
1218      } else
1219        LooseCompatible = false;
1220    }
1221
1222    if (LooseCompatible) {
1223      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
1224        Diag(Warnings[Warn].NewParm->getLocation(),
1225             diag::ext_param_promoted_not_compatible_with_prototype)
1226          << Warnings[Warn].PromotedType
1227          << Warnings[Warn].OldParm->getType();
1228        Diag(Warnings[Warn].OldParm->getLocation(),
1229             diag::note_previous_declaration);
1230      }
1231
1232      New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0],
1233                                           ArgTypes.size(),
1234                                           OldProto->isVariadic(), 0,
1235                                           false, false, 0, 0,
1236                                           OldProto->getExtInfo()));
1237      return MergeCompatibleFunctionDecls(New, Old);
1238    }
1239
1240    // Fall through to diagnose conflicting types.
1241  }
1242
1243  // A function that has already been declared has been redeclared or defined
1244  // with a different type- show appropriate diagnostic
1245  if (unsigned BuiltinID = Old->getBuiltinID()) {
1246    // The user has declared a builtin function with an incompatible
1247    // signature.
1248    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
1249      // The function the user is redeclaring is a library-defined
1250      // function like 'malloc' or 'printf'. Warn about the
1251      // redeclaration, then pretend that we don't know about this
1252      // library built-in.
1253      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
1254      Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
1255        << Old << Old->getType();
1256      New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin);
1257      Old->setInvalidDecl();
1258      return false;
1259    }
1260
1261    PrevDiag = diag::note_previous_builtin_declaration;
1262  }
1263
1264  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
1265  Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
1266  return true;
1267}
1268
1269/// \brief Completes the merge of two function declarations that are
1270/// known to be compatible.
1271///
1272/// This routine handles the merging of attributes and other
1273/// properties of function declarations form the old declaration to
1274/// the new declaration, once we know that New is in fact a
1275/// redeclaration of Old.
1276///
1277/// \returns false
1278bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
1279  // Merge the attributes
1280  MergeAttributes(New, Old, Context);
1281
1282  // Merge the storage class.
1283  if (Old->getStorageClass() != FunctionDecl::Extern &&
1284      Old->getStorageClass() != FunctionDecl::None)
1285    New->setStorageClass(Old->getStorageClass());
1286
1287  // Merge "pure" flag.
1288  if (Old->isPure())
1289    New->setPure();
1290
1291  // Merge the "deleted" flag.
1292  if (Old->isDeleted())
1293    New->setDeleted();
1294
1295  if (getLangOptions().CPlusPlus)
1296    return MergeCXXFunctionDecl(New, Old);
1297
1298  return false;
1299}
1300
1301/// MergeVarDecl - We just parsed a variable 'New' which has the same name
1302/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
1303/// situation, merging decls or emitting diagnostics as appropriate.
1304///
1305/// Tentative definition rules (C99 6.9.2p2) are checked by
1306/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
1307/// definitions here, since the initializer hasn't been attached.
1308///
1309void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
1310  // If the new decl is already invalid, don't do any other checking.
1311  if (New->isInvalidDecl())
1312    return;
1313
1314  // Verify the old decl was also a variable.
1315  VarDecl *Old = 0;
1316  if (!Previous.isSingleResult() ||
1317      !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) {
1318    Diag(New->getLocation(), diag::err_redefinition_different_kind)
1319      << New->getDeclName();
1320    Diag(Previous.getRepresentativeDecl()->getLocation(),
1321         diag::note_previous_definition);
1322    return New->setInvalidDecl();
1323  }
1324
1325  MergeAttributes(New, Old, Context);
1326
1327  // Merge the types
1328  QualType MergedT;
1329  if (getLangOptions().CPlusPlus) {
1330    if (Context.hasSameType(New->getType(), Old->getType()))
1331      MergedT = New->getType();
1332    // C++ [basic.link]p10:
1333    //   [...] the types specified by all declarations referring to a given
1334    //   object or function shall be identical, except that declarations for an
1335    //   array object can specify array types that differ by the presence or
1336    //   absence of a major array bound (8.3.4).
1337    else if (Old->getType()->isIncompleteArrayType() &&
1338             New->getType()->isArrayType()) {
1339      CanQual<ArrayType> OldArray
1340        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1341      CanQual<ArrayType> NewArray
1342        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1343      if (OldArray->getElementType() == NewArray->getElementType())
1344        MergedT = New->getType();
1345    } else if (Old->getType()->isArrayType() &&
1346             New->getType()->isIncompleteArrayType()) {
1347      CanQual<ArrayType> OldArray
1348        = Context.getCanonicalType(Old->getType())->getAs<ArrayType>();
1349      CanQual<ArrayType> NewArray
1350        = Context.getCanonicalType(New->getType())->getAs<ArrayType>();
1351      if (OldArray->getElementType() == NewArray->getElementType())
1352        MergedT = Old->getType();
1353    }
1354  } else {
1355    MergedT = Context.mergeTypes(New->getType(), Old->getType());
1356  }
1357  if (MergedT.isNull()) {
1358    Diag(New->getLocation(), diag::err_redefinition_different_type)
1359      << New->getDeclName();
1360    Diag(Old->getLocation(), diag::note_previous_definition);
1361    return New->setInvalidDecl();
1362  }
1363  New->setType(MergedT);
1364
1365  // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
1366  if (New->getStorageClass() == VarDecl::Static &&
1367      (Old->getStorageClass() == VarDecl::None || Old->hasExternalStorage())) {
1368    Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
1369    Diag(Old->getLocation(), diag::note_previous_definition);
1370    return New->setInvalidDecl();
1371  }
1372  // C99 6.2.2p4:
1373  //   For an identifier declared with the storage-class specifier
1374  //   extern in a scope in which a prior declaration of that
1375  //   identifier is visible,23) if the prior declaration specifies
1376  //   internal or external linkage, the linkage of the identifier at
1377  //   the later declaration is the same as the linkage specified at
1378  //   the prior declaration. If no prior declaration is visible, or
1379  //   if the prior declaration specifies no linkage, then the
1380  //   identifier has external linkage.
1381  if (New->hasExternalStorage() && Old->hasLinkage())
1382    /* Okay */;
1383  else if (New->getStorageClass() != VarDecl::Static &&
1384           Old->getStorageClass() == VarDecl::Static) {
1385    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
1386    Diag(Old->getLocation(), diag::note_previous_definition);
1387    return New->setInvalidDecl();
1388  }
1389
1390  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
1391
1392  // FIXME: The test for external storage here seems wrong? We still
1393  // need to check for mismatches.
1394  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
1395      // Don't complain about out-of-line definitions of static members.
1396      !(Old->getLexicalDeclContext()->isRecord() &&
1397        !New->getLexicalDeclContext()->isRecord())) {
1398    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
1399    Diag(Old->getLocation(), diag::note_previous_definition);
1400    return New->setInvalidDecl();
1401  }
1402
1403  if (New->isThreadSpecified() && !Old->isThreadSpecified()) {
1404    Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
1405    Diag(Old->getLocation(), diag::note_previous_definition);
1406  } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) {
1407    Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
1408    Diag(Old->getLocation(), diag::note_previous_definition);
1409  }
1410
1411  // C++ doesn't have tentative definitions, so go right ahead and check here.
1412  const VarDecl *Def;
1413  if (getLangOptions().CPlusPlus &&
1414      New->isThisDeclarationADefinition() == VarDecl::Definition &&
1415      (Def = Old->getDefinition())) {
1416    Diag(New->getLocation(), diag::err_redefinition)
1417      << New->getDeclName();
1418    Diag(Def->getLocation(), diag::note_previous_definition);
1419    New->setInvalidDecl();
1420    return;
1421  }
1422
1423  // Keep a chain of previous declarations.
1424  New->setPreviousDeclaration(Old);
1425
1426  // Inherit access appropriately.
1427  New->setAccess(Old->getAccess());
1428}
1429
1430/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
1431/// no declarator (e.g. "struct foo;") is parsed.
1432Sema::DeclPtrTy Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
1433  // FIXME: Error on auto/register at file scope
1434  // FIXME: Error on inline/virtual/explicit
1435  // FIXME: Warn on useless __thread
1436  // FIXME: Warn on useless const/volatile
1437  // FIXME: Warn on useless static/extern/typedef/private_extern/mutable
1438  // FIXME: Warn on useless attributes
1439  Decl *TagD = 0;
1440  TagDecl *Tag = 0;
1441  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
1442      DS.getTypeSpecType() == DeclSpec::TST_struct ||
1443      DS.getTypeSpecType() == DeclSpec::TST_union ||
1444      DS.getTypeSpecType() == DeclSpec::TST_enum) {
1445    TagD = static_cast<Decl *>(DS.getTypeRep());
1446
1447    if (!TagD) // We probably had an error
1448      return DeclPtrTy();
1449
1450    // Note that the above type specs guarantee that the
1451    // type rep is a Decl, whereas in many of the others
1452    // it's a Type.
1453    Tag = dyn_cast<TagDecl>(TagD);
1454  }
1455
1456  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1457    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
1458    // or incomplete types shall not be restrict-qualified."
1459    if (TypeQuals & DeclSpec::TQ_restrict)
1460      Diag(DS.getRestrictSpecLoc(),
1461           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
1462           << DS.getSourceRange();
1463  }
1464
1465  if (DS.isFriendSpecified()) {
1466    // If we're dealing with a class template decl, assume that the
1467    // template routines are handling it.
1468    if (TagD && isa<ClassTemplateDecl>(TagD))
1469      return DeclPtrTy();
1470    return ActOnFriendTypeDecl(S, DS, MultiTemplateParamsArg(*this, 0, 0));
1471  }
1472
1473  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
1474    // If there are attributes in the DeclSpec, apply them to the record.
1475    if (const AttributeList *AL = DS.getAttributes())
1476      ProcessDeclAttributeList(S, Record, AL);
1477
1478    if (!Record->getDeclName() && Record->isDefinition() &&
1479        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
1480      if (getLangOptions().CPlusPlus ||
1481          Record->getDeclContext()->isRecord())
1482        return BuildAnonymousStructOrUnion(S, DS, Record);
1483
1484      Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1485        << DS.getSourceRange();
1486    }
1487
1488    // Microsoft allows unnamed struct/union fields. Don't complain
1489    // about them.
1490    // FIXME: Should we support Microsoft's extensions in this area?
1491    if (Record->getDeclName() && getLangOptions().Microsoft)
1492      return DeclPtrTy::make(Tag);
1493  }
1494
1495  if (!DS.isMissingDeclaratorOk() &&
1496      DS.getTypeSpecType() != DeclSpec::TST_error) {
1497    // Warn about typedefs of enums without names, since this is an
1498    // extension in both Microsoft an GNU.
1499    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
1500        Tag && isa<EnumDecl>(Tag)) {
1501      Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
1502        << DS.getSourceRange();
1503      return DeclPtrTy::make(Tag);
1504    }
1505
1506    Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
1507      << DS.getSourceRange();
1508  }
1509
1510  return DeclPtrTy::make(Tag);
1511}
1512
1513/// We are trying to inject an anonymous member into the given scope;
1514/// check if there's an existing declaration that can't be overloaded.
1515///
1516/// \return true if this is a forbidden redeclaration
1517static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
1518                                         Scope *S,
1519                                         DeclContext *Owner,
1520                                         DeclarationName Name,
1521                                         SourceLocation NameLoc,
1522                                         unsigned diagnostic) {
1523  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
1524                 Sema::ForRedeclaration);
1525  if (!SemaRef.LookupName(R, S)) return false;
1526
1527  if (R.getAsSingle<TagDecl>())
1528    return false;
1529
1530  // Pick a representative declaration.
1531  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
1532  if (PrevDecl && Owner->isRecord()) {
1533    RecordDecl *Record = cast<RecordDecl>(Owner);
1534    if (!SemaRef.isDeclInScope(PrevDecl, Record, S))
1535      return false;
1536  }
1537
1538  SemaRef.Diag(NameLoc, diagnostic) << Name;
1539  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
1540
1541  return true;
1542}
1543
1544/// InjectAnonymousStructOrUnionMembers - Inject the members of the
1545/// anonymous struct or union AnonRecord into the owning context Owner
1546/// and scope S. This routine will be invoked just after we realize
1547/// that an unnamed union or struct is actually an anonymous union or
1548/// struct, e.g.,
1549///
1550/// @code
1551/// union {
1552///   int i;
1553///   float f;
1554/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
1555///    // f into the surrounding scope.x
1556/// @endcode
1557///
1558/// This routine is recursive, injecting the names of nested anonymous
1559/// structs/unions into the owning context and scope as well.
1560bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
1561                                               RecordDecl *AnonRecord) {
1562  unsigned diagKind
1563    = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl
1564                            : diag::err_anonymous_struct_member_redecl;
1565
1566  bool Invalid = false;
1567  for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
1568                               FEnd = AnonRecord->field_end();
1569       F != FEnd; ++F) {
1570    if ((*F)->getDeclName()) {
1571      if (CheckAnonMemberRedeclaration(*this, S, Owner, (*F)->getDeclName(),
1572                                       (*F)->getLocation(), diagKind)) {
1573        // C++ [class.union]p2:
1574        //   The names of the members of an anonymous union shall be
1575        //   distinct from the names of any other entity in the
1576        //   scope in which the anonymous union is declared.
1577        Invalid = true;
1578      } else {
1579        // C++ [class.union]p2:
1580        //   For the purpose of name lookup, after the anonymous union
1581        //   definition, the members of the anonymous union are
1582        //   considered to have been defined in the scope in which the
1583        //   anonymous union is declared.
1584        Owner->makeDeclVisibleInContext(*F);
1585        S->AddDecl(DeclPtrTy::make(*F));
1586        IdResolver.AddDecl(*F);
1587      }
1588    } else if (const RecordType *InnerRecordType
1589                 = (*F)->getType()->getAs<RecordType>()) {
1590      RecordDecl *InnerRecord = InnerRecordType->getDecl();
1591      if (InnerRecord->isAnonymousStructOrUnion())
1592        Invalid = Invalid ||
1593          InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
1594    }
1595  }
1596
1597  return Invalid;
1598}
1599
1600/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
1601/// a VarDecl::StorageClass. Any error reporting is up to the caller:
1602/// illegal input values are mapped to VarDecl::None.
1603static VarDecl::StorageClass
1604StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1605  switch (StorageClassSpec) {
1606  case DeclSpec::SCS_unspecified:    return VarDecl::None;
1607  case DeclSpec::SCS_extern:         return VarDecl::Extern;
1608  case DeclSpec::SCS_static:         return VarDecl::Static;
1609  case DeclSpec::SCS_auto:           return VarDecl::Auto;
1610  case DeclSpec::SCS_register:       return VarDecl::Register;
1611  case DeclSpec::SCS_private_extern: return VarDecl::PrivateExtern;
1612    // Illegal SCSs map to None: error reporting is up to the caller.
1613  case DeclSpec::SCS_mutable:        // Fall through.
1614  case DeclSpec::SCS_typedef:        return VarDecl::None;
1615  }
1616  llvm_unreachable("unknown storage class specifier");
1617}
1618
1619/// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to
1620/// a FunctionDecl::StorageClass. Any error reporting is up to the caller:
1621/// illegal input values are mapped to FunctionDecl::None.
1622static FunctionDecl::StorageClass
1623StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) {
1624  switch (StorageClassSpec) {
1625  case DeclSpec::SCS_unspecified:    return FunctionDecl::None;
1626  case DeclSpec::SCS_extern:         return FunctionDecl::Extern;
1627  case DeclSpec::SCS_static:         return FunctionDecl::Static;
1628  case DeclSpec::SCS_private_extern: return FunctionDecl::PrivateExtern;
1629    // Illegal SCSs map to None: error reporting is up to the caller.
1630  case DeclSpec::SCS_auto:           // Fall through.
1631  case DeclSpec::SCS_mutable:        // Fall through.
1632  case DeclSpec::SCS_register:       // Fall through.
1633  case DeclSpec::SCS_typedef:        return FunctionDecl::None;
1634  }
1635  llvm_unreachable("unknown storage class specifier");
1636}
1637
1638/// ActOnAnonymousStructOrUnion - Handle the declaration of an
1639/// anonymous structure or union. Anonymous unions are a C++ feature
1640/// (C++ [class.union]) and a GNU C extension; anonymous structures
1641/// are a GNU C and GNU C++ extension.
1642Sema::DeclPtrTy Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
1643                                                  RecordDecl *Record) {
1644  DeclContext *Owner = Record->getDeclContext();
1645
1646  // Diagnose whether this anonymous struct/union is an extension.
1647  if (Record->isUnion() && !getLangOptions().CPlusPlus)
1648    Diag(Record->getLocation(), diag::ext_anonymous_union);
1649  else if (!Record->isUnion())
1650    Diag(Record->getLocation(), diag::ext_anonymous_struct);
1651
1652  // C and C++ require different kinds of checks for anonymous
1653  // structs/unions.
1654  bool Invalid = false;
1655  if (getLangOptions().CPlusPlus) {
1656    const char* PrevSpec = 0;
1657    unsigned DiagID;
1658    // C++ [class.union]p3:
1659    //   Anonymous unions declared in a named namespace or in the
1660    //   global namespace shall be declared static.
1661    if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1662        (isa<TranslationUnitDecl>(Owner) ||
1663         (isa<NamespaceDecl>(Owner) &&
1664          cast<NamespaceDecl>(Owner)->getDeclName()))) {
1665      Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1666      Invalid = true;
1667
1668      // Recover by adding 'static'.
1669      DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(),
1670                             PrevSpec, DiagID);
1671    }
1672    // C++ [class.union]p3:
1673    //   A storage class is not allowed in a declaration of an
1674    //   anonymous union in a class scope.
1675    else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1676             isa<RecordDecl>(Owner)) {
1677      Diag(DS.getStorageClassSpecLoc(),
1678           diag::err_anonymous_union_with_storage_spec);
1679      Invalid = true;
1680
1681      // Recover by removing the storage specifier.
1682      DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1683                             PrevSpec, DiagID);
1684    }
1685
1686    // C++ [class.union]p2:
1687    //   The member-specification of an anonymous union shall only
1688    //   define non-static data members. [Note: nested types and
1689    //   functions cannot be declared within an anonymous union. ]
1690    for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1691                                 MemEnd = Record->decls_end();
1692         Mem != MemEnd; ++Mem) {
1693      if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1694        // C++ [class.union]p3:
1695        //   An anonymous union shall not have private or protected
1696        //   members (clause 11).
1697        if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1698          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1699            << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1700          Invalid = true;
1701        }
1702      } else if ((*Mem)->isImplicit()) {
1703        // Any implicit members are fine.
1704      } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1705        // This is a type that showed up in an
1706        // elaborated-type-specifier inside the anonymous struct or
1707        // union, but which actually declares a type outside of the
1708        // anonymous struct or union. It's okay.
1709      } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1710        if (!MemRecord->isAnonymousStructOrUnion() &&
1711            MemRecord->getDeclName()) {
1712          // This is a nested type declaration.
1713          Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1714            << (int)Record->isUnion();
1715          Invalid = true;
1716        }
1717      } else {
1718        // We have something that isn't a non-static data
1719        // member. Complain about it.
1720        unsigned DK = diag::err_anonymous_record_bad_member;
1721        if (isa<TypeDecl>(*Mem))
1722          DK = diag::err_anonymous_record_with_type;
1723        else if (isa<FunctionDecl>(*Mem))
1724          DK = diag::err_anonymous_record_with_function;
1725        else if (isa<VarDecl>(*Mem))
1726          DK = diag::err_anonymous_record_with_static;
1727        Diag((*Mem)->getLocation(), DK)
1728            << (int)Record->isUnion();
1729          Invalid = true;
1730      }
1731    }
1732  }
1733
1734  if (!Record->isUnion() && !Owner->isRecord()) {
1735    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1736      << (int)getLangOptions().CPlusPlus;
1737    Invalid = true;
1738  }
1739
1740  // Mock up a declarator.
1741  Declarator Dc(DS, Declarator::TypeNameContext);
1742  TypeSourceInfo *TInfo = 0;
1743  GetTypeForDeclarator(Dc, S, &TInfo);
1744  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
1745
1746  // Create a declaration for this anonymous struct/union.
1747  NamedDecl *Anon = 0;
1748  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1749    Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1750                             /*IdentifierInfo=*/0,
1751                             Context.getTypeDeclType(Record),
1752                             TInfo,
1753                             /*BitWidth=*/0, /*Mutable=*/false);
1754    Anon->setAccess(AS_public);
1755    if (getLangOptions().CPlusPlus)
1756      FieldCollector->Add(cast<FieldDecl>(Anon));
1757  } else {
1758    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
1759    assert(SCSpec != DeclSpec::SCS_typedef &&
1760           "Parser allowed 'typedef' as storage class VarDecl.");
1761    VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
1762    if (SCSpec == DeclSpec::SCS_mutable) {
1763      // mutable can only appear on non-static class members, so it's always
1764      // an error here
1765      Diag(Record->getLocation(), diag::err_mutable_nonmember);
1766      Invalid = true;
1767      SC = VarDecl::None;
1768    }
1769    SCSpec = DS.getStorageClassSpecAsWritten();
1770    VarDecl::StorageClass SCAsWritten
1771      = StorageClassSpecToVarDeclStorageClass(SCSpec);
1772
1773    Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1774                           /*IdentifierInfo=*/0,
1775                           Context.getTypeDeclType(Record),
1776                           TInfo, SC, SCAsWritten);
1777  }
1778  Anon->setImplicit();
1779
1780  // Add the anonymous struct/union object to the current
1781  // context. We'll be referencing this object when we refer to one of
1782  // its members.
1783  Owner->addDecl(Anon);
1784
1785  // Inject the members of the anonymous struct/union into the owning
1786  // context and into the identifier resolver chain for name lookup
1787  // purposes.
1788  if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1789    Invalid = true;
1790
1791  // Mark this as an anonymous struct/union type. Note that we do not
1792  // do this until after we have already checked and injected the
1793  // members of this anonymous struct/union type, because otherwise
1794  // the members could be injected twice: once by DeclContext when it
1795  // builds its lookup table, and once by
1796  // InjectAnonymousStructOrUnionMembers.
1797  Record->setAnonymousStructOrUnion(true);
1798
1799  if (Invalid)
1800    Anon->setInvalidDecl();
1801
1802  return DeclPtrTy::make(Anon);
1803}
1804
1805
1806/// GetNameForDeclarator - Determine the full declaration name for the
1807/// given Declarator.
1808DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1809  return GetNameFromUnqualifiedId(D.getName());
1810}
1811
1812/// \brief Retrieves the canonicalized name from a parsed unqualified-id.
1813DeclarationName Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
1814  switch (Name.getKind()) {
1815    case UnqualifiedId::IK_Identifier:
1816      return DeclarationName(Name.Identifier);
1817
1818    case UnqualifiedId::IK_OperatorFunctionId:
1819      return Context.DeclarationNames.getCXXOperatorName(
1820                                              Name.OperatorFunctionId.Operator);
1821
1822    case UnqualifiedId::IK_LiteralOperatorId:
1823      return Context.DeclarationNames.getCXXLiteralOperatorName(
1824                                                               Name.Identifier);
1825
1826    case UnqualifiedId::IK_ConversionFunctionId: {
1827      QualType Ty = GetTypeFromParser(Name.ConversionFunctionId);
1828      if (Ty.isNull())
1829        return DeclarationName();
1830
1831      return Context.DeclarationNames.getCXXConversionFunctionName(
1832                                                  Context.getCanonicalType(Ty));
1833    }
1834
1835    case UnqualifiedId::IK_ConstructorName: {
1836      QualType Ty = GetTypeFromParser(Name.ConstructorName);
1837      if (Ty.isNull())
1838        return DeclarationName();
1839
1840      return Context.DeclarationNames.getCXXConstructorName(
1841                                                  Context.getCanonicalType(Ty));
1842    }
1843
1844    case UnqualifiedId::IK_ConstructorTemplateId: {
1845      // In well-formed code, we can only have a constructor
1846      // template-id that refers to the current context, so go there
1847      // to find the actual type being constructed.
1848      CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
1849      if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
1850        return DeclarationName();
1851
1852      // Determine the type of the class being constructed.
1853      QualType CurClassType = Context.getTypeDeclType(CurClass);
1854
1855      // FIXME: Check two things: that the template-id names the same type as
1856      // CurClassType, and that the template-id does not occur when the name
1857      // was qualified.
1858
1859      return Context.DeclarationNames.getCXXConstructorName(
1860                                       Context.getCanonicalType(CurClassType));
1861    }
1862
1863    case UnqualifiedId::IK_DestructorName: {
1864      QualType Ty = GetTypeFromParser(Name.DestructorName);
1865      if (Ty.isNull())
1866        return DeclarationName();
1867
1868      return Context.DeclarationNames.getCXXDestructorName(
1869                                                           Context.getCanonicalType(Ty));
1870    }
1871
1872    case UnqualifiedId::IK_TemplateId: {
1873      TemplateName TName
1874        = TemplateName::getFromVoidPointer(Name.TemplateId->Template);
1875      return Context.getNameForTemplate(TName);
1876    }
1877  }
1878
1879  assert(false && "Unknown name kind");
1880  return DeclarationName();
1881}
1882
1883/// isNearlyMatchingFunction - Determine whether the C++ functions
1884/// Declaration and Definition are "nearly" matching. This heuristic
1885/// is used to improve diagnostics in the case where an out-of-line
1886/// function definition doesn't match any declaration within
1887/// the class or namespace.
1888static bool isNearlyMatchingFunction(ASTContext &Context,
1889                                     FunctionDecl *Declaration,
1890                                     FunctionDecl *Definition) {
1891  if (Declaration->param_size() != Definition->param_size())
1892    return false;
1893  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1894    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1895    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1896
1897    if (!Context.hasSameUnqualifiedType(DeclParamTy.getNonReferenceType(),
1898                                        DefParamTy.getNonReferenceType()))
1899      return false;
1900  }
1901
1902  return true;
1903}
1904
1905Sema::DeclPtrTy
1906Sema::HandleDeclarator(Scope *S, Declarator &D,
1907                       MultiTemplateParamsArg TemplateParamLists,
1908                       bool IsFunctionDefinition) {
1909  DeclarationName Name = GetNameForDeclarator(D);
1910
1911  // All of these full declarators require an identifier.  If it doesn't have
1912  // one, the ParsedFreeStandingDeclSpec action should be used.
1913  if (!Name) {
1914    if (!D.isInvalidType())  // Reject this if we think it is valid.
1915      Diag(D.getDeclSpec().getSourceRange().getBegin(),
1916           diag::err_declarator_need_ident)
1917        << D.getDeclSpec().getSourceRange() << D.getSourceRange();
1918    return DeclPtrTy();
1919  }
1920
1921  // The scope passed in may not be a decl scope.  Zip up the scope tree until
1922  // we find one that is.
1923  while ((S->getFlags() & Scope::DeclScope) == 0 ||
1924         (S->getFlags() & Scope::TemplateParamScope) != 0)
1925    S = S->getParent();
1926
1927  // If this is an out-of-line definition of a member of a class template
1928  // or class template partial specialization, we may need to rebuild the
1929  // type specifier in the declarator. See RebuildTypeInCurrentInstantiation()
1930  // for more information.
1931  // FIXME: cope with decltype(expr) and typeof(expr) once the rebuilder can
1932  // handle expressions properly.
1933  DeclSpec &DS = const_cast<DeclSpec&>(D.getDeclSpec());
1934  if (D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid() &&
1935      isDependentScopeSpecifier(D.getCXXScopeSpec()) &&
1936      (DS.getTypeSpecType() == DeclSpec::TST_typename ||
1937       DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
1938       DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
1939       DS.getTypeSpecType() == DeclSpec::TST_decltype)) {
1940    if (DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(), true)) {
1941      // FIXME: Preserve type source info.
1942      QualType T = GetTypeFromParser(DS.getTypeRep());
1943
1944      DeclContext *SavedContext = CurContext;
1945      CurContext = DC;
1946      T = RebuildTypeInCurrentInstantiation(T, D.getIdentifierLoc(), Name);
1947      CurContext = SavedContext;
1948
1949      if (T.isNull())
1950        return DeclPtrTy();
1951      DS.UpdateTypeRep(T.getAsOpaquePtr());
1952    }
1953  }
1954
1955  DeclContext *DC;
1956  NamedDecl *New;
1957
1958  TypeSourceInfo *TInfo = 0;
1959  QualType R = GetTypeForDeclarator(D, S, &TInfo);
1960
1961  LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
1962                        ForRedeclaration);
1963
1964  // See if this is a redefinition of a variable in the same scope.
1965  if (D.getCXXScopeSpec().isInvalid()) {
1966    DC = CurContext;
1967    D.setInvalidType();
1968  } else if (!D.getCXXScopeSpec().isSet()) {
1969    bool IsLinkageLookup = false;
1970
1971    // If the declaration we're planning to build will be a function
1972    // or object with linkage, then look for another declaration with
1973    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1974    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1975      /* Do nothing*/;
1976    else if (R->isFunctionType()) {
1977      if (CurContext->isFunctionOrMethod() ||
1978          D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1979        IsLinkageLookup = true;
1980    } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1981      IsLinkageLookup = true;
1982    else if (CurContext->getLookupContext()->isTranslationUnit() &&
1983             D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
1984      IsLinkageLookup = true;
1985
1986    if (IsLinkageLookup)
1987      Previous.clear(LookupRedeclarationWithLinkage);
1988
1989    DC = CurContext;
1990    LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup);
1991  } else { // Something like "int foo::x;"
1992    DC = computeDeclContext(D.getCXXScopeSpec(), true);
1993
1994    if (!DC) {
1995      // If we could not compute the declaration context, it's because the
1996      // declaration context is dependent but does not refer to a class,
1997      // class template, or class template partial specialization. Complain
1998      // and return early, to avoid the coming semantic disaster.
1999      Diag(D.getIdentifierLoc(),
2000           diag::err_template_qualified_declarator_no_match)
2001        << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep()
2002        << D.getCXXScopeSpec().getRange();
2003      return DeclPtrTy();
2004    }
2005
2006    if (!DC->isDependentContext() &&
2007        RequireCompleteDeclContext(D.getCXXScopeSpec()))
2008      return DeclPtrTy();
2009
2010    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
2011      Diag(D.getIdentifierLoc(),
2012           diag::err_member_def_undefined_record)
2013        << Name << DC << D.getCXXScopeSpec().getRange();
2014      D.setInvalidType();
2015    }
2016
2017    LookupQualifiedName(Previous, DC);
2018
2019    // Don't consider using declarations as previous declarations for
2020    // out-of-line members.
2021    RemoveUsingDecls(Previous);
2022
2023    // C++ 7.3.1.2p2:
2024    // Members (including explicit specializations of templates) of a named
2025    // namespace can also be defined outside that namespace by explicit
2026    // qualification of the name being defined, provided that the entity being
2027    // defined was already declared in the namespace and the definition appears
2028    // after the point of declaration in a namespace that encloses the
2029    // declarations namespace.
2030    //
2031    // Note that we only check the context at this point. We don't yet
2032    // have enough information to make sure that PrevDecl is actually
2033    // the declaration we want to match. For example, given:
2034    //
2035    //   class X {
2036    //     void f();
2037    //     void f(float);
2038    //   };
2039    //
2040    //   void X::f(int) { } // ill-formed
2041    //
2042    // In this case, PrevDecl will point to the overload set
2043    // containing the two f's declared in X, but neither of them
2044    // matches.
2045
2046    // First check whether we named the global scope.
2047    if (isa<TranslationUnitDecl>(DC)) {
2048      Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
2049        << Name << D.getCXXScopeSpec().getRange();
2050    } else {
2051      DeclContext *Cur = CurContext;
2052      while (isa<LinkageSpecDecl>(Cur))
2053        Cur = Cur->getParent();
2054      if (!Cur->Encloses(DC)) {
2055        // The qualifying scope doesn't enclose the original declaration.
2056        // Emit diagnostic based on current scope.
2057        SourceLocation L = D.getIdentifierLoc();
2058        SourceRange R = D.getCXXScopeSpec().getRange();
2059        if (isa<FunctionDecl>(Cur))
2060          Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
2061        else
2062          Diag(L, diag::err_invalid_declarator_scope)
2063            << Name << cast<NamedDecl>(DC) << R;
2064        D.setInvalidType();
2065      }
2066    }
2067  }
2068
2069  if (Previous.isSingleResult() &&
2070      Previous.getFoundDecl()->isTemplateParameter()) {
2071    // Maybe we will complain about the shadowed template parameter.
2072    if (!D.isInvalidType())
2073      if (DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
2074                                          Previous.getFoundDecl()))
2075        D.setInvalidType();
2076
2077    // Just pretend that we didn't see the previous declaration.
2078    Previous.clear();
2079  }
2080
2081  // In C++, the previous declaration we find might be a tag type
2082  // (class or enum). In this case, the new declaration will hide the
2083  // tag type. Note that this does does not apply if we're declaring a
2084  // typedef (C++ [dcl.typedef]p4).
2085  if (Previous.isSingleTagDecl() &&
2086      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
2087    Previous.clear();
2088
2089  bool Redeclaration = false;
2090  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
2091    if (TemplateParamLists.size()) {
2092      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
2093      return DeclPtrTy();
2094    }
2095
2096    New = ActOnTypedefDeclarator(S, D, DC, R, TInfo, Previous, Redeclaration);
2097  } else if (R->isFunctionType()) {
2098    New = ActOnFunctionDeclarator(S, D, DC, R, TInfo, Previous,
2099                                  move(TemplateParamLists),
2100                                  IsFunctionDefinition, Redeclaration);
2101  } else {
2102    New = ActOnVariableDeclarator(S, D, DC, R, TInfo, Previous,
2103                                  move(TemplateParamLists),
2104                                  Redeclaration);
2105  }
2106
2107  if (New == 0)
2108    return DeclPtrTy();
2109
2110  // If this has an identifier and is not an invalid redeclaration or
2111  // function template specialization, add it to the scope stack.
2112  if (Name && !(Redeclaration && New->isInvalidDecl()))
2113    PushOnScopeChains(New, S);
2114
2115  return DeclPtrTy::make(New);
2116}
2117
2118/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2119/// types into constant array types in certain situations which would otherwise
2120/// be errors (for GCC compatibility).
2121static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2122                                                    ASTContext &Context,
2123                                                    bool &SizeIsNegative) {
2124  // This method tries to turn a variable array into a constant
2125  // array even when the size isn't an ICE.  This is necessary
2126  // for compatibility with code that depends on gcc's buggy
2127  // constant expression folding, like struct {char x[(int)(char*)2];}
2128  SizeIsNegative = false;
2129
2130  QualifierCollector Qs;
2131  const Type *Ty = Qs.strip(T);
2132
2133  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
2134    QualType Pointee = PTy->getPointeeType();
2135    QualType FixedType =
2136        TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
2137    if (FixedType.isNull()) return FixedType;
2138    FixedType = Context.getPointerType(FixedType);
2139    return Qs.apply(FixedType);
2140  }
2141
2142  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2143  if (!VLATy)
2144    return QualType();
2145  // FIXME: We should probably handle this case
2146  if (VLATy->getElementType()->isVariablyModifiedType())
2147    return QualType();
2148
2149  Expr::EvalResult EvalResult;
2150  if (!VLATy->getSizeExpr() ||
2151      !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
2152      !EvalResult.Val.isInt())
2153    return QualType();
2154
2155  llvm::APSInt &Res = EvalResult.Val.getInt();
2156  if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) {
2157    // TODO: preserve the size expression in declarator info
2158    return Context.getConstantArrayType(VLATy->getElementType(),
2159                                        Res, ArrayType::Normal, 0);
2160  }
2161
2162  SizeIsNegative = true;
2163  return QualType();
2164}
2165
2166/// \brief Register the given locally-scoped external C declaration so
2167/// that it can be found later for redeclarations
2168void
2169Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND,
2170                                       const LookupResult &Previous,
2171                                       Scope *S) {
2172  assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
2173         "Decl is not a locally-scoped decl!");
2174  // Note that we have a locally-scoped external with this name.
2175  LocallyScopedExternalDecls[ND->getDeclName()] = ND;
2176
2177  if (!Previous.isSingleResult())
2178    return;
2179
2180  NamedDecl *PrevDecl = Previous.getFoundDecl();
2181
2182  // If there was a previous declaration of this variable, it may be
2183  // in our identifier chain. Update the identifier chain with the new
2184  // declaration.
2185  if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) {
2186    // The previous declaration was found on the identifer resolver
2187    // chain, so remove it from its scope.
2188    while (S && !S->isDeclScope(DeclPtrTy::make(PrevDecl)))
2189      S = S->getParent();
2190
2191    if (S)
2192      S->RemoveDecl(DeclPtrTy::make(PrevDecl));
2193  }
2194}
2195
2196/// \brief Diagnose function specifiers on a declaration of an identifier that
2197/// does not identify a function.
2198void Sema::DiagnoseFunctionSpecifiers(Declarator& D) {
2199  // FIXME: We should probably indicate the identifier in question to avoid
2200  // confusion for constructs like "inline int a(), b;"
2201  if (D.getDeclSpec().isInlineSpecified())
2202    Diag(D.getDeclSpec().getInlineSpecLoc(),
2203         diag::err_inline_non_function);
2204
2205  if (D.getDeclSpec().isVirtualSpecified())
2206    Diag(D.getDeclSpec().getVirtualSpecLoc(),
2207         diag::err_virtual_non_function);
2208
2209  if (D.getDeclSpec().isExplicitSpecified())
2210    Diag(D.getDeclSpec().getExplicitSpecLoc(),
2211         diag::err_explicit_non_function);
2212}
2213
2214NamedDecl*
2215Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2216                             QualType R,  TypeSourceInfo *TInfo,
2217                             LookupResult &Previous, bool &Redeclaration) {
2218  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
2219  if (D.getCXXScopeSpec().isSet()) {
2220    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
2221      << D.getCXXScopeSpec().getRange();
2222    D.setInvalidType();
2223    // Pretend we didn't see the scope specifier.
2224    DC = CurContext;
2225    Previous.clear();
2226  }
2227
2228  if (getLangOptions().CPlusPlus) {
2229    // Check that there are no default arguments (C++ only).
2230    CheckExtraCXXDefaultArguments(D);
2231  }
2232
2233  DiagnoseFunctionSpecifiers(D);
2234
2235  if (D.getDeclSpec().isThreadSpecified())
2236    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2237
2238  TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, TInfo);
2239  if (!NewTD) return 0;
2240
2241  // Handle attributes prior to checking for duplicates in MergeVarDecl
2242  ProcessDeclAttributes(S, NewTD, D);
2243
2244  // Merge the decl with the existing one if appropriate. If the decl is
2245  // in an outer scope, it isn't the same thing.
2246  FilterLookupForScope(*this, Previous, DC, S, /*ConsiderLinkage*/ false);
2247  if (!Previous.empty()) {
2248    Redeclaration = true;
2249    MergeTypeDefDecl(NewTD, Previous);
2250  }
2251
2252  // C99 6.7.7p2: If a typedef name specifies a variably modified type
2253  // then it shall have block scope.
2254  QualType T = NewTD->getUnderlyingType();
2255  if (T->isVariablyModifiedType()) {
2256    FunctionNeedsScopeChecking() = true;
2257
2258    if (S->getFnParent() == 0) {
2259      bool SizeIsNegative;
2260      QualType FixedTy =
2261          TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2262      if (!FixedTy.isNull()) {
2263        Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
2264        NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy));
2265      } else {
2266        if (SizeIsNegative)
2267          Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
2268        else if (T->isVariableArrayType())
2269          Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
2270        else
2271          Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
2272        NewTD->setInvalidDecl();
2273      }
2274    }
2275  }
2276
2277  // If this is the C FILE type, notify the AST context.
2278  if (IdentifierInfo *II = NewTD->getIdentifier())
2279    if (!NewTD->isInvalidDecl() &&
2280        NewTD->getDeclContext()->getLookupContext()->isTranslationUnit()) {
2281      if (II->isStr("FILE"))
2282        Context.setFILEDecl(NewTD);
2283      else if (II->isStr("jmp_buf"))
2284        Context.setjmp_bufDecl(NewTD);
2285      else if (II->isStr("sigjmp_buf"))
2286        Context.setsigjmp_bufDecl(NewTD);
2287    }
2288
2289  return NewTD;
2290}
2291
2292/// \brief Determines whether the given declaration is an out-of-scope
2293/// previous declaration.
2294///
2295/// This routine should be invoked when name lookup has found a
2296/// previous declaration (PrevDecl) that is not in the scope where a
2297/// new declaration by the same name is being introduced. If the new
2298/// declaration occurs in a local scope, previous declarations with
2299/// linkage may still be considered previous declarations (C99
2300/// 6.2.2p4-5, C++ [basic.link]p6).
2301///
2302/// \param PrevDecl the previous declaration found by name
2303/// lookup
2304///
2305/// \param DC the context in which the new declaration is being
2306/// declared.
2307///
2308/// \returns true if PrevDecl is an out-of-scope previous declaration
2309/// for a new delcaration with the same name.
2310static bool
2311isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
2312                                ASTContext &Context) {
2313  if (!PrevDecl)
2314    return 0;
2315
2316  if (!PrevDecl->hasLinkage())
2317    return false;
2318
2319  if (Context.getLangOptions().CPlusPlus) {
2320    // C++ [basic.link]p6:
2321    //   If there is a visible declaration of an entity with linkage
2322    //   having the same name and type, ignoring entities declared
2323    //   outside the innermost enclosing namespace scope, the block
2324    //   scope declaration declares that same entity and receives the
2325    //   linkage of the previous declaration.
2326    DeclContext *OuterContext = DC->getLookupContext();
2327    if (!OuterContext->isFunctionOrMethod())
2328      // This rule only applies to block-scope declarations.
2329      return false;
2330    else {
2331      DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
2332      if (PrevOuterContext->isRecord())
2333        // We found a member function: ignore it.
2334        return false;
2335      else {
2336        // Find the innermost enclosing namespace for the new and
2337        // previous declarations.
2338        while (!OuterContext->isFileContext())
2339          OuterContext = OuterContext->getParent();
2340        while (!PrevOuterContext->isFileContext())
2341          PrevOuterContext = PrevOuterContext->getParent();
2342
2343        // The previous declaration is in a different namespace, so it
2344        // isn't the same function.
2345        if (OuterContext->getPrimaryContext() !=
2346            PrevOuterContext->getPrimaryContext())
2347          return false;
2348      }
2349    }
2350  }
2351
2352  return true;
2353}
2354
2355static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
2356  CXXScopeSpec &SS = D.getCXXScopeSpec();
2357  if (!SS.isSet()) return;
2358  DD->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2359                       SS.getRange());
2360}
2361
2362NamedDecl*
2363Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2364                              QualType R, TypeSourceInfo *TInfo,
2365                              LookupResult &Previous,
2366                              MultiTemplateParamsArg TemplateParamLists,
2367                              bool &Redeclaration) {
2368  DeclarationName Name = GetNameForDeclarator(D);
2369
2370  // Check that there are no default arguments (C++ only).
2371  if (getLangOptions().CPlusPlus)
2372    CheckExtraCXXDefaultArguments(D);
2373
2374  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
2375  assert(SCSpec != DeclSpec::SCS_typedef &&
2376         "Parser allowed 'typedef' as storage class VarDecl.");
2377  VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec);
2378  if (SCSpec == DeclSpec::SCS_mutable) {
2379    // mutable can only appear on non-static class members, so it's always
2380    // an error here
2381    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
2382    D.setInvalidType();
2383    SC = VarDecl::None;
2384  }
2385  SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2386  VarDecl::StorageClass SCAsWritten
2387    = StorageClassSpecToVarDeclStorageClass(SCSpec);
2388
2389  IdentifierInfo *II = Name.getAsIdentifierInfo();
2390  if (!II) {
2391    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
2392      << Name.getAsString();
2393    return 0;
2394  }
2395
2396  DiagnoseFunctionSpecifiers(D);
2397
2398  if (!DC->isRecord() && S->getFnParent() == 0) {
2399    // C99 6.9p2: The storage-class specifiers auto and register shall not
2400    // appear in the declaration specifiers in an external declaration.
2401    if (SC == VarDecl::Auto || SC == VarDecl::Register) {
2402
2403      // If this is a register variable with an asm label specified, then this
2404      // is a GNU extension.
2405      if (SC == VarDecl::Register && D.getAsmLabel())
2406        Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register);
2407      else
2408        Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
2409      D.setInvalidType();
2410    }
2411  }
2412  if (DC->isRecord() && !CurContext->isRecord()) {
2413    // This is an out-of-line definition of a static data member.
2414    if (SC == VarDecl::Static) {
2415      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2416           diag::err_static_out_of_line)
2417        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2418    } else if (SC == VarDecl::None)
2419      SC = VarDecl::Static;
2420  }
2421  if (SC == VarDecl::Static) {
2422    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2423      if (RD->isLocalClass())
2424        Diag(D.getIdentifierLoc(),
2425             diag::err_static_data_member_not_allowed_in_local_class)
2426          << Name << RD->getDeclName();
2427    }
2428  }
2429
2430  // Match up the template parameter lists with the scope specifier, then
2431  // determine whether we have a template or a template specialization.
2432  bool isExplicitSpecialization = false;
2433  if (TemplateParameterList *TemplateParams
2434        = MatchTemplateParametersToScopeSpecifier(
2435                                  D.getDeclSpec().getSourceRange().getBegin(),
2436                                                  D.getCXXScopeSpec(),
2437                        (TemplateParameterList**)TemplateParamLists.get(),
2438                                                   TemplateParamLists.size(),
2439                                                  /*never a friend*/ false,
2440                                                  isExplicitSpecialization)) {
2441    if (TemplateParams->size() > 0) {
2442      // There is no such thing as a variable template.
2443      Diag(D.getIdentifierLoc(), diag::err_template_variable)
2444        << II
2445        << SourceRange(TemplateParams->getTemplateLoc(),
2446                       TemplateParams->getRAngleLoc());
2447      return 0;
2448    } else {
2449      // There is an extraneous 'template<>' for this variable. Complain
2450      // about it, but allow the declaration of the variable.
2451      Diag(TemplateParams->getTemplateLoc(),
2452           diag::err_template_variable_noparams)
2453        << II
2454        << SourceRange(TemplateParams->getTemplateLoc(),
2455                       TemplateParams->getRAngleLoc());
2456
2457      isExplicitSpecialization = true;
2458    }
2459  }
2460
2461  VarDecl *NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
2462                                   II, R, TInfo, SC, SCAsWritten);
2463
2464  if (D.isInvalidType())
2465    NewVD->setInvalidDecl();
2466
2467  SetNestedNameSpecifier(NewVD, D);
2468
2469  if (D.getDeclSpec().isThreadSpecified()) {
2470    if (NewVD->hasLocalStorage())
2471      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global);
2472    else if (!Context.Target.isTLSSupported())
2473      Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported);
2474    else
2475      NewVD->setThreadSpecified(true);
2476  }
2477
2478  // Set the lexical context. If the declarator has a C++ scope specifier, the
2479  // lexical context will be different from the semantic context.
2480  NewVD->setLexicalDeclContext(CurContext);
2481
2482  // Handle attributes prior to checking for duplicates in MergeVarDecl
2483  ProcessDeclAttributes(S, NewVD, D);
2484
2485  // Handle GNU asm-label extension (encoded as an attribute).
2486  if (Expr *E = (Expr*) D.getAsmLabel()) {
2487    // The parser guarantees this is a string.
2488    StringLiteral *SE = cast<StringLiteral>(E);
2489    NewVD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
2490  }
2491
2492  // Diagnose shadowed variables before filtering for scope.
2493  if (!D.getCXXScopeSpec().isSet())
2494    CheckShadow(S, NewVD, Previous);
2495
2496  // Don't consider existing declarations that are in a different
2497  // scope and are out-of-semantic-context declarations (if the new
2498  // declaration has linkage).
2499  FilterLookupForScope(*this, Previous, DC, S, NewVD->hasLinkage());
2500
2501  // Merge the decl with the existing one if appropriate.
2502  if (!Previous.empty()) {
2503    if (Previous.isSingleResult() &&
2504        isa<FieldDecl>(Previous.getFoundDecl()) &&
2505        D.getCXXScopeSpec().isSet()) {
2506      // The user tried to define a non-static data member
2507      // out-of-line (C++ [dcl.meaning]p1).
2508      Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
2509        << D.getCXXScopeSpec().getRange();
2510      Previous.clear();
2511      NewVD->setInvalidDecl();
2512    }
2513  } else if (D.getCXXScopeSpec().isSet()) {
2514    // No previous declaration in the qualifying scope.
2515    Diag(D.getIdentifierLoc(), diag::err_no_member)
2516      << Name << computeDeclContext(D.getCXXScopeSpec(), true)
2517      << D.getCXXScopeSpec().getRange();
2518    NewVD->setInvalidDecl();
2519  }
2520
2521  CheckVariableDeclaration(NewVD, Previous, Redeclaration);
2522
2523  // This is an explicit specialization of a static data member. Check it.
2524  if (isExplicitSpecialization && !NewVD->isInvalidDecl() &&
2525      CheckMemberSpecialization(NewVD, Previous))
2526    NewVD->setInvalidDecl();
2527
2528  // attributes declared post-definition are currently ignored
2529  if (Previous.isSingleResult()) {
2530    VarDecl *Def = dyn_cast<VarDecl>(Previous.getFoundDecl());
2531    if (Def && (Def = Def->getDefinition()) &&
2532        Def != NewVD && D.hasAttributes()) {
2533      Diag(NewVD->getLocation(), diag::warn_attribute_precede_definition);
2534      Diag(Def->getLocation(), diag::note_previous_definition);
2535    }
2536  }
2537
2538  // If this is a locally-scoped extern C variable, update the map of
2539  // such variables.
2540  if (CurContext->isFunctionOrMethod() && NewVD->isExternC() &&
2541      !NewVD->isInvalidDecl())
2542    RegisterLocallyScopedExternCDecl(NewVD, Previous, S);
2543
2544  return NewVD;
2545}
2546
2547/// \brief Diagnose variable or built-in function shadowing.  Implements
2548/// -Wshadow.
2549///
2550/// This method is called whenever a VarDecl is added to a "useful"
2551/// scope.
2552///
2553/// \param S the scope in which the shadowing name is being declared
2554/// \param R the lookup of the name
2555///
2556void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
2557  // Return if warning is ignored.
2558  if (Diags.getDiagnosticLevel(diag::warn_decl_shadow) == Diagnostic::Ignored)
2559    return;
2560
2561  // Don't diagnose declarations at file scope.  The scope might not
2562  // have a DeclContext if (e.g.) we're parsing a function prototype.
2563  DeclContext *NewDC = static_cast<DeclContext*>(S->getEntity());
2564  if (NewDC && NewDC->isFileContext())
2565    return;
2566
2567  // Only diagnose if we're shadowing an unambiguous field or variable.
2568  if (R.getResultKind() != LookupResult::Found)
2569    return;
2570
2571  NamedDecl* ShadowedDecl = R.getFoundDecl();
2572  if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
2573    return;
2574
2575  DeclContext *OldDC = ShadowedDecl->getDeclContext();
2576
2577  // Only warn about certain kinds of shadowing for class members.
2578  if (NewDC && NewDC->isRecord()) {
2579    // In particular, don't warn about shadowing non-class members.
2580    if (!OldDC->isRecord())
2581      return;
2582
2583    // TODO: should we warn about static data members shadowing
2584    // static data members from base classes?
2585
2586    // TODO: don't diagnose for inaccessible shadowed members.
2587    // This is hard to do perfectly because we might friend the
2588    // shadowing context, but that's just a false negative.
2589  }
2590
2591  // Determine what kind of declaration we're shadowing.
2592  unsigned Kind;
2593  if (isa<RecordDecl>(OldDC)) {
2594    if (isa<FieldDecl>(ShadowedDecl))
2595      Kind = 3; // field
2596    else
2597      Kind = 2; // static data member
2598  } else if (OldDC->isFileContext())
2599    Kind = 1; // global
2600  else
2601    Kind = 0; // local
2602
2603  DeclarationName Name = R.getLookupName();
2604
2605  // Emit warning and note.
2606  Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
2607  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
2608}
2609
2610/// \brief Check -Wshadow without the advantage of a previous lookup.
2611void Sema::CheckShadow(Scope *S, VarDecl *D) {
2612  LookupResult R(*this, D->getDeclName(), D->getLocation(),
2613                 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
2614  LookupName(R, S);
2615  CheckShadow(S, D, R);
2616}
2617
2618/// \brief Perform semantic checking on a newly-created variable
2619/// declaration.
2620///
2621/// This routine performs all of the type-checking required for a
2622/// variable declaration once it has been built. It is used both to
2623/// check variables after they have been parsed and their declarators
2624/// have been translated into a declaration, and to check variables
2625/// that have been instantiated from a template.
2626///
2627/// Sets NewVD->isInvalidDecl() if an error was encountered.
2628void Sema::CheckVariableDeclaration(VarDecl *NewVD,
2629                                    LookupResult &Previous,
2630                                    bool &Redeclaration) {
2631  // If the decl is already known invalid, don't check it.
2632  if (NewVD->isInvalidDecl())
2633    return;
2634
2635  QualType T = NewVD->getType();
2636
2637  if (T->isObjCInterfaceType()) {
2638    Diag(NewVD->getLocation(), diag::err_statically_allocated_object);
2639    return NewVD->setInvalidDecl();
2640  }
2641
2642  // Emit an error if an address space was applied to decl with local storage.
2643  // This includes arrays of objects with address space qualifiers, but not
2644  // automatic variables that point to other address spaces.
2645  // ISO/IEC TR 18037 S5.1.2
2646  if (NewVD->hasLocalStorage() && (T.getAddressSpace() != 0)) {
2647    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
2648    return NewVD->setInvalidDecl();
2649  }
2650
2651  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
2652      && !NewVD->hasAttr<BlocksAttr>())
2653    Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
2654
2655  bool isVM = T->isVariablyModifiedType();
2656  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
2657      NewVD->hasAttr<BlocksAttr>() ||
2658      // FIXME: We need to diagnose jumps passed initialized variables in C++.
2659      // However, this turns on the scope checker for everything with a variable
2660      // which may impact compile time.  See if we can find a better solution
2661      // to this, perhaps only checking functions that contain gotos in C++?
2662      (LangOpts.CPlusPlus && NewVD->hasLocalStorage()))
2663    FunctionNeedsScopeChecking() = true;
2664
2665  if ((isVM && NewVD->hasLinkage()) ||
2666      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
2667    bool SizeIsNegative;
2668    QualType FixedTy =
2669        TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
2670
2671    if (FixedTy.isNull() && T->isVariableArrayType()) {
2672      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
2673      // FIXME: This won't give the correct result for
2674      // int a[10][n];
2675      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
2676
2677      if (NewVD->isFileVarDecl())
2678        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
2679        << SizeRange;
2680      else if (NewVD->getStorageClass() == VarDecl::Static)
2681        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
2682        << SizeRange;
2683      else
2684        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
2685        << SizeRange;
2686      return NewVD->setInvalidDecl();
2687    }
2688
2689    if (FixedTy.isNull()) {
2690      if (NewVD->isFileVarDecl())
2691        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
2692      else
2693        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
2694      return NewVD->setInvalidDecl();
2695    }
2696
2697    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
2698    NewVD->setType(FixedTy);
2699  }
2700
2701  if (Previous.empty() && NewVD->isExternC()) {
2702    // Since we did not find anything by this name and we're declaring
2703    // an extern "C" variable, look for a non-visible extern "C"
2704    // declaration with the same name.
2705    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2706      = LocallyScopedExternalDecls.find(NewVD->getDeclName());
2707    if (Pos != LocallyScopedExternalDecls.end())
2708      Previous.addDecl(Pos->second);
2709  }
2710
2711  if (T->isVoidType() && !NewVD->hasExternalStorage()) {
2712    Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
2713      << T;
2714    return NewVD->setInvalidDecl();
2715  }
2716
2717  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
2718    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
2719    return NewVD->setInvalidDecl();
2720  }
2721
2722  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
2723    Diag(NewVD->getLocation(), diag::err_block_on_vm);
2724    return NewVD->setInvalidDecl();
2725  }
2726
2727  if (!Previous.empty()) {
2728    Redeclaration = true;
2729    MergeVarDecl(NewVD, Previous);
2730  }
2731}
2732
2733/// \brief Data used with FindOverriddenMethod
2734struct FindOverriddenMethodData {
2735  Sema *S;
2736  CXXMethodDecl *Method;
2737};
2738
2739/// \brief Member lookup function that determines whether a given C++
2740/// method overrides a method in a base class, to be used with
2741/// CXXRecordDecl::lookupInBases().
2742static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier,
2743                                 CXXBasePath &Path,
2744                                 void *UserData) {
2745  RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2746
2747  FindOverriddenMethodData *Data
2748    = reinterpret_cast<FindOverriddenMethodData*>(UserData);
2749
2750  DeclarationName Name = Data->Method->getDeclName();
2751
2752  // FIXME: Do we care about other names here too?
2753  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2754    // We really want to find the base class constructor here.
2755    QualType T = Data->S->Context.getTypeDeclType(BaseRecord);
2756    CanQualType CT = Data->S->Context.getCanonicalType(T);
2757
2758    Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT);
2759  }
2760
2761  for (Path.Decls = BaseRecord->lookup(Name);
2762       Path.Decls.first != Path.Decls.second;
2763       ++Path.Decls.first) {
2764    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*Path.Decls.first)) {
2765      if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD))
2766        return true;
2767    }
2768  }
2769
2770  return false;
2771}
2772
2773/// AddOverriddenMethods - See if a method overrides any in the base classes,
2774/// and if so, check that it's a valid override and remember it.
2775void Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2776  // Look for virtual methods in base classes that this method might override.
2777  CXXBasePaths Paths;
2778  FindOverriddenMethodData Data;
2779  Data.Method = MD;
2780  Data.S = this;
2781  if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) {
2782    for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(),
2783         E = Paths.found_decls_end(); I != E; ++I) {
2784      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) {
2785        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
2786            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
2787            !CheckOverridingFunctionAttributes(MD, OldMD))
2788          MD->addOverriddenMethod(OldMD->getCanonicalDecl());
2789      }
2790    }
2791  }
2792}
2793
2794NamedDecl*
2795Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2796                              QualType R, TypeSourceInfo *TInfo,
2797                              LookupResult &Previous,
2798                              MultiTemplateParamsArg TemplateParamLists,
2799                              bool IsFunctionDefinition, bool &Redeclaration) {
2800  assert(R.getTypePtr()->isFunctionType());
2801
2802  DeclarationName Name = GetNameForDeclarator(D);
2803  FunctionDecl::StorageClass SC = FunctionDecl::None;
2804  switch (D.getDeclSpec().getStorageClassSpec()) {
2805  default: assert(0 && "Unknown storage class!");
2806  case DeclSpec::SCS_auto:
2807  case DeclSpec::SCS_register:
2808  case DeclSpec::SCS_mutable:
2809    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2810         diag::err_typecheck_sclass_func);
2811    D.setInvalidType();
2812    break;
2813  case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
2814  case DeclSpec::SCS_extern:      SC = FunctionDecl::Extern; break;
2815  case DeclSpec::SCS_static: {
2816    if (CurContext->getLookupContext()->isFunctionOrMethod()) {
2817      // C99 6.7.1p5:
2818      //   The declaration of an identifier for a function that has
2819      //   block scope shall have no explicit storage-class specifier
2820      //   other than extern
2821      // See also (C++ [dcl.stc]p4).
2822      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
2823           diag::err_static_block_func);
2824      SC = FunctionDecl::None;
2825    } else
2826      SC = FunctionDecl::Static;
2827    break;
2828  }
2829  case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
2830  }
2831
2832  if (D.getDeclSpec().isThreadSpecified())
2833    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2834
2835  bool isFriend = D.getDeclSpec().isFriendSpecified();
2836  bool isInline = D.getDeclSpec().isInlineSpecified();
2837  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
2838  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
2839
2840  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten();
2841  FunctionDecl::StorageClass SCAsWritten
2842    = StorageClassSpecToFunctionDeclStorageClass(SCSpec);
2843
2844  // Check that the return type is not an abstract class type.
2845  // For record types, this is done by the AbstractClassUsageDiagnoser once
2846  // the class has been completely parsed.
2847  if (!DC->isRecord() &&
2848      RequireNonAbstractType(D.getIdentifierLoc(),
2849                             R->getAs<FunctionType>()->getResultType(),
2850                             diag::err_abstract_type_in_decl,
2851                             AbstractReturnType))
2852    D.setInvalidType();
2853
2854  // Do not allow returning a objc interface by-value.
2855  if (R->getAs<FunctionType>()->getResultType()->isObjCInterfaceType()) {
2856    Diag(D.getIdentifierLoc(),
2857         diag::err_object_cannot_be_passed_returned_by_value) << 0
2858      << R->getAs<FunctionType>()->getResultType();
2859    D.setInvalidType();
2860  }
2861
2862  bool isVirtualOkay = false;
2863  FunctionDecl *NewFD;
2864
2865  if (isFriend) {
2866    // C++ [class.friend]p5
2867    //   A function can be defined in a friend declaration of a
2868    //   class . . . . Such a function is implicitly inline.
2869    isInline |= IsFunctionDefinition;
2870  }
2871
2872  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
2873    // This is a C++ constructor declaration.
2874    assert(DC->isRecord() &&
2875           "Constructors can only be declared in a member context");
2876
2877    R = CheckConstructorDeclarator(D, R, SC);
2878
2879    // Create the new declaration
2880    NewFD = CXXConstructorDecl::Create(Context,
2881                                       cast<CXXRecordDecl>(DC),
2882                                       D.getIdentifierLoc(), Name, R, TInfo,
2883                                       isExplicit, isInline,
2884                                       /*isImplicitlyDeclared=*/false);
2885  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
2886    // This is a C++ destructor declaration.
2887    if (DC->isRecord()) {
2888      R = CheckDestructorDeclarator(D, SC);
2889
2890      NewFD = CXXDestructorDecl::Create(Context,
2891                                        cast<CXXRecordDecl>(DC),
2892                                        D.getIdentifierLoc(), Name, R,
2893                                        isInline,
2894                                        /*isImplicitlyDeclared=*/false);
2895      NewFD->setTypeSourceInfo(TInfo);
2896
2897      isVirtualOkay = true;
2898    } else {
2899      Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
2900
2901      // Create a FunctionDecl to satisfy the function definition parsing
2902      // code path.
2903      NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
2904                                   Name, R, TInfo, SC, SCAsWritten, isInline,
2905                                   /*hasPrototype=*/true);
2906      D.setInvalidType();
2907    }
2908  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2909    if (!DC->isRecord()) {
2910      Diag(D.getIdentifierLoc(),
2911           diag::err_conv_function_not_member);
2912      return 0;
2913    }
2914
2915    CheckConversionDeclarator(D, R, SC);
2916    NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
2917                                      D.getIdentifierLoc(), Name, R, TInfo,
2918                                      isInline, isExplicit);
2919
2920    isVirtualOkay = true;
2921  } else if (DC->isRecord()) {
2922    // If the of the function is the same as the name of the record, then this
2923    // must be an invalid constructor that has a return type.
2924    // (The parser checks for a return type and makes the declarator a
2925    // constructor if it has no return type).
2926    // must have an invalid constructor that has a return type
2927    if (Name.getAsIdentifierInfo() &&
2928        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
2929      Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
2930        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2931        << SourceRange(D.getIdentifierLoc());
2932      return 0;
2933    }
2934
2935    bool isStatic = SC == FunctionDecl::Static;
2936
2937    // [class.free]p1:
2938    // Any allocation function for a class T is a static member
2939    // (even if not explicitly declared static).
2940    if (Name.getCXXOverloadedOperator() == OO_New ||
2941        Name.getCXXOverloadedOperator() == OO_Array_New)
2942      isStatic = true;
2943
2944    // [class.free]p6 Any deallocation function for a class X is a static member
2945    // (even if not explicitly declared static).
2946    if (Name.getCXXOverloadedOperator() == OO_Delete ||
2947        Name.getCXXOverloadedOperator() == OO_Array_Delete)
2948      isStatic = true;
2949
2950    // This is a C++ method declaration.
2951    NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
2952                                  D.getIdentifierLoc(), Name, R, TInfo,
2953                                  isStatic, SCAsWritten, isInline);
2954
2955    isVirtualOkay = !isStatic;
2956  } else {
2957    // Determine whether the function was written with a
2958    // prototype. This true when:
2959    //   - we're in C++ (where every function has a prototype),
2960    //   - there is a prototype in the declarator, or
2961    //   - the type R of the function is some kind of typedef or other reference
2962    //     to a type name (which eventually refers to a function type).
2963    bool HasPrototype =
2964       getLangOptions().CPlusPlus ||
2965       (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype) ||
2966       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
2967
2968    NewFD = FunctionDecl::Create(Context, DC,
2969                                 D.getIdentifierLoc(),
2970                                 Name, R, TInfo, SC, SCAsWritten, isInline,
2971                                 HasPrototype);
2972  }
2973
2974  if (D.isInvalidType())
2975    NewFD->setInvalidDecl();
2976
2977  SetNestedNameSpecifier(NewFD, D);
2978
2979  // Set the lexical context. If the declarator has a C++
2980  // scope specifier, or is the object of a friend declaration, the
2981  // lexical context will be different from the semantic context.
2982  NewFD->setLexicalDeclContext(CurContext);
2983
2984  // Match up the template parameter lists with the scope specifier, then
2985  // determine whether we have a template or a template specialization.
2986  FunctionTemplateDecl *FunctionTemplate = 0;
2987  bool isExplicitSpecialization = false;
2988  bool isFunctionTemplateSpecialization = false;
2989  if (TemplateParameterList *TemplateParams
2990        = MatchTemplateParametersToScopeSpecifier(
2991                                  D.getDeclSpec().getSourceRange().getBegin(),
2992                                  D.getCXXScopeSpec(),
2993                           (TemplateParameterList**)TemplateParamLists.get(),
2994                                                  TemplateParamLists.size(),
2995                                                  isFriend,
2996                                                  isExplicitSpecialization)) {
2997    if (TemplateParams->size() > 0) {
2998      // This is a function template
2999
3000      // Check that we can declare a template here.
3001      if (CheckTemplateDeclScope(S, TemplateParams))
3002        return 0;
3003
3004      FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
3005                                                      NewFD->getLocation(),
3006                                                      Name, TemplateParams,
3007                                                      NewFD);
3008      FunctionTemplate->setLexicalDeclContext(CurContext);
3009      NewFD->setDescribedFunctionTemplate(FunctionTemplate);
3010    } else {
3011      // This is a function template specialization.
3012      isFunctionTemplateSpecialization = true;
3013
3014      // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
3015      if (isFriend && isFunctionTemplateSpecialization) {
3016        // We want to remove the "template<>", found here.
3017        SourceRange RemoveRange = TemplateParams->getSourceRange();
3018
3019        // If we remove the template<> and the name is not a
3020        // template-id, we're actually silently creating a problem:
3021        // the friend declaration will refer to an untemplated decl,
3022        // and clearly the user wants a template specialization.  So
3023        // we need to insert '<>' after the name.
3024        SourceLocation InsertLoc;
3025        if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
3026          InsertLoc = D.getName().getSourceRange().getEnd();
3027          InsertLoc = PP.getLocForEndOfToken(InsertLoc);
3028        }
3029
3030        Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
3031          << Name << RemoveRange
3032          << FixItHint::CreateRemoval(RemoveRange)
3033          << FixItHint::CreateInsertion(InsertLoc, "<>");
3034      }
3035    }
3036
3037    // FIXME: Free this memory properly.
3038    TemplateParamLists.release();
3039  }
3040
3041  // C++ [dcl.fct.spec]p5:
3042  //   The virtual specifier shall only be used in declarations of
3043  //   nonstatic class member functions that appear within a
3044  //   member-specification of a class declaration; see 10.3.
3045  //
3046  if (isVirtual && !NewFD->isInvalidDecl()) {
3047    if (!isVirtualOkay) {
3048       Diag(D.getDeclSpec().getVirtualSpecLoc(),
3049           diag::err_virtual_non_function);
3050    } else if (!CurContext->isRecord()) {
3051      // 'virtual' was specified outside of the class.
3052      Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
3053        << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
3054    } else {
3055      // Okay: Add virtual to the method.
3056      CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
3057      CurClass->setMethodAsVirtual(NewFD);
3058    }
3059  }
3060
3061  // C++ [dcl.fct.spec]p6:
3062  //  The explicit specifier shall be used only in the declaration of a
3063  //  constructor or conversion function within its class definition; see 12.3.1
3064  //  and 12.3.2.
3065  if (isExplicit && !NewFD->isInvalidDecl()) {
3066    if (!CurContext->isRecord()) {
3067      // 'explicit' was specified outside of the class.
3068      Diag(D.getDeclSpec().getExplicitSpecLoc(),
3069           diag::err_explicit_out_of_class)
3070        << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3071    } else if (!isa<CXXConstructorDecl>(NewFD) &&
3072               !isa<CXXConversionDecl>(NewFD)) {
3073      // 'explicit' was specified on a function that wasn't a constructor
3074      // or conversion function.
3075      Diag(D.getDeclSpec().getExplicitSpecLoc(),
3076           diag::err_explicit_non_ctor_or_conv_function)
3077        << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
3078    }
3079  }
3080
3081  // Filter out previous declarations that don't match the scope.
3082  FilterLookupForScope(*this, Previous, DC, S, NewFD->hasLinkage());
3083
3084  if (isFriend) {
3085    // DC is the namespace in which the function is being declared.
3086    assert((DC->isFileContext() || !Previous.empty()) &&
3087           "previously-undeclared friend function being created "
3088           "in a non-namespace context");
3089
3090    // For now, claim that the objects have no previous declaration.
3091    if (FunctionTemplate) {
3092      FunctionTemplate->setObjectOfFriendDecl(false);
3093      FunctionTemplate->setAccess(AS_public);
3094    }
3095    NewFD->setObjectOfFriendDecl(false);
3096    NewFD->setAccess(AS_public);
3097  }
3098
3099  if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
3100      !CurContext->isRecord()) {
3101    // C++ [class.static]p1:
3102    //   A data or function member of a class may be declared static
3103    //   in a class definition, in which case it is a static member of
3104    //   the class.
3105
3106    // Complain about the 'static' specifier if it's on an out-of-line
3107    // member function definition.
3108    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
3109         diag::err_static_out_of_line)
3110      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3111  }
3112
3113  // Handle GNU asm-label extension (encoded as an attribute).
3114  if (Expr *E = (Expr*) D.getAsmLabel()) {
3115    // The parser guarantees this is a string.
3116    StringLiteral *SE = cast<StringLiteral>(E);
3117    NewFD->addAttr(::new (Context) AsmLabelAttr(Context, SE->getString()));
3118  }
3119
3120  // Copy the parameter declarations from the declarator D to the function
3121  // declaration NewFD, if they are available.  First scavenge them into Params.
3122  llvm::SmallVector<ParmVarDecl*, 16> Params;
3123  if (D.getNumTypeObjects() > 0) {
3124    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3125
3126    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
3127    // function that takes no arguments, not a function that takes a
3128    // single void argument.
3129    // We let through "const void" here because Sema::GetTypeForDeclarator
3130    // already checks for that case.
3131    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3132        FTI.ArgInfo[0].Param &&
3133        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType()) {
3134      // Empty arg list, don't push any params.
3135      ParmVarDecl *Param = FTI.ArgInfo[0].Param.getAs<ParmVarDecl>();
3136
3137      // In C++, the empty parameter-type-list must be spelled "void"; a
3138      // typedef of void is not permitted.
3139      if (getLangOptions().CPlusPlus &&
3140          Param->getType().getUnqualifiedType() != Context.VoidTy)
3141        Diag(Param->getLocation(), diag::err_param_typedef_of_void);
3142      // FIXME: Leaks decl?
3143    } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
3144      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
3145        ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
3146        assert(Param->getDeclContext() != NewFD && "Was set before ?");
3147        Param->setDeclContext(NewFD);
3148        Params.push_back(Param);
3149
3150        if (Param->isInvalidDecl())
3151          NewFD->setInvalidDecl();
3152      }
3153    }
3154
3155  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
3156    // When we're declaring a function with a typedef, typeof, etc as in the
3157    // following example, we'll need to synthesize (unnamed)
3158    // parameters for use in the declaration.
3159    //
3160    // @code
3161    // typedef void fn(int);
3162    // fn f;
3163    // @endcode
3164
3165    // Synthesize a parameter for each argument type.
3166    for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(),
3167         AE = FT->arg_type_end(); AI != AE; ++AI) {
3168      ParmVarDecl *Param = ParmVarDecl::Create(Context, NewFD,
3169                                               SourceLocation(), 0,
3170                                               *AI, /*TInfo=*/0,
3171                                               VarDecl::None,
3172                                               VarDecl::None, 0);
3173      Param->setImplicit();
3174      Params.push_back(Param);
3175    }
3176  } else {
3177    assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
3178           "Should not need args for typedef of non-prototype fn");
3179  }
3180  // Finally, we know we have the right number of parameters, install them.
3181  NewFD->setParams(Params.data(), Params.size());
3182
3183  // If the declarator is a template-id, translate the parser's template
3184  // argument list into our AST format.
3185  bool HasExplicitTemplateArgs = false;
3186  TemplateArgumentListInfo TemplateArgs;
3187  if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
3188    TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3189    TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
3190    TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
3191    ASTTemplateArgsPtr TemplateArgsPtr(*this,
3192                                       TemplateId->getTemplateArgs(),
3193                                       TemplateId->NumArgs);
3194    translateTemplateArguments(TemplateArgsPtr,
3195                               TemplateArgs);
3196    TemplateArgsPtr.release();
3197
3198    HasExplicitTemplateArgs = true;
3199
3200    if (FunctionTemplate) {
3201      // FIXME: Diagnose function template with explicit template
3202      // arguments.
3203      HasExplicitTemplateArgs = false;
3204    } else if (!isFunctionTemplateSpecialization &&
3205               !D.getDeclSpec().isFriendSpecified()) {
3206      // We have encountered something that the user meant to be a
3207      // specialization (because it has explicitly-specified template
3208      // arguments) but that was not introduced with a "template<>" (or had
3209      // too few of them).
3210      Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header)
3211        << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)
3212        << FixItHint::CreateInsertion(
3213                                   D.getDeclSpec().getSourceRange().getBegin(),
3214                                                 "template<> ");
3215      isFunctionTemplateSpecialization = true;
3216    } else {
3217      // "friend void foo<>(int);" is an implicit specialization decl.
3218      isFunctionTemplateSpecialization = true;
3219    }
3220  } else if (isFriend && isFunctionTemplateSpecialization) {
3221    // This combination is only possible in a recovery case;  the user
3222    // wrote something like:
3223    //   template <> friend void foo(int);
3224    // which we're recovering from as if the user had written:
3225    //   friend void foo<>(int);
3226    // Go ahead and fake up a template id.
3227    HasExplicitTemplateArgs = true;
3228    TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
3229    TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
3230  }
3231
3232  // If it's a friend (and only if it's a friend), it's possible
3233  // that either the specialized function type or the specialized
3234  // template is dependent, and therefore matching will fail.  In
3235  // this case, don't check the specialization yet.
3236  if (isFunctionTemplateSpecialization && isFriend &&
3237      (NewFD->getType()->isDependentType() || DC->isDependentContext())) {
3238    assert(HasExplicitTemplateArgs &&
3239           "friend function specialization without template args");
3240    if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
3241                                                     Previous))
3242      NewFD->setInvalidDecl();
3243  } else if (isFunctionTemplateSpecialization) {
3244    if (CheckFunctionTemplateSpecialization(NewFD,
3245                               (HasExplicitTemplateArgs ? &TemplateArgs : 0),
3246                                            Previous))
3247      NewFD->setInvalidDecl();
3248  } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
3249    if (CheckMemberSpecialization(NewFD, Previous))
3250      NewFD->setInvalidDecl();
3251  }
3252
3253  // Perform semantic checking on the function declaration.
3254  bool OverloadableAttrRequired = false; // FIXME: HACK!
3255  CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3256                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3257
3258  assert((NewFD->isInvalidDecl() || !Redeclaration ||
3259          Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3260         "previous declaration set still overloaded");
3261
3262  NamedDecl *PrincipalDecl = (FunctionTemplate
3263                              ? cast<NamedDecl>(FunctionTemplate)
3264                              : NewFD);
3265
3266  if (isFriend && Redeclaration) {
3267    AccessSpecifier Access = AS_public;
3268    if (!NewFD->isInvalidDecl())
3269      Access = NewFD->getPreviousDeclaration()->getAccess();
3270
3271    NewFD->setAccess(Access);
3272    if (FunctionTemplate) FunctionTemplate->setAccess(Access);
3273
3274    PrincipalDecl->setObjectOfFriendDecl(true);
3275  }
3276
3277  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
3278      PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3279    PrincipalDecl->setNonMemberOperator();
3280
3281  // If we have a function template, check the template parameter
3282  // list. This will check and merge default template arguments.
3283  if (FunctionTemplate) {
3284    FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3285    CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3286                      PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3287             D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3288                                                : TPC_FunctionTemplate);
3289  }
3290
3291  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3292    // Fake up an access specifier if it's supposed to be a class member.
3293    if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
3294      NewFD->setAccess(AS_public);
3295
3296    // An out-of-line member function declaration must also be a
3297    // definition (C++ [dcl.meaning]p1).
3298    // Note that this is not the case for explicit specializations of
3299    // function templates or member functions of class templates, per
3300    // C++ [temp.expl.spec]p2.
3301    if (!IsFunctionDefinition && !isFriend &&
3302        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3303      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3304        << D.getCXXScopeSpec().getRange();
3305      NewFD->setInvalidDecl();
3306    } else if (!Redeclaration &&
3307               !(isFriend && CurContext->isDependentContext())) {
3308      // The user tried to provide an out-of-line definition for a
3309      // function that is a member of a class or namespace, but there
3310      // was no such member function declared (C++ [class.mfct]p2,
3311      // C++ [namespace.memdef]p2). For example:
3312      //
3313      // class X {
3314      //   void f() const;
3315      // };
3316      //
3317      // void X::f() { } // ill-formed
3318      //
3319      // Complain about this problem, and attempt to suggest close
3320      // matches (e.g., those that differ only in cv-qualifiers and
3321      // whether the parameter types are references).
3322      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3323        << Name << DC << D.getCXXScopeSpec().getRange();
3324      NewFD->setInvalidDecl();
3325
3326      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3327                        ForRedeclaration);
3328      LookupQualifiedName(Prev, DC);
3329      assert(!Prev.isAmbiguous() &&
3330             "Cannot have an ambiguity in previous-declaration lookup");
3331      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3332           Func != FuncEnd; ++Func) {
3333        if (isa<FunctionDecl>(*Func) &&
3334            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3335          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3336      }
3337    }
3338  }
3339
3340  // Handle attributes. We need to have merged decls when handling attributes
3341  // (for example to check for conflicts, etc).
3342  // FIXME: This needs to happen before we merge declarations. Then,
3343  // let attribute merging cope with attribute conflicts.
3344  ProcessDeclAttributes(S, NewFD, D);
3345
3346  // attributes declared post-definition are currently ignored
3347  if (Redeclaration && Previous.isSingleResult()) {
3348    const FunctionDecl *Def;
3349    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3350    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3351      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3352      Diag(Def->getLocation(), diag::note_previous_definition);
3353    }
3354  }
3355
3356  AddKnownFunctionAttributes(NewFD);
3357
3358  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3359    // If a function name is overloadable in C, then every function
3360    // with that name must be marked "overloadable".
3361    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3362      << Redeclaration << NewFD;
3363    if (!Previous.empty())
3364      Diag(Previous.getRepresentativeDecl()->getLocation(),
3365           diag::note_attribute_overloadable_prev_overload);
3366    NewFD->addAttr(::new (Context) OverloadableAttr());
3367  }
3368
3369  // If this is a locally-scoped extern C function, update the
3370  // map of such names.
3371  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3372      && !NewFD->isInvalidDecl())
3373    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3374
3375  // Set this FunctionDecl's range up to the right paren.
3376  NewFD->setLocEnd(D.getSourceRange().getEnd());
3377
3378  if (FunctionTemplate && NewFD->isInvalidDecl())
3379    FunctionTemplate->setInvalidDecl();
3380
3381  if (FunctionTemplate)
3382    return FunctionTemplate;
3383
3384
3385  // Keep track of static, non-inlined function definitions that
3386  // have not been used. We will warn later.
3387  // FIXME: Also include static functions declared but not defined.
3388  if (!NewFD->isInvalidDecl() && IsFunctionDefinition
3389      && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
3390      && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>()
3391      && !NewFD->hasAttr<ConstructorAttr>()
3392      && !NewFD->hasAttr<DestructorAttr>())
3393    UnusedStaticFuncs.push_back(NewFD);
3394
3395  return NewFD;
3396}
3397
3398/// \brief Perform semantic checking of a new function declaration.
3399///
3400/// Performs semantic analysis of the new function declaration
3401/// NewFD. This routine performs all semantic checking that does not
3402/// require the actual declarator involved in the declaration, and is
3403/// used both for the declaration of functions as they are parsed
3404/// (called via ActOnDeclarator) and for the declaration of functions
3405/// that have been instantiated via C++ template instantiation (called
3406/// via InstantiateDecl).
3407///
3408/// \param IsExplicitSpecialiation whether this new function declaration is
3409/// an explicit specialization of the previous declaration.
3410///
3411/// This sets NewFD->isInvalidDecl() to true if there was an error.
3412void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3413                                    LookupResult &Previous,
3414                                    bool IsExplicitSpecialization,
3415                                    bool &Redeclaration,
3416                                    bool &OverloadableAttrRequired) {
3417  // If NewFD is already known erroneous, don't do any of this checking.
3418  if (NewFD->isInvalidDecl())
3419    return;
3420
3421  if (NewFD->getResultType()->isVariablyModifiedType()) {
3422    // Functions returning a variably modified type violate C99 6.7.5.2p2
3423    // because all functions have linkage.
3424    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3425    return NewFD->setInvalidDecl();
3426  }
3427
3428  if (NewFD->isMain())
3429    CheckMain(NewFD);
3430
3431  // Check for a previous declaration of this name.
3432  if (Previous.empty() && NewFD->isExternC()) {
3433    // Since we did not find anything by this name and we're declaring
3434    // an extern "C" function, look for a non-visible extern "C"
3435    // declaration with the same name.
3436    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3437      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3438    if (Pos != LocallyScopedExternalDecls.end())
3439      Previous.addDecl(Pos->second);
3440  }
3441
3442  // Merge or overload the declaration with an existing declaration of
3443  // the same name, if appropriate.
3444  if (!Previous.empty()) {
3445    // Determine whether NewFD is an overload of PrevDecl or
3446    // a declaration that requires merging. If it's an overload,
3447    // there's no more work to do here; we'll just add the new
3448    // function to the scope.
3449
3450    NamedDecl *OldDecl = 0;
3451    if (!AllowOverloadingOfFunction(Previous, Context)) {
3452      Redeclaration = true;
3453      OldDecl = Previous.getFoundDecl();
3454    } else {
3455      if (!getLangOptions().CPlusPlus) {
3456        OverloadableAttrRequired = true;
3457
3458        // Functions marked "overloadable" must have a prototype (that
3459        // we can't get through declaration merging).
3460        if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3461          Diag(NewFD->getLocation(),
3462               diag::err_attribute_overloadable_no_prototype)
3463            << NewFD;
3464          Redeclaration = true;
3465
3466          // Turn this into a variadic function with no parameters.
3467          QualType R = Context.getFunctionType(
3468                     NewFD->getType()->getAs<FunctionType>()->getResultType(),
3469                     0, 0, true, 0, false, false, 0, 0,
3470                     FunctionType::ExtInfo());
3471          NewFD->setType(R);
3472          return NewFD->setInvalidDecl();
3473        }
3474      }
3475
3476      switch (CheckOverload(NewFD, Previous, OldDecl)) {
3477      case Ovl_Match:
3478        Redeclaration = true;
3479        if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3480          HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3481          Redeclaration = false;
3482        }
3483        break;
3484
3485      case Ovl_NonFunction:
3486        Redeclaration = true;
3487        break;
3488
3489      case Ovl_Overload:
3490        Redeclaration = false;
3491        break;
3492      }
3493    }
3494
3495    if (Redeclaration) {
3496      // NewFD and OldDecl represent declarations that need to be
3497      // merged.
3498      if (MergeFunctionDecl(NewFD, OldDecl))
3499        return NewFD->setInvalidDecl();
3500
3501      Previous.clear();
3502      Previous.addDecl(OldDecl);
3503
3504      if (FunctionTemplateDecl *OldTemplateDecl
3505                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3506        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3507        FunctionTemplateDecl *NewTemplateDecl
3508          = NewFD->getDescribedFunctionTemplate();
3509        assert(NewTemplateDecl && "Template/non-template mismatch");
3510        if (CXXMethodDecl *Method
3511              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3512          Method->setAccess(OldTemplateDecl->getAccess());
3513          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3514        }
3515
3516        // If this is an explicit specialization of a member that is a function
3517        // template, mark it as a member specialization.
3518        if (IsExplicitSpecialization &&
3519            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3520          NewTemplateDecl->setMemberSpecialization();
3521          assert(OldTemplateDecl->isMemberSpecialization());
3522        }
3523      } else {
3524        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3525          NewFD->setAccess(OldDecl->getAccess());
3526        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3527      }
3528    }
3529  }
3530
3531  // Semantic checking for this function declaration (in isolation).
3532  if (getLangOptions().CPlusPlus) {
3533    // C++-specific checks.
3534    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3535      CheckConstructor(Constructor);
3536    } else if (CXXDestructorDecl *Destructor =
3537                dyn_cast<CXXDestructorDecl>(NewFD)) {
3538      CXXRecordDecl *Record = Destructor->getParent();
3539      QualType ClassType = Context.getTypeDeclType(Record);
3540
3541      // FIXME: Shouldn't we be able to perform thisc heck even when the class
3542      // type is dependent? Both gcc and edg can handle that.
3543      if (!ClassType->isDependentType()) {
3544        DeclarationName Name
3545          = Context.DeclarationNames.getCXXDestructorName(
3546                                        Context.getCanonicalType(ClassType));
3547        if (NewFD->getDeclName() != Name) {
3548          Diag(NewFD->getLocation(), diag::err_destructor_name);
3549          return NewFD->setInvalidDecl();
3550        }
3551      }
3552
3553      Record->setUserDeclaredDestructor(true);
3554      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3555      // user-defined destructor.
3556      Record->setPOD(false);
3557
3558      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3559      // declared destructor.
3560      // FIXME: C++0x: don't do this for "= default" destructors
3561      Record->setHasTrivialDestructor(false);
3562    } else if (CXXConversionDecl *Conversion
3563               = dyn_cast<CXXConversionDecl>(NewFD)) {
3564      ActOnConversionDeclarator(Conversion);
3565    }
3566
3567    // Find any virtual functions that this function overrides.
3568    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3569      if (!Method->isFunctionTemplateSpecialization() &&
3570          !Method->getDescribedFunctionTemplate())
3571        AddOverriddenMethods(Method->getParent(), Method);
3572    }
3573
3574    // Additional checks for the destructor; make sure we do this after we
3575    // figure out whether the destructor is virtual.
3576    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3577      if (!Destructor->getParent()->isDependentType())
3578        CheckDestructor(Destructor);
3579
3580    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3581    if (NewFD->isOverloadedOperator() &&
3582        CheckOverloadedOperatorDeclaration(NewFD))
3583      return NewFD->setInvalidDecl();
3584
3585    // Extra checking for C++0x literal operators (C++0x [over.literal]).
3586    if (NewFD->getLiteralIdentifier() &&
3587        CheckLiteralOperatorDeclaration(NewFD))
3588      return NewFD->setInvalidDecl();
3589
3590    // In C++, check default arguments now that we have merged decls. Unless
3591    // the lexical context is the class, because in this case this is done
3592    // during delayed parsing anyway.
3593    if (!CurContext->isRecord())
3594      CheckCXXDefaultArguments(NewFD);
3595  }
3596}
3597
3598void Sema::CheckMain(FunctionDecl* FD) {
3599  // C++ [basic.start.main]p3:  A program that declares main to be inline
3600  //   or static is ill-formed.
3601  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3602  //   shall not appear in a declaration of main.
3603  // static main is not an error under C99, but we should warn about it.
3604  bool isInline = FD->isInlineSpecified();
3605  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3606  if (isInline || isStatic) {
3607    unsigned diagID = diag::warn_unusual_main_decl;
3608    if (isInline || getLangOptions().CPlusPlus)
3609      diagID = diag::err_unusual_main_decl;
3610
3611    int which = isStatic + (isInline << 1) - 1;
3612    Diag(FD->getLocation(), diagID) << which;
3613  }
3614
3615  QualType T = FD->getType();
3616  assert(T->isFunctionType() && "function decl is not of function type");
3617  const FunctionType* FT = T->getAs<FunctionType>();
3618
3619  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3620    // TODO: add a replacement fixit to turn the return type into 'int'.
3621    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3622    FD->setInvalidDecl(true);
3623  }
3624
3625  // Treat protoless main() as nullary.
3626  if (isa<FunctionNoProtoType>(FT)) return;
3627
3628  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3629  unsigned nparams = FTP->getNumArgs();
3630  assert(FD->getNumParams() == nparams);
3631
3632  bool HasExtraParameters = (nparams > 3);
3633
3634  // Darwin passes an undocumented fourth argument of type char**.  If
3635  // other platforms start sprouting these, the logic below will start
3636  // getting shifty.
3637  if (nparams == 4 &&
3638      Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3639    HasExtraParameters = false;
3640
3641  if (HasExtraParameters) {
3642    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3643    FD->setInvalidDecl(true);
3644    nparams = 3;
3645  }
3646
3647  // FIXME: a lot of the following diagnostics would be improved
3648  // if we had some location information about types.
3649
3650  QualType CharPP =
3651    Context.getPointerType(Context.getPointerType(Context.CharTy));
3652  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
3653
3654  for (unsigned i = 0; i < nparams; ++i) {
3655    QualType AT = FTP->getArgType(i);
3656
3657    bool mismatch = true;
3658
3659    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3660      mismatch = false;
3661    else if (Expected[i] == CharPP) {
3662      // As an extension, the following forms are okay:
3663      //   char const **
3664      //   char const * const *
3665      //   char * const *
3666
3667      QualifierCollector qs;
3668      const PointerType* PT;
3669      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3670          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3671          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3672        qs.removeConst();
3673        mismatch = !qs.empty();
3674      }
3675    }
3676
3677    if (mismatch) {
3678      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3679      // TODO: suggest replacing given type with expected type
3680      FD->setInvalidDecl(true);
3681    }
3682  }
3683
3684  if (nparams == 1 && !FD->isInvalidDecl()) {
3685    Diag(FD->getLocation(), diag::warn_main_one_arg);
3686  }
3687}
3688
3689bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3690  // FIXME: Need strict checking.  In C89, we need to check for
3691  // any assignment, increment, decrement, function-calls, or
3692  // commas outside of a sizeof.  In C99, it's the same list,
3693  // except that the aforementioned are allowed in unevaluated
3694  // expressions.  Everything else falls under the
3695  // "may accept other forms of constant expressions" exception.
3696  // (We never end up here for C++, so the constant expression
3697  // rules there don't matter.)
3698  if (Init->isConstantInitializer(Context))
3699    return false;
3700  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3701    << Init->getSourceRange();
3702  return true;
3703}
3704
3705void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3706  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3707}
3708
3709/// AddInitializerToDecl - Adds the initializer Init to the
3710/// declaration dcl. If DirectInit is true, this is C++ direct
3711/// initialization rather than copy initialization.
3712void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3713  Decl *RealDecl = dcl.getAs<Decl>();
3714  // If there is no declaration, there was an error parsing it.  Just ignore
3715  // the initializer.
3716  if (RealDecl == 0)
3717    return;
3718
3719  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3720    // With declarators parsed the way they are, the parser cannot
3721    // distinguish between a normal initializer and a pure-specifier.
3722    // Thus this grotesque test.
3723    IntegerLiteral *IL;
3724    Expr *Init = static_cast<Expr *>(init.get());
3725    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3726        Context.getCanonicalType(IL->getType()) == Context.IntTy)
3727      CheckPureMethod(Method, Init->getSourceRange());
3728    else {
3729      Diag(Method->getLocation(), diag::err_member_function_initialization)
3730        << Method->getDeclName() << Init->getSourceRange();
3731      Method->setInvalidDecl();
3732    }
3733    return;
3734  }
3735
3736  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3737  if (!VDecl) {
3738    if (getLangOptions().CPlusPlus &&
3739        RealDecl->getLexicalDeclContext()->isRecord() &&
3740        isa<NamedDecl>(RealDecl))
3741      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3742        << cast<NamedDecl>(RealDecl)->getDeclName();
3743    else
3744      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3745    RealDecl->setInvalidDecl();
3746    return;
3747  }
3748
3749  // A definition must end up with a complete type, which means it must be
3750  // complete with the restriction that an array type might be completed by the
3751  // initializer; note that later code assumes this restriction.
3752  QualType BaseDeclType = VDecl->getType();
3753  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3754    BaseDeclType = Array->getElementType();
3755  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3756                          diag::err_typecheck_decl_incomplete_type)) {
3757    RealDecl->setInvalidDecl();
3758    return;
3759  }
3760
3761  // The variable can not have an abstract class type.
3762  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3763                             diag::err_abstract_type_in_decl,
3764                             AbstractVariableType))
3765    VDecl->setInvalidDecl();
3766
3767  const VarDecl *Def;
3768  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
3769    Diag(VDecl->getLocation(), diag::err_redefinition)
3770      << VDecl->getDeclName();
3771    Diag(Def->getLocation(), diag::note_previous_definition);
3772    VDecl->setInvalidDecl();
3773    return;
3774  }
3775
3776  // Take ownership of the expression, now that we're sure we have somewhere
3777  // to put it.
3778  Expr *Init = init.takeAs<Expr>();
3779  assert(Init && "missing initializer");
3780
3781  // Capture the variable that is being initialized and the style of
3782  // initialization.
3783  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3784
3785  // FIXME: Poor source location information.
3786  InitializationKind Kind
3787    = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3788                                                   Init->getLocStart(),
3789                                                   Init->getLocEnd())
3790                : InitializationKind::CreateCopy(VDecl->getLocation(),
3791                                                 Init->getLocStart());
3792
3793  // Get the decls type and save a reference for later, since
3794  // CheckInitializerTypes may change it.
3795  QualType DclT = VDecl->getType(), SavT = DclT;
3796  if (VDecl->isBlockVarDecl()) {
3797    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3798      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3799      VDecl->setInvalidDecl();
3800    } else if (!VDecl->isInvalidDecl()) {
3801      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3802      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3803                                          MultiExprArg(*this, (void**)&Init, 1),
3804                                                &DclT);
3805      if (Result.isInvalid()) {
3806        VDecl->setInvalidDecl();
3807        return;
3808      }
3809
3810      Init = Result.takeAs<Expr>();
3811
3812      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3813      // Don't check invalid declarations to avoid emitting useless diagnostics.
3814      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3815        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3816          CheckForConstantInitializer(Init, DclT);
3817      }
3818    }
3819  } else if (VDecl->isStaticDataMember() &&
3820             VDecl->getLexicalDeclContext()->isRecord()) {
3821    // This is an in-class initialization for a static data member, e.g.,
3822    //
3823    // struct S {
3824    //   static const int value = 17;
3825    // };
3826
3827    // Attach the initializer
3828    VDecl->setInit(Init);
3829
3830    // C++ [class.mem]p4:
3831    //   A member-declarator can contain a constant-initializer only
3832    //   if it declares a static member (9.4) of const integral or
3833    //   const enumeration type, see 9.4.2.
3834    QualType T = VDecl->getType();
3835    if (!T->isDependentType() &&
3836        (!Context.getCanonicalType(T).isConstQualified() ||
3837         !T->isIntegralType())) {
3838      Diag(VDecl->getLocation(), diag::err_member_initialization)
3839        << VDecl->getDeclName() << Init->getSourceRange();
3840      VDecl->setInvalidDecl();
3841    } else {
3842      // C++ [class.static.data]p4:
3843      //   If a static data member is of const integral or const
3844      //   enumeration type, its declaration in the class definition
3845      //   can specify a constant-initializer which shall be an
3846      //   integral constant expression (5.19).
3847      if (!Init->isTypeDependent() &&
3848          !Init->getType()->isIntegralType()) {
3849        // We have a non-dependent, non-integral or enumeration type.
3850        Diag(Init->getSourceRange().getBegin(),
3851             diag::err_in_class_initializer_non_integral_type)
3852          << Init->getType() << Init->getSourceRange();
3853        VDecl->setInvalidDecl();
3854      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3855        // Check whether the expression is a constant expression.
3856        llvm::APSInt Value;
3857        SourceLocation Loc;
3858        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3859          Diag(Loc, diag::err_in_class_initializer_non_constant)
3860            << Init->getSourceRange();
3861          VDecl->setInvalidDecl();
3862        } else if (!VDecl->getType()->isDependentType())
3863          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3864      }
3865    }
3866  } else if (VDecl->isFileVarDecl()) {
3867    if (VDecl->getStorageClass() == VarDecl::Extern &&
3868        (!getLangOptions().CPlusPlus ||
3869         !Context.getBaseElementType(VDecl->getType()).isConstQualified()))
3870      Diag(VDecl->getLocation(), diag::warn_extern_init);
3871    if (!VDecl->isInvalidDecl()) {
3872      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3873      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3874                                          MultiExprArg(*this, (void**)&Init, 1),
3875                                                &DclT);
3876      if (Result.isInvalid()) {
3877        VDecl->setInvalidDecl();
3878        return;
3879      }
3880
3881      Init = Result.takeAs<Expr>();
3882    }
3883
3884    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3885    // Don't check invalid declarations to avoid emitting useless diagnostics.
3886    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3887      // C99 6.7.8p4. All file scoped initializers need to be constant.
3888      CheckForConstantInitializer(Init, DclT);
3889    }
3890  }
3891  // If the type changed, it means we had an incomplete type that was
3892  // completed by the initializer. For example:
3893  //   int ary[] = { 1, 3, 5 };
3894  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3895  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3896    VDecl->setType(DclT);
3897    Init->setType(DclT);
3898  }
3899
3900  Init = MaybeCreateCXXExprWithTemporaries(Init);
3901  // Attach the initializer to the decl.
3902  VDecl->setInit(Init);
3903
3904  if (getLangOptions().CPlusPlus) {
3905    // Make sure we mark the destructor as used if necessary.
3906    QualType InitType = VDecl->getType();
3907    while (const ArrayType *Array = Context.getAsArrayType(InitType))
3908      InitType = Context.getBaseElementType(Array);
3909    if (const RecordType *Record = InitType->getAs<RecordType>())
3910      FinalizeVarWithDestructor(VDecl, Record);
3911  }
3912
3913  return;
3914}
3915
3916/// ActOnInitializerError - Given that there was an error parsing an
3917/// initializer for the given declaration, try to return to some form
3918/// of sanity.
3919void Sema::ActOnInitializerError(DeclPtrTy dcl) {
3920  // Our main concern here is re-establishing invariants like "a
3921  // variable's type is either dependent or complete".
3922  Decl *D = dcl.getAs<Decl>();
3923  if (!D || D->isInvalidDecl()) return;
3924
3925  VarDecl *VD = dyn_cast<VarDecl>(D);
3926  if (!VD) return;
3927
3928  QualType Ty = VD->getType();
3929  if (Ty->isDependentType()) return;
3930
3931  // Require a complete type.
3932  if (RequireCompleteType(VD->getLocation(),
3933                          Context.getBaseElementType(Ty),
3934                          diag::err_typecheck_decl_incomplete_type)) {
3935    VD->setInvalidDecl();
3936    return;
3937  }
3938
3939  // Require an abstract type.
3940  if (RequireNonAbstractType(VD->getLocation(), Ty,
3941                             diag::err_abstract_type_in_decl,
3942                             AbstractVariableType)) {
3943    VD->setInvalidDecl();
3944    return;
3945  }
3946
3947  // Don't bother complaining about constructors or destructors,
3948  // though.
3949}
3950
3951void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3952                                  bool TypeContainsUndeducedAuto) {
3953  Decl *RealDecl = dcl.getAs<Decl>();
3954
3955  // If there is no declaration, there was an error parsing it. Just ignore it.
3956  if (RealDecl == 0)
3957    return;
3958
3959  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3960    QualType Type = Var->getType();
3961
3962    // C++0x [dcl.spec.auto]p3
3963    if (TypeContainsUndeducedAuto) {
3964      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3965        << Var->getDeclName() << Type;
3966      Var->setInvalidDecl();
3967      return;
3968    }
3969
3970    switch (Var->isThisDeclarationADefinition()) {
3971    case VarDecl::Definition:
3972      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
3973        break;
3974
3975      // We have an out-of-line definition of a static data member
3976      // that has an in-class initializer, so we type-check this like
3977      // a declaration.
3978      //
3979      // Fall through
3980
3981    case VarDecl::DeclarationOnly:
3982      // It's only a declaration.
3983
3984      // Block scope. C99 6.7p7: If an identifier for an object is
3985      // declared with no linkage (C99 6.2.2p6), the type for the
3986      // object shall be complete.
3987      if (!Type->isDependentType() && Var->isBlockVarDecl() &&
3988          !Var->getLinkage() && !Var->isInvalidDecl() &&
3989          RequireCompleteType(Var->getLocation(), Type,
3990                              diag::err_typecheck_decl_incomplete_type))
3991        Var->setInvalidDecl();
3992
3993      // Make sure that the type is not abstract.
3994      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
3995          RequireNonAbstractType(Var->getLocation(), Type,
3996                                 diag::err_abstract_type_in_decl,
3997                                 AbstractVariableType))
3998        Var->setInvalidDecl();
3999      return;
4000
4001    case VarDecl::TentativeDefinition:
4002      // File scope. C99 6.9.2p2: A declaration of an identifier for an
4003      // object that has file scope without an initializer, and without a
4004      // storage-class specifier or with the storage-class specifier "static",
4005      // constitutes a tentative definition. Note: A tentative definition with
4006      // external linkage is valid (C99 6.2.2p5).
4007      if (!Var->isInvalidDecl()) {
4008        if (const IncompleteArrayType *ArrayT
4009                                    = Context.getAsIncompleteArrayType(Type)) {
4010          if (RequireCompleteType(Var->getLocation(),
4011                                  ArrayT->getElementType(),
4012                                  diag::err_illegal_decl_array_incomplete_type))
4013            Var->setInvalidDecl();
4014        } else if (Var->getStorageClass() == VarDecl::Static) {
4015          // C99 6.9.2p3: If the declaration of an identifier for an object is
4016          // a tentative definition and has internal linkage (C99 6.2.2p3), the
4017          // declared type shall not be an incomplete type.
4018          // NOTE: code such as the following
4019          //     static struct s;
4020          //     struct s { int a; };
4021          // is accepted by gcc. Hence here we issue a warning instead of
4022          // an error and we do not invalidate the static declaration.
4023          // NOTE: to avoid multiple warnings, only check the first declaration.
4024          if (Var->getPreviousDeclaration() == 0)
4025            RequireCompleteType(Var->getLocation(), Type,
4026                                diag::ext_typecheck_decl_incomplete_type);
4027        }
4028      }
4029
4030      // Record the tentative definition; we're done.
4031      if (!Var->isInvalidDecl())
4032        TentativeDefinitions.push_back(Var);
4033      return;
4034    }
4035
4036    // Provide a specific diagnostic for uninitialized variable
4037    // definitions with incomplete array type.
4038    if (Type->isIncompleteArrayType()) {
4039      Diag(Var->getLocation(),
4040           diag::err_typecheck_incomplete_array_needs_initializer);
4041      Var->setInvalidDecl();
4042      return;
4043    }
4044
4045   // Provide a specific diagnostic for uninitialized variable
4046   // definitions with reference type.
4047   if (Type->isReferenceType()) {
4048     Diag(Var->getLocation(), diag::err_reference_var_requires_init)
4049       << Var->getDeclName()
4050       << SourceRange(Var->getLocation(), Var->getLocation());
4051     Var->setInvalidDecl();
4052     return;
4053   }
4054
4055    // Do not attempt to type-check the default initializer for a
4056    // variable with dependent type.
4057    if (Type->isDependentType())
4058      return;
4059
4060    if (Var->isInvalidDecl())
4061      return;
4062
4063    if (RequireCompleteType(Var->getLocation(),
4064                            Context.getBaseElementType(Type),
4065                            diag::err_typecheck_decl_incomplete_type)) {
4066      Var->setInvalidDecl();
4067      return;
4068    }
4069
4070    // The variable can not have an abstract class type.
4071    if (RequireNonAbstractType(Var->getLocation(), Type,
4072                               diag::err_abstract_type_in_decl,
4073                               AbstractVariableType)) {
4074      Var->setInvalidDecl();
4075      return;
4076    }
4077
4078    const RecordType *Record
4079      = Context.getBaseElementType(Type)->getAs<RecordType>();
4080    if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4081        cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4082      // C++03 [dcl.init]p9:
4083      //   If no initializer is specified for an object, and the
4084      //   object is of (possibly cv-qualified) non-POD class type (or
4085      //   array thereof), the object shall be default-initialized; if
4086      //   the object is of const-qualified type, the underlying class
4087      //   type shall have a user-declared default
4088      //   constructor. Otherwise, if no initializer is specified for
4089      //   a non- static object, the object and its subobjects, if
4090      //   any, have an indeterminate initial value); if the object
4091      //   or any of its subobjects are of const-qualified type, the
4092      //   program is ill-formed.
4093      // FIXME: DPG thinks it is very fishy that C++0x disables this.
4094    } else {
4095      InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4096      InitializationKind Kind
4097        = InitializationKind::CreateDefault(Var->getLocation());
4098
4099      InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4100      OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4101                                              MultiExprArg(*this, 0, 0));
4102      if (Init.isInvalid())
4103        Var->setInvalidDecl();
4104      else if (Init.get())
4105        Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
4106    }
4107
4108    if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
4109      FinalizeVarWithDestructor(Var, Record);
4110  }
4111}
4112
4113Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4114                                                   DeclPtrTy *Group,
4115                                                   unsigned NumDecls) {
4116  llvm::SmallVector<Decl*, 8> Decls;
4117
4118  if (DS.isTypeSpecOwned())
4119    Decls.push_back((Decl*)DS.getTypeRep());
4120
4121  for (unsigned i = 0; i != NumDecls; ++i)
4122    if (Decl *D = Group[i].getAs<Decl>())
4123      Decls.push_back(D);
4124
4125  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
4126                                                   Decls.data(), Decls.size()));
4127}
4128
4129
4130/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4131/// to introduce parameters into function prototype scope.
4132Sema::DeclPtrTy
4133Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
4134  const DeclSpec &DS = D.getDeclSpec();
4135
4136  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
4137  VarDecl::StorageClass StorageClass = VarDecl::None;
4138  VarDecl::StorageClass StorageClassAsWritten = VarDecl::None;
4139  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4140    StorageClass = VarDecl::Register;
4141    StorageClassAsWritten = VarDecl::Register;
4142  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
4143    Diag(DS.getStorageClassSpecLoc(),
4144         diag::err_invalid_storage_class_in_func_decl);
4145    D.getMutableDeclSpec().ClearStorageClassSpecs();
4146  }
4147
4148  if (D.getDeclSpec().isThreadSpecified())
4149    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4150
4151  DiagnoseFunctionSpecifiers(D);
4152
4153  // Check that there are no default arguments inside the type of this
4154  // parameter (C++ only).
4155  if (getLangOptions().CPlusPlus)
4156    CheckExtraCXXDefaultArguments(D);
4157
4158  TypeSourceInfo *TInfo = 0;
4159  TagDecl *OwnedDecl = 0;
4160  QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
4161
4162  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
4163    // C++ [dcl.fct]p6:
4164    //   Types shall not be defined in return or parameter types.
4165    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
4166      << Context.getTypeDeclType(OwnedDecl);
4167  }
4168
4169  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
4170  IdentifierInfo *II = D.getIdentifier();
4171  if (II) {
4172    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
4173                   ForRedeclaration);
4174    LookupName(R, S);
4175    if (R.isSingleResult()) {
4176      NamedDecl *PrevDecl = R.getFoundDecl();
4177      if (PrevDecl->isTemplateParameter()) {
4178        // Maybe we will complain about the shadowed template parameter.
4179        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4180        // Just pretend that we didn't see the previous declaration.
4181        PrevDecl = 0;
4182      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
4183        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
4184        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4185
4186        // Recover by removing the name
4187        II = 0;
4188        D.SetIdentifier(0, D.getIdentifierLoc());
4189        D.setInvalidType(true);
4190      }
4191    }
4192  }
4193
4194  // Temporarily put parameter variables in the translation unit, not
4195  // the enclosing context.  This prevents them from accidentally
4196  // looking like class members in C++.
4197  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
4198                                    TInfo, parmDeclType, II,
4199                                    D.getIdentifierLoc(),
4200                                    StorageClass, StorageClassAsWritten);
4201
4202  if (D.isInvalidType())
4203    New->setInvalidDecl();
4204
4205  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4206  if (D.getCXXScopeSpec().isSet()) {
4207    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4208      << D.getCXXScopeSpec().getRange();
4209    New->setInvalidDecl();
4210  }
4211
4212  // Add the parameter declaration into this scope.
4213  S->AddDecl(DeclPtrTy::make(New));
4214  if (II)
4215    IdResolver.AddDecl(New);
4216
4217  ProcessDeclAttributes(S, New, D);
4218
4219  if (New->hasAttr<BlocksAttr>()) {
4220    Diag(New->getLocation(), diag::err_block_on_nonlocal);
4221  }
4222  return DeclPtrTy::make(New);
4223}
4224
4225ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
4226                                  TypeSourceInfo *TSInfo, QualType T,
4227                                  IdentifierInfo *Name,
4228                                  SourceLocation NameLoc,
4229                                  VarDecl::StorageClass StorageClass,
4230                                  VarDecl::StorageClass StorageClassAsWritten) {
4231  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
4232                                         adjustParameterType(T), TSInfo,
4233                                         StorageClass, StorageClassAsWritten,
4234                                         0);
4235
4236  // Parameters can not be abstract class types.
4237  // For record types, this is done by the AbstractClassUsageDiagnoser once
4238  // the class has been completely parsed.
4239  if (!CurContext->isRecord() &&
4240      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
4241                             AbstractParamType))
4242    New->setInvalidDecl();
4243
4244  // Parameter declarators cannot be interface types. All ObjC objects are
4245  // passed by reference.
4246  if (T->isObjCInterfaceType()) {
4247    Diag(NameLoc,
4248         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4249    New->setInvalidDecl();
4250  }
4251
4252  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4253  // duration shall not be qualified by an address-space qualifier."
4254  // Since all parameters have automatic store duration, they can not have
4255  // an address space.
4256  if (T.getAddressSpace() != 0) {
4257    Diag(NameLoc, diag::err_arg_with_address_space);
4258    New->setInvalidDecl();
4259  }
4260
4261  return New;
4262}
4263
4264void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4265                                           SourceLocation LocAfterDecls) {
4266  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4267         "Not a function declarator!");
4268  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4269
4270  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4271  // for a K&R function.
4272  if (!FTI.hasPrototype) {
4273    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4274      --i;
4275      if (FTI.ArgInfo[i].Param == 0) {
4276        llvm::SmallString<256> Code;
4277        llvm::raw_svector_ostream(Code) << "  int "
4278                                        << FTI.ArgInfo[i].Ident->getName()
4279                                        << ";\n";
4280        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
4281          << FTI.ArgInfo[i].Ident
4282          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
4283
4284        // Implicitly declare the argument as type 'int' for lack of a better
4285        // type.
4286        DeclSpec DS;
4287        const char* PrevSpec; // unused
4288        unsigned DiagID; // unused
4289        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
4290                           PrevSpec, DiagID);
4291        Declarator ParamD(DS, Declarator::KNRTypeListContext);
4292        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
4293        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
4294      }
4295    }
4296  }
4297}
4298
4299Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4300                                              Declarator &D) {
4301  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4302  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4303         "Not a function declarator!");
4304  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4305
4306  if (FTI.hasPrototype) {
4307    // FIXME: Diagnose arguments without names in C.
4308  }
4309
4310  Scope *ParentScope = FnBodyScope->getParent();
4311
4312  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
4313                                  MultiTemplateParamsArg(*this),
4314                                  /*IsFunctionDefinition=*/true);
4315  return ActOnStartOfFunctionDef(FnBodyScope, DP);
4316}
4317
4318static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4319  // Don't warn about invalid declarations.
4320  if (FD->isInvalidDecl())
4321    return false;
4322
4323  // Or declarations that aren't global.
4324  if (!FD->isGlobal())
4325    return false;
4326
4327  // Don't warn about C++ member functions.
4328  if (isa<CXXMethodDecl>(FD))
4329    return false;
4330
4331  // Don't warn about 'main'.
4332  if (FD->isMain())
4333    return false;
4334
4335  // Don't warn about inline functions.
4336  if (FD->isInlineSpecified())
4337    return false;
4338
4339  // Don't warn about function templates.
4340  if (FD->getDescribedFunctionTemplate())
4341    return false;
4342
4343  // Don't warn about function template specializations.
4344  if (FD->isFunctionTemplateSpecialization())
4345    return false;
4346
4347  bool MissingPrototype = true;
4348  for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4349       Prev; Prev = Prev->getPreviousDeclaration()) {
4350    // Ignore any declarations that occur in function or method
4351    // scope, because they aren't visible from the header.
4352    if (Prev->getDeclContext()->isFunctionOrMethod())
4353      continue;
4354
4355    MissingPrototype = !Prev->getType()->isFunctionProtoType();
4356    break;
4357  }
4358
4359  return MissingPrototype;
4360}
4361
4362Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4363  // Clear the last template instantiation error context.
4364  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4365
4366  if (!D)
4367    return D;
4368  FunctionDecl *FD = 0;
4369
4370  if (FunctionTemplateDecl *FunTmpl
4371        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4372    FD = FunTmpl->getTemplatedDecl();
4373  else
4374    FD = cast<FunctionDecl>(D.getAs<Decl>());
4375
4376  // Enter a new function scope
4377  PushFunctionScope();
4378
4379  // See if this is a redefinition.
4380  // But don't complain if we're in GNU89 mode and the previous definition
4381  // was an extern inline function.
4382  const FunctionDecl *Definition;
4383  if (FD->getBody(Definition) &&
4384      !canRedefineFunction(Definition, getLangOptions())) {
4385    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4386    Diag(Definition->getLocation(), diag::note_previous_definition);
4387  }
4388
4389  // Builtin functions cannot be defined.
4390  if (unsigned BuiltinID = FD->getBuiltinID()) {
4391    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4392      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4393      FD->setInvalidDecl();
4394    }
4395  }
4396
4397  // The return type of a function definition must be complete
4398  // (C99 6.9.1p3, C++ [dcl.fct]p6).
4399  QualType ResultType = FD->getResultType();
4400  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4401      !FD->isInvalidDecl() &&
4402      RequireCompleteType(FD->getLocation(), ResultType,
4403                          diag::err_func_def_incomplete_result))
4404    FD->setInvalidDecl();
4405
4406  // GNU warning -Wmissing-prototypes:
4407  //   Warn if a global function is defined without a previous
4408  //   prototype declaration. This warning is issued even if the
4409  //   definition itself provides a prototype. The aim is to detect
4410  //   global functions that fail to be declared in header files.
4411  if (ShouldWarnAboutMissingPrototype(FD))
4412    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4413
4414  if (FnBodyScope)
4415    PushDeclContext(FnBodyScope, FD);
4416
4417  // Check the validity of our function parameters
4418  CheckParmsForFunctionDef(FD);
4419
4420  bool ShouldCheckShadow =
4421    Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
4422
4423  // Introduce our parameters into the function scope
4424  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4425    ParmVarDecl *Param = FD->getParamDecl(p);
4426    Param->setOwningFunction(FD);
4427
4428    // If this has an identifier, add it to the scope stack.
4429    if (Param->getIdentifier() && FnBodyScope) {
4430      if (ShouldCheckShadow)
4431        CheckShadow(FnBodyScope, Param);
4432
4433      PushOnScopeChains(Param, FnBodyScope);
4434    }
4435  }
4436
4437  // Checking attributes of current function definition
4438  // dllimport attribute.
4439  if (FD->getAttr<DLLImportAttr>() &&
4440      (!FD->getAttr<DLLExportAttr>())) {
4441    // dllimport attribute cannot be applied to definition.
4442    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4443      Diag(FD->getLocation(),
4444           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4445        << "dllimport";
4446      FD->setInvalidDecl();
4447      return DeclPtrTy::make(FD);
4448    }
4449
4450    // Visual C++ appears to not think this is an issue, so only issue
4451    // a warning when Microsoft extensions are disabled.
4452    if (!LangOpts.Microsoft) {
4453      // If a symbol previously declared dllimport is later defined, the
4454      // attribute is ignored in subsequent references, and a warning is
4455      // emitted.
4456      Diag(FD->getLocation(),
4457           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4458        << FD->getNameAsCString() << "dllimport";
4459    }
4460  }
4461  return DeclPtrTy::make(FD);
4462}
4463
4464Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4465  return ActOnFinishFunctionBody(D, move(BodyArg), false);
4466}
4467
4468Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4469                                              bool IsInstantiation) {
4470  Decl *dcl = D.getAs<Decl>();
4471  Stmt *Body = BodyArg.takeAs<Stmt>();
4472
4473  FunctionDecl *FD = 0;
4474  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4475  if (FunTmpl)
4476    FD = FunTmpl->getTemplatedDecl();
4477  else
4478    FD = dyn_cast_or_null<FunctionDecl>(dcl);
4479
4480  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
4481
4482  if (FD) {
4483    FD->setBody(Body);
4484    if (FD->isMain()) {
4485      // C and C++ allow for main to automagically return 0.
4486      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4487      FD->setHasImplicitReturnZero(true);
4488      WP.disableCheckFallThrough();
4489    }
4490
4491    if (!FD->isInvalidDecl())
4492      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4493
4494    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4495      MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
4496
4497    assert(FD == getCurFunctionDecl() && "Function parsing confused");
4498  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4499    assert(MD == getCurMethodDecl() && "Method parsing confused");
4500    MD->setBody(Body);
4501    MD->setEndLoc(Body->getLocEnd());
4502    if (!MD->isInvalidDecl())
4503      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4504  } else {
4505    Body->Destroy(Context);
4506    return DeclPtrTy();
4507  }
4508
4509  // Verify and clean out per-function state.
4510
4511  // Check goto/label use.
4512  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4513       I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
4514    LabelStmt *L = I->second;
4515
4516    // Verify that we have no forward references left.  If so, there was a goto
4517    // or address of a label taken, but no definition of it.  Label fwd
4518    // definitions are indicated with a null substmt.
4519    if (L->getSubStmt() != 0)
4520      continue;
4521
4522    // Emit error.
4523    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4524
4525    // At this point, we have gotos that use the bogus label.  Stitch it into
4526    // the function body so that they aren't leaked and that the AST is well
4527    // formed.
4528    if (Body == 0) {
4529      // The whole function wasn't parsed correctly, just delete this.
4530      L->Destroy(Context);
4531      continue;
4532    }
4533
4534    // Otherwise, the body is valid: we want to stitch the label decl into the
4535    // function somewhere so that it is properly owned and so that the goto
4536    // has a valid target.  Do this by creating a new compound stmt with the
4537    // label in it.
4538
4539    // Give the label a sub-statement.
4540    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4541
4542    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4543                               cast<CXXTryStmt>(Body)->getTryBlock() :
4544                               cast<CompoundStmt>(Body);
4545    llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
4546                                          Compound->body_end());
4547    Elements.push_back(L);
4548    Compound->setStmts(Context, Elements.data(), Elements.size());
4549  }
4550
4551  if (Body) {
4552    // C++ constructors that have function-try-blocks can't have return
4553    // statements in the handlers of that block. (C++ [except.handle]p14)
4554    // Verify this.
4555    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4556      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4557
4558    // Verify that that gotos and switch cases don't jump into scopes illegally.
4559    // Verify that that gotos and switch cases don't jump into scopes illegally.
4560    if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
4561      DiagnoseInvalidJumps(Body);
4562
4563    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4564      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4565                                             Destructor->getParent());
4566
4567    // If any errors have occurred, clear out any temporaries that may have
4568    // been leftover. This ensures that these temporaries won't be picked up for
4569    // deletion in some later function.
4570    if (PP.getDiagnostics().hasErrorOccurred())
4571      ExprTemporaries.clear();
4572    else if (!isa<FunctionTemplateDecl>(dcl)) {
4573      // Since the body is valid, issue any analysis-based warnings that are
4574      // enabled.
4575      QualType ResultType;
4576      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
4577        ResultType = FD->getResultType();
4578      }
4579      else {
4580        ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
4581        ResultType = MD->getResultType();
4582      }
4583      AnalysisWarnings.IssueWarnings(WP, dcl);
4584    }
4585
4586    assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4587  }
4588
4589  if (!IsInstantiation)
4590    PopDeclContext();
4591
4592  PopFunctionOrBlockScope();
4593
4594  // If any errors have occurred, clear out any temporaries that may have
4595  // been leftover. This ensures that these temporaries won't be picked up for
4596  // deletion in some later function.
4597  if (getDiagnostics().hasErrorOccurred())
4598    ExprTemporaries.clear();
4599
4600  return D;
4601}
4602
4603/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4604/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4605NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4606                                          IdentifierInfo &II, Scope *S) {
4607  // Before we produce a declaration for an implicitly defined
4608  // function, see whether there was a locally-scoped declaration of
4609  // this name as a function or variable. If so, use that
4610  // (non-visible) declaration, and complain about it.
4611  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4612    = LocallyScopedExternalDecls.find(&II);
4613  if (Pos != LocallyScopedExternalDecls.end()) {
4614    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4615    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4616    return Pos->second;
4617  }
4618
4619  // Extension in C99.  Legal in C90, but warn about it.
4620  if (II.getName().startswith("__builtin_"))
4621    Diag(Loc, diag::warn_builtin_unknown) << &II;
4622  else if (getLangOptions().C99)
4623    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4624  else
4625    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4626
4627  // Set a Declarator for the implicit definition: int foo();
4628  const char *Dummy;
4629  DeclSpec DS;
4630  unsigned DiagID;
4631  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4632  Error = Error; // Silence warning.
4633  assert(!Error && "Error setting up implicit decl!");
4634  Declarator D(DS, Declarator::BlockContext);
4635  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4636                                             0, 0, false, SourceLocation(),
4637                                             false, 0,0,0, Loc, Loc, D),
4638                SourceLocation());
4639  D.SetIdentifier(&II, Loc);
4640
4641  // Insert this function into translation-unit scope.
4642
4643  DeclContext *PrevDC = CurContext;
4644  CurContext = Context.getTranslationUnitDecl();
4645
4646  FunctionDecl *FD =
4647 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4648  FD->setImplicit();
4649
4650  CurContext = PrevDC;
4651
4652  AddKnownFunctionAttributes(FD);
4653
4654  return FD;
4655}
4656
4657/// \brief Adds any function attributes that we know a priori based on
4658/// the declaration of this function.
4659///
4660/// These attributes can apply both to implicitly-declared builtins
4661/// (like __builtin___printf_chk) or to library-declared functions
4662/// like NSLog or printf.
4663void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4664  if (FD->isInvalidDecl())
4665    return;
4666
4667  // If this is a built-in function, map its builtin attributes to
4668  // actual attributes.
4669  if (unsigned BuiltinID = FD->getBuiltinID()) {
4670    // Handle printf-formatting attributes.
4671    unsigned FormatIdx;
4672    bool HasVAListArg;
4673    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4674      if (!FD->getAttr<FormatAttr>())
4675        FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
4676                                               HasVAListArg ? 0 : FormatIdx+2));
4677    }
4678
4679    // Mark const if we don't care about errno and that is the only
4680    // thing preventing the function from being const. This allows
4681    // IRgen to use LLVM intrinsics for such functions.
4682    if (!getLangOptions().MathErrno &&
4683        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4684      if (!FD->getAttr<ConstAttr>())
4685        FD->addAttr(::new (Context) ConstAttr());
4686    }
4687
4688    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4689      FD->setType(Context.getNoReturnType(FD->getType()));
4690    if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4691      FD->addAttr(::new (Context) NoThrowAttr());
4692    if (Context.BuiltinInfo.isConst(BuiltinID))
4693      FD->addAttr(::new (Context) ConstAttr());
4694  }
4695
4696  IdentifierInfo *Name = FD->getIdentifier();
4697  if (!Name)
4698    return;
4699  if ((!getLangOptions().CPlusPlus &&
4700       FD->getDeclContext()->isTranslationUnit()) ||
4701      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4702       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4703       LinkageSpecDecl::lang_c)) {
4704    // Okay: this could be a libc/libm/Objective-C function we know
4705    // about.
4706  } else
4707    return;
4708
4709  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4710    // FIXME: NSLog and NSLogv should be target specific
4711    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4712      // FIXME: We known better than our headers.
4713      const_cast<FormatAttr *>(Format)->setType(Context, "printf");
4714    } else
4715      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
4716                                             Name->isStr("NSLogv") ? 0 : 2));
4717  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4718    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4719    // target-specific builtins, perhaps?
4720    if (!FD->getAttr<FormatAttr>())
4721      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
4722                                             Name->isStr("vasprintf") ? 0 : 3));
4723  }
4724}
4725
4726TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4727                                    TypeSourceInfo *TInfo) {
4728  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4729  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4730
4731  if (!TInfo) {
4732    assert(D.isInvalidType() && "no declarator info for valid type");
4733    TInfo = Context.getTrivialTypeSourceInfo(T);
4734  }
4735
4736  // Scope manipulation handled by caller.
4737  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4738                                           D.getIdentifierLoc(),
4739                                           D.getIdentifier(),
4740                                           TInfo);
4741
4742  if (const TagType *TT = T->getAs<TagType>()) {
4743    TagDecl *TD = TT->getDecl();
4744
4745    // If the TagDecl that the TypedefDecl points to is an anonymous decl
4746    // keep track of the TypedefDecl.
4747    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4748      TD->setTypedefForAnonDecl(NewTD);
4749  }
4750
4751  if (D.isInvalidType())
4752    NewTD->setInvalidDecl();
4753  return NewTD;
4754}
4755
4756
4757/// \brief Determine whether a tag with a given kind is acceptable
4758/// as a redeclaration of the given tag declaration.
4759///
4760/// \returns true if the new tag kind is acceptable, false otherwise.
4761bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4762                                        TagDecl::TagKind NewTag,
4763                                        SourceLocation NewTagLoc,
4764                                        const IdentifierInfo &Name) {
4765  // C++ [dcl.type.elab]p3:
4766  //   The class-key or enum keyword present in the
4767  //   elaborated-type-specifier shall agree in kind with the
4768  //   declaration to which the name in theelaborated-type-specifier
4769  //   refers. This rule also applies to the form of
4770  //   elaborated-type-specifier that declares a class-name or
4771  //   friend class since it can be construed as referring to the
4772  //   definition of the class. Thus, in any
4773  //   elaborated-type-specifier, the enum keyword shall be used to
4774  //   refer to an enumeration (7.2), the union class-keyshall be
4775  //   used to refer to a union (clause 9), and either the class or
4776  //   struct class-key shall be used to refer to a class (clause 9)
4777  //   declared using the class or struct class-key.
4778  TagDecl::TagKind OldTag = Previous->getTagKind();
4779  if (OldTag == NewTag)
4780    return true;
4781
4782  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4783      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4784    // Warn about the struct/class tag mismatch.
4785    bool isTemplate = false;
4786    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4787      isTemplate = Record->getDescribedClassTemplate();
4788
4789    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4790      << (NewTag == TagDecl::TK_class)
4791      << isTemplate << &Name
4792      << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
4793                              OldTag == TagDecl::TK_class? "class" : "struct");
4794    Diag(Previous->getLocation(), diag::note_previous_use);
4795    return true;
4796  }
4797  return false;
4798}
4799
4800/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
4801/// former case, Name will be non-null.  In the later case, Name will be null.
4802/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4803/// reference/declaration/definition of a tag.
4804Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4805                               SourceLocation KWLoc, CXXScopeSpec &SS,
4806                               IdentifierInfo *Name, SourceLocation NameLoc,
4807                               AttributeList *Attr, AccessSpecifier AS,
4808                               MultiTemplateParamsArg TemplateParameterLists,
4809                               bool &OwnedDecl, bool &IsDependent) {
4810  // If this is not a definition, it must have a name.
4811  assert((Name != 0 || TUK == TUK_Definition) &&
4812         "Nameless record must be a definition!");
4813
4814  OwnedDecl = false;
4815  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4816
4817  // FIXME: Check explicit specializations more carefully.
4818  bool isExplicitSpecialization = false;
4819  if (TUK != TUK_Reference) {
4820    if (TemplateParameterList *TemplateParams
4821          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4822                        (TemplateParameterList**)TemplateParameterLists.get(),
4823                                              TemplateParameterLists.size(),
4824                                                    TUK == TUK_Friend,
4825                                                    isExplicitSpecialization)) {
4826      if (TemplateParams->size() > 0) {
4827        // This is a declaration or definition of a class template (which may
4828        // be a member of another template).
4829        OwnedDecl = false;
4830        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4831                                               SS, Name, NameLoc, Attr,
4832                                               TemplateParams,
4833                                               AS);
4834        TemplateParameterLists.release();
4835        return Result.get();
4836      } else {
4837        // The "template<>" header is extraneous.
4838        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4839          << ElaboratedType::getNameForTagKind(Kind) << Name;
4840        isExplicitSpecialization = true;
4841      }
4842    }
4843
4844    TemplateParameterLists.release();
4845  }
4846
4847  DeclContext *SearchDC = CurContext;
4848  DeclContext *DC = CurContext;
4849  bool isStdBadAlloc = false;
4850  bool Invalid = false;
4851
4852  RedeclarationKind Redecl = ForRedeclaration;
4853  if (TUK == TUK_Friend || TUK == TUK_Reference)
4854    Redecl = NotForRedeclaration;
4855
4856  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4857
4858  if (Name && SS.isNotEmpty()) {
4859    // We have a nested-name tag ('struct foo::bar').
4860
4861    // Check for invalid 'foo::'.
4862    if (SS.isInvalid()) {
4863      Name = 0;
4864      goto CreateNewDecl;
4865    }
4866
4867    // If this is a friend or a reference to a class in a dependent
4868    // context, don't try to make a decl for it.
4869    if (TUK == TUK_Friend || TUK == TUK_Reference) {
4870      DC = computeDeclContext(SS, false);
4871      if (!DC) {
4872        IsDependent = true;
4873        return DeclPtrTy();
4874      }
4875    }
4876
4877    if (RequireCompleteDeclContext(SS))
4878      return DeclPtrTy::make((Decl *)0);
4879
4880    DC = computeDeclContext(SS, true);
4881    SearchDC = DC;
4882    // Look-up name inside 'foo::'.
4883    LookupQualifiedName(Previous, DC);
4884
4885    if (Previous.isAmbiguous())
4886      return DeclPtrTy();
4887
4888    if (Previous.empty()) {
4889      // Name lookup did not find anything. However, if the
4890      // nested-name-specifier refers to the current instantiation,
4891      // and that current instantiation has any dependent base
4892      // classes, we might find something at instantiation time: treat
4893      // this as a dependent elaborated-type-specifier.
4894      if (Previous.wasNotFoundInCurrentInstantiation()) {
4895        IsDependent = true;
4896        return DeclPtrTy();
4897      }
4898
4899      // A tag 'foo::bar' must already exist.
4900      Diag(NameLoc, diag::err_not_tag_in_scope)
4901        << Kind << Name << DC << SS.getRange();
4902      Name = 0;
4903      Invalid = true;
4904      goto CreateNewDecl;
4905    }
4906  } else if (Name) {
4907    // If this is a named struct, check to see if there was a previous forward
4908    // declaration or definition.
4909    // FIXME: We're looking into outer scopes here, even when we
4910    // shouldn't be. Doing so can result in ambiguities that we
4911    // shouldn't be diagnosing.
4912    LookupName(Previous, S);
4913
4914    // Note:  there used to be some attempt at recovery here.
4915    if (Previous.isAmbiguous())
4916      return DeclPtrTy();
4917
4918    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4919      // FIXME: This makes sure that we ignore the contexts associated
4920      // with C structs, unions, and enums when looking for a matching
4921      // tag declaration or definition. See the similar lookup tweak
4922      // in Sema::LookupName; is there a better way to deal with this?
4923      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4924        SearchDC = SearchDC->getParent();
4925    }
4926  }
4927
4928  if (Previous.isSingleResult() &&
4929      Previous.getFoundDecl()->isTemplateParameter()) {
4930    // Maybe we will complain about the shadowed template parameter.
4931    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4932    // Just pretend that we didn't see the previous declaration.
4933    Previous.clear();
4934  }
4935
4936  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4937      DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4938    // This is a declaration of or a reference to "std::bad_alloc".
4939    isStdBadAlloc = true;
4940
4941    if (Previous.empty() && StdBadAlloc) {
4942      // std::bad_alloc has been implicitly declared (but made invisible to
4943      // name lookup). Fill in this implicit declaration as the previous
4944      // declaration, so that the declarations get chained appropriately.
4945      Previous.addDecl(StdBadAlloc);
4946    }
4947  }
4948
4949  // If we didn't find a previous declaration, and this is a reference
4950  // (or friend reference), move to the correct scope.  In C++, we
4951  // also need to do a redeclaration lookup there, just in case
4952  // there's a shadow friend decl.
4953  if (Name && Previous.empty() &&
4954      (TUK == TUK_Reference || TUK == TUK_Friend)) {
4955    if (Invalid) goto CreateNewDecl;
4956    assert(SS.isEmpty());
4957
4958    if (TUK == TUK_Reference) {
4959      // C++ [basic.scope.pdecl]p5:
4960      //   -- for an elaborated-type-specifier of the form
4961      //
4962      //          class-key identifier
4963      //
4964      //      if the elaborated-type-specifier is used in the
4965      //      decl-specifier-seq or parameter-declaration-clause of a
4966      //      function defined in namespace scope, the identifier is
4967      //      declared as a class-name in the namespace that contains
4968      //      the declaration; otherwise, except as a friend
4969      //      declaration, the identifier is declared in the smallest
4970      //      non-class, non-function-prototype scope that contains the
4971      //      declaration.
4972      //
4973      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4974      // C structs and unions.
4975      //
4976      // It is an error in C++ to declare (rather than define) an enum
4977      // type, including via an elaborated type specifier.  We'll
4978      // diagnose that later; for now, declare the enum in the same
4979      // scope as we would have picked for any other tag type.
4980      //
4981      // GNU C also supports this behavior as part of its incomplete
4982      // enum types extension, while GNU C++ does not.
4983      //
4984      // Find the context where we'll be declaring the tag.
4985      // FIXME: We would like to maintain the current DeclContext as the
4986      // lexical context,
4987      while (SearchDC->isRecord())
4988        SearchDC = SearchDC->getParent();
4989
4990      // Find the scope where we'll be declaring the tag.
4991      while (S->isClassScope() ||
4992             (getLangOptions().CPlusPlus &&
4993              S->isFunctionPrototypeScope()) ||
4994             ((S->getFlags() & Scope::DeclScope) == 0) ||
4995             (S->getEntity() &&
4996              ((DeclContext *)S->getEntity())->isTransparentContext()))
4997        S = S->getParent();
4998    } else {
4999      assert(TUK == TUK_Friend);
5000      // C++ [namespace.memdef]p3:
5001      //   If a friend declaration in a non-local class first declares a
5002      //   class or function, the friend class or function is a member of
5003      //   the innermost enclosing namespace.
5004      SearchDC = SearchDC->getEnclosingNamespaceContext();
5005    }
5006
5007    // In C++, we need to do a redeclaration lookup to properly
5008    // diagnose some problems.
5009    if (getLangOptions().CPlusPlus) {
5010      Previous.setRedeclarationKind(ForRedeclaration);
5011      LookupQualifiedName(Previous, SearchDC);
5012    }
5013  }
5014
5015  if (!Previous.empty()) {
5016    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
5017
5018    // It's okay to have a tag decl in the same scope as a typedef
5019    // which hides a tag decl in the same scope.  Finding this
5020    // insanity with a redeclaration lookup can only actually happen
5021    // in C++.
5022    //
5023    // This is also okay for elaborated-type-specifiers, which is
5024    // technically forbidden by the current standard but which is
5025    // okay according to the likely resolution of an open issue;
5026    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
5027    if (getLangOptions().CPlusPlus) {
5028      if (TypedefDecl *TD = dyn_cast<TypedefDecl>(PrevDecl)) {
5029        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
5030          TagDecl *Tag = TT->getDecl();
5031          if (Tag->getDeclName() == Name &&
5032              Tag->getDeclContext()->getLookupContext()
5033                          ->Equals(TD->getDeclContext()->getLookupContext())) {
5034            PrevDecl = Tag;
5035            Previous.clear();
5036            Previous.addDecl(Tag);
5037          }
5038        }
5039      }
5040    }
5041
5042    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
5043      // If this is a use of a previous tag, or if the tag is already declared
5044      // in the same scope (so that the definition/declaration completes or
5045      // rementions the tag), reuse the decl.
5046      if (TUK == TUK_Reference || TUK == TUK_Friend ||
5047          isDeclInScope(PrevDecl, SearchDC, S)) {
5048        // Make sure that this wasn't declared as an enum and now used as a
5049        // struct or something similar.
5050        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
5051          bool SafeToContinue
5052            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
5053               Kind != TagDecl::TK_enum);
5054          if (SafeToContinue)
5055            Diag(KWLoc, diag::err_use_with_wrong_tag)
5056              << Name
5057              << FixItHint::CreateReplacement(SourceRange(KWLoc),
5058                                              PrevTagDecl->getKindName());
5059          else
5060            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
5061          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
5062
5063          if (SafeToContinue)
5064            Kind = PrevTagDecl->getTagKind();
5065          else {
5066            // Recover by making this an anonymous redefinition.
5067            Name = 0;
5068            Previous.clear();
5069            Invalid = true;
5070          }
5071        }
5072
5073        if (!Invalid) {
5074          // If this is a use, just return the declaration we found.
5075
5076          // FIXME: In the future, return a variant or some other clue
5077          // for the consumer of this Decl to know it doesn't own it.
5078          // For our current ASTs this shouldn't be a problem, but will
5079          // need to be changed with DeclGroups.
5080          if (TUK == TUK_Reference || TUK == TUK_Friend)
5081            return DeclPtrTy::make(PrevTagDecl);
5082
5083          // Diagnose attempts to redefine a tag.
5084          if (TUK == TUK_Definition) {
5085            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
5086              // If we're defining a specialization and the previous definition
5087              // is from an implicit instantiation, don't emit an error
5088              // here; we'll catch this in the general case below.
5089              if (!isExplicitSpecialization ||
5090                  !isa<CXXRecordDecl>(Def) ||
5091                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
5092                                               == TSK_ExplicitSpecialization) {
5093                Diag(NameLoc, diag::err_redefinition) << Name;
5094                Diag(Def->getLocation(), diag::note_previous_definition);
5095                // If this is a redefinition, recover by making this
5096                // struct be anonymous, which will make any later
5097                // references get the previous definition.
5098                Name = 0;
5099                Previous.clear();
5100                Invalid = true;
5101              }
5102            } else {
5103              // If the type is currently being defined, complain
5104              // about a nested redefinition.
5105              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
5106              if (Tag->isBeingDefined()) {
5107                Diag(NameLoc, diag::err_nested_redefinition) << Name;
5108                Diag(PrevTagDecl->getLocation(),
5109                     diag::note_previous_definition);
5110                Name = 0;
5111                Previous.clear();
5112                Invalid = true;
5113              }
5114            }
5115
5116            // Okay, this is definition of a previously declared or referenced
5117            // tag PrevDecl. We're going to create a new Decl for it.
5118          }
5119        }
5120        // If we get here we have (another) forward declaration or we
5121        // have a definition.  Just create a new decl.
5122
5123      } else {
5124        // If we get here, this is a definition of a new tag type in a nested
5125        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
5126        // new decl/type.  We set PrevDecl to NULL so that the entities
5127        // have distinct types.
5128        Previous.clear();
5129      }
5130      // If we get here, we're going to create a new Decl. If PrevDecl
5131      // is non-NULL, it's a definition of the tag declared by
5132      // PrevDecl. If it's NULL, we have a new definition.
5133
5134
5135    // Otherwise, PrevDecl is not a tag, but was found with tag
5136    // lookup.  This is only actually possible in C++, where a few
5137    // things like templates still live in the tag namespace.
5138    } else {
5139      assert(getLangOptions().CPlusPlus);
5140
5141      // Use a better diagnostic if an elaborated-type-specifier
5142      // found the wrong kind of type on the first
5143      // (non-redeclaration) lookup.
5144      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
5145          !Previous.isForRedeclaration()) {
5146        unsigned Kind = 0;
5147        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5148        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5149        Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
5150        Diag(PrevDecl->getLocation(), diag::note_declared_at);
5151        Invalid = true;
5152
5153      // Otherwise, only diagnose if the declaration is in scope.
5154      } else if (!isDeclInScope(PrevDecl, SearchDC, S)) {
5155        // do nothing
5156
5157      // Diagnose implicit declarations introduced by elaborated types.
5158      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
5159        unsigned Kind = 0;
5160        if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
5161        else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 2;
5162        Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
5163        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5164        Invalid = true;
5165
5166      // Otherwise it's a declaration.  Call out a particularly common
5167      // case here.
5168      } else if (isa<TypedefDecl>(PrevDecl)) {
5169        Diag(NameLoc, diag::err_tag_definition_of_typedef)
5170          << Name
5171          << cast<TypedefDecl>(PrevDecl)->getUnderlyingType();
5172        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
5173        Invalid = true;
5174
5175      // Otherwise, diagnose.
5176      } else {
5177        // The tag name clashes with something else in the target scope,
5178        // issue an error and recover by making this tag be anonymous.
5179        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
5180        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5181        Name = 0;
5182        Invalid = true;
5183      }
5184
5185      // The existing declaration isn't relevant to us; we're in a
5186      // new scope, so clear out the previous declaration.
5187      Previous.clear();
5188    }
5189  }
5190
5191CreateNewDecl:
5192
5193  TagDecl *PrevDecl = 0;
5194  if (Previous.isSingleResult())
5195    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
5196
5197  // If there is an identifier, use the location of the identifier as the
5198  // location of the decl, otherwise use the location of the struct/union
5199  // keyword.
5200  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
5201
5202  // Otherwise, create a new declaration. If there is a previous
5203  // declaration of the same entity, the two will be linked via
5204  // PrevDecl.
5205  TagDecl *New;
5206
5207  if (Kind == TagDecl::TK_enum) {
5208    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5209    // enum X { A, B, C } D;    D should chain to X.
5210    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
5211                           cast_or_null<EnumDecl>(PrevDecl));
5212    // If this is an undefined enum, warn.
5213    if (TUK != TUK_Definition && !Invalid)  {
5214      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
5215                                              : diag::ext_forward_ref_enum;
5216      Diag(Loc, DK);
5217    }
5218  } else {
5219    // struct/union/class
5220
5221    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5222    // struct X { int A; } D;    D should chain to X.
5223    if (getLangOptions().CPlusPlus) {
5224      // FIXME: Look for a way to use RecordDecl for simple structs.
5225      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5226                                  cast_or_null<CXXRecordDecl>(PrevDecl));
5227
5228      if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
5229        StdBadAlloc = cast<CXXRecordDecl>(New);
5230    } else
5231      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5232                               cast_or_null<RecordDecl>(PrevDecl));
5233  }
5234
5235  // Maybe add qualifier info.
5236  if (SS.isNotEmpty()) {
5237    NestedNameSpecifier *NNS
5238      = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5239    New->setQualifierInfo(NNS, SS.getRange());
5240  }
5241
5242  if (Kind != TagDecl::TK_enum) {
5243    // Handle #pragma pack: if the #pragma pack stack has non-default
5244    // alignment, make up a packed attribute for this decl. These
5245    // attributes are checked when the ASTContext lays out the
5246    // structure.
5247    //
5248    // It is important for implementing the correct semantics that this
5249    // happen here (in act on tag decl). The #pragma pack stack is
5250    // maintained as a result of parser callbacks which can occur at
5251    // many points during the parsing of a struct declaration (because
5252    // the #pragma tokens are effectively skipped over during the
5253    // parsing of the struct).
5254    if (unsigned Alignment = getPragmaPackAlignment())
5255      New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
5256  }
5257
5258  // If this is a specialization of a member class (of a class template),
5259  // check the specialization.
5260  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
5261    Invalid = true;
5262
5263  if (Invalid)
5264    New->setInvalidDecl();
5265
5266  if (Attr)
5267    ProcessDeclAttributeList(S, New, Attr);
5268
5269  // If we're declaring or defining a tag in function prototype scope
5270  // in C, note that this type can only be used within the function.
5271  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
5272    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
5273
5274  // Set the lexical context. If the tag has a C++ scope specifier, the
5275  // lexical context will be different from the semantic context.
5276  New->setLexicalDeclContext(CurContext);
5277
5278  // Mark this as a friend decl if applicable.
5279  if (TUK == TUK_Friend)
5280    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
5281
5282  // Set the access specifier.
5283  if (!Invalid && SearchDC->isRecord())
5284    SetMemberAccessSpecifier(New, PrevDecl, AS);
5285
5286  if (TUK == TUK_Definition)
5287    New->startDefinition();
5288
5289  // If this has an identifier, add it to the scope stack.
5290  if (TUK == TUK_Friend) {
5291    // We might be replacing an existing declaration in the lookup tables;
5292    // if so, borrow its access specifier.
5293    if (PrevDecl)
5294      New->setAccess(PrevDecl->getAccess());
5295
5296    DeclContext *DC = New->getDeclContext()->getLookupContext();
5297    DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
5298    if (Name) // can be null along some error paths
5299      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5300        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
5301  } else if (Name) {
5302    S = getNonFieldDeclScope(S);
5303    PushOnScopeChains(New, S);
5304  } else {
5305    CurContext->addDecl(New);
5306  }
5307
5308  // If this is the C FILE type, notify the AST context.
5309  if (IdentifierInfo *II = New->getIdentifier())
5310    if (!New->isInvalidDecl() &&
5311        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
5312        II->isStr("FILE"))
5313      Context.setFILEDecl(New);
5314
5315  OwnedDecl = true;
5316  return DeclPtrTy::make(New);
5317}
5318
5319void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
5320  AdjustDeclIfTemplate(TagD);
5321  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5322
5323  // Enter the tag context.
5324  PushDeclContext(S, Tag);
5325}
5326
5327void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5328                                           SourceLocation LBraceLoc) {
5329  AdjustDeclIfTemplate(TagD);
5330  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
5331
5332  FieldCollector->StartClass();
5333
5334  if (!Record->getIdentifier())
5335    return;
5336
5337  // C++ [class]p2:
5338  //   [...] The class-name is also inserted into the scope of the
5339  //   class itself; this is known as the injected-class-name. For
5340  //   purposes of access checking, the injected-class-name is treated
5341  //   as if it were a public member name.
5342  CXXRecordDecl *InjectedClassName
5343    = CXXRecordDecl::Create(Context, Record->getTagKind(),
5344                            CurContext, Record->getLocation(),
5345                            Record->getIdentifier(),
5346                            Record->getTagKeywordLoc(),
5347                            Record);
5348  InjectedClassName->setImplicit();
5349  InjectedClassName->setAccess(AS_public);
5350  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5351      InjectedClassName->setDescribedClassTemplate(Template);
5352  PushOnScopeChains(InjectedClassName, S);
5353  assert(InjectedClassName->isInjectedClassName() &&
5354         "Broken injected-class-name");
5355}
5356
5357// Traverses the class and any nested classes, making a note of any
5358// dynamic classes that have no key function so that we can mark all of
5359// their virtual member functions as "used" at the end of the translation
5360// unit. This ensures that all functions needed by the vtable will get
5361// instantiated/synthesized.
5362static void
5363RecordDynamicClassesWithNoKeyFunction(Sema &S, CXXRecordDecl *Record,
5364                                      SourceLocation Loc) {
5365  // We don't look at dependent or undefined classes.
5366  if (Record->isDependentContext() || !Record->isDefinition())
5367    return;
5368
5369  if (Record->isDynamicClass()) {
5370    const CXXMethodDecl *KeyFunction = S.Context.getKeyFunction(Record);
5371
5372    if (!KeyFunction)
5373      S.ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Record,
5374                                                                   Loc));
5375
5376    if ((!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
5377        && Record->getLinkage() == ExternalLinkage)
5378      S.Diag(Record->getLocation(), diag::warn_weak_vtable) << Record;
5379  }
5380  for (DeclContext::decl_iterator D = Record->decls_begin(),
5381                               DEnd = Record->decls_end();
5382       D != DEnd; ++D) {
5383    if (CXXRecordDecl *Nested = dyn_cast<CXXRecordDecl>(*D))
5384      RecordDynamicClassesWithNoKeyFunction(S, Nested, Loc);
5385  }
5386}
5387
5388void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5389                                    SourceLocation RBraceLoc) {
5390  AdjustDeclIfTemplate(TagD);
5391  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5392  Tag->setRBraceLoc(RBraceLoc);
5393
5394  if (isa<CXXRecordDecl>(Tag))
5395    FieldCollector->FinishClass();
5396
5397  // Exit this scope of this tag's definition.
5398  PopDeclContext();
5399
5400  if (isa<CXXRecordDecl>(Tag) && !Tag->getLexicalDeclContext()->isRecord())
5401    RecordDynamicClassesWithNoKeyFunction(*this, cast<CXXRecordDecl>(Tag),
5402                                          RBraceLoc);
5403
5404  // Notify the consumer that we've defined a tag.
5405  Consumer.HandleTagDeclDefinition(Tag);
5406}
5407
5408void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) {
5409  AdjustDeclIfTemplate(TagD);
5410  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5411  Tag->setInvalidDecl();
5412
5413  // We're undoing ActOnTagStartDefinition here, not
5414  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
5415  // the FieldCollector.
5416
5417  PopDeclContext();
5418}
5419
5420// Note that FieldName may be null for anonymous bitfields.
5421bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5422                          QualType FieldTy, const Expr *BitWidth,
5423                          bool *ZeroWidth) {
5424  // Default to true; that shouldn't confuse checks for emptiness
5425  if (ZeroWidth)
5426    *ZeroWidth = true;
5427
5428  // C99 6.7.2.1p4 - verify the field type.
5429  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
5430  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
5431    // Handle incomplete types with specific error.
5432    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5433      return true;
5434    if (FieldName)
5435      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5436        << FieldName << FieldTy << BitWidth->getSourceRange();
5437    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5438      << FieldTy << BitWidth->getSourceRange();
5439  }
5440
5441  // If the bit-width is type- or value-dependent, don't try to check
5442  // it now.
5443  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5444    return false;
5445
5446  llvm::APSInt Value;
5447  if (VerifyIntegerConstantExpression(BitWidth, &Value))
5448    return true;
5449
5450  if (Value != 0 && ZeroWidth)
5451    *ZeroWidth = false;
5452
5453  // Zero-width bitfield is ok for anonymous field.
5454  if (Value == 0 && FieldName)
5455    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5456
5457  if (Value.isSigned() && Value.isNegative()) {
5458    if (FieldName)
5459      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5460               << FieldName << Value.toString(10);
5461    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5462      << Value.toString(10);
5463  }
5464
5465  if (!FieldTy->isDependentType()) {
5466    uint64_t TypeSize = Context.getTypeSize(FieldTy);
5467    if (Value.getZExtValue() > TypeSize) {
5468      if (!getLangOptions().CPlusPlus) {
5469        if (FieldName)
5470          return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5471            << FieldName << (unsigned)Value.getZExtValue()
5472            << (unsigned)TypeSize;
5473
5474        return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5475          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5476      }
5477
5478      if (FieldName)
5479        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size)
5480          << FieldName << (unsigned)Value.getZExtValue()
5481          << (unsigned)TypeSize;
5482      else
5483        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size)
5484          << (unsigned)Value.getZExtValue() << (unsigned)TypeSize;
5485    }
5486  }
5487
5488  return false;
5489}
5490
5491/// ActOnField - Each field of a struct/union/class is passed into this in order
5492/// to create a FieldDecl object for it.
5493Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5494                                 SourceLocation DeclStart,
5495                                 Declarator &D, ExprTy *BitfieldWidth) {
5496  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5497                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5498                               AS_public);
5499  return DeclPtrTy::make(Res);
5500}
5501
5502/// HandleField - Analyze a field of a C struct or a C++ data member.
5503///
5504FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5505                             SourceLocation DeclStart,
5506                             Declarator &D, Expr *BitWidth,
5507                             AccessSpecifier AS) {
5508  IdentifierInfo *II = D.getIdentifier();
5509  SourceLocation Loc = DeclStart;
5510  if (II) Loc = D.getIdentifierLoc();
5511
5512  TypeSourceInfo *TInfo = 0;
5513  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5514  if (getLangOptions().CPlusPlus)
5515    CheckExtraCXXDefaultArguments(D);
5516
5517  DiagnoseFunctionSpecifiers(D);
5518
5519  if (D.getDeclSpec().isThreadSpecified())
5520    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5521
5522  NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
5523                                         ForRedeclaration);
5524
5525  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5526    // Maybe we will complain about the shadowed template parameter.
5527    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5528    // Just pretend that we didn't see the previous declaration.
5529    PrevDecl = 0;
5530  }
5531
5532  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5533    PrevDecl = 0;
5534
5535  bool Mutable
5536    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5537  SourceLocation TSSL = D.getSourceRange().getBegin();
5538  FieldDecl *NewFD
5539    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5540                     AS, PrevDecl, &D);
5541
5542  if (NewFD->isInvalidDecl())
5543    Record->setInvalidDecl();
5544
5545  if (NewFD->isInvalidDecl() && PrevDecl) {
5546    // Don't introduce NewFD into scope; there's already something
5547    // with the same name in the same scope.
5548  } else if (II) {
5549    PushOnScopeChains(NewFD, S);
5550  } else
5551    Record->addDecl(NewFD);
5552
5553  return NewFD;
5554}
5555
5556/// \brief Build a new FieldDecl and check its well-formedness.
5557///
5558/// This routine builds a new FieldDecl given the fields name, type,
5559/// record, etc. \p PrevDecl should refer to any previous declaration
5560/// with the same name and in the same scope as the field to be
5561/// created.
5562///
5563/// \returns a new FieldDecl.
5564///
5565/// \todo The Declarator argument is a hack. It will be removed once
5566FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5567                                TypeSourceInfo *TInfo,
5568                                RecordDecl *Record, SourceLocation Loc,
5569                                bool Mutable, Expr *BitWidth,
5570                                SourceLocation TSSL,
5571                                AccessSpecifier AS, NamedDecl *PrevDecl,
5572                                Declarator *D) {
5573  IdentifierInfo *II = Name.getAsIdentifierInfo();
5574  bool InvalidDecl = false;
5575  if (D) InvalidDecl = D->isInvalidType();
5576
5577  // If we receive a broken type, recover by assuming 'int' and
5578  // marking this declaration as invalid.
5579  if (T.isNull()) {
5580    InvalidDecl = true;
5581    T = Context.IntTy;
5582  }
5583
5584  QualType EltTy = Context.getBaseElementType(T);
5585  if (!EltTy->isDependentType() &&
5586      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5587    InvalidDecl = true;
5588
5589  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5590  // than a variably modified type.
5591  if (!InvalidDecl && T->isVariablyModifiedType()) {
5592    bool SizeIsNegative;
5593    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5594                                                           SizeIsNegative);
5595    if (!FixedTy.isNull()) {
5596      Diag(Loc, diag::warn_illegal_constant_array_size);
5597      T = FixedTy;
5598    } else {
5599      if (SizeIsNegative)
5600        Diag(Loc, diag::err_typecheck_negative_array_size);
5601      else
5602        Diag(Loc, diag::err_typecheck_field_variable_size);
5603      InvalidDecl = true;
5604    }
5605  }
5606
5607  // Fields can not have abstract class types
5608  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5609                                             diag::err_abstract_type_in_decl,
5610                                             AbstractFieldType))
5611    InvalidDecl = true;
5612
5613  bool ZeroWidth = false;
5614  // If this is declared as a bit-field, check the bit-field.
5615  if (!InvalidDecl && BitWidth &&
5616      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5617    InvalidDecl = true;
5618    DeleteExpr(BitWidth);
5619    BitWidth = 0;
5620    ZeroWidth = false;
5621  }
5622
5623  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5624                                       BitWidth, Mutable);
5625  if (InvalidDecl)
5626    NewFD->setInvalidDecl();
5627
5628  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5629    Diag(Loc, diag::err_duplicate_member) << II;
5630    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5631    NewFD->setInvalidDecl();
5632  }
5633
5634  if (!InvalidDecl && getLangOptions().CPlusPlus) {
5635    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5636
5637    if (!T->isPODType())
5638      CXXRecord->setPOD(false);
5639    if (!ZeroWidth)
5640      CXXRecord->setEmpty(false);
5641
5642    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5643      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5644
5645      if (!RDecl->hasTrivialConstructor())
5646        CXXRecord->setHasTrivialConstructor(false);
5647      if (!RDecl->hasTrivialCopyConstructor())
5648        CXXRecord->setHasTrivialCopyConstructor(false);
5649      if (!RDecl->hasTrivialCopyAssignment())
5650        CXXRecord->setHasTrivialCopyAssignment(false);
5651      if (!RDecl->hasTrivialDestructor())
5652        CXXRecord->setHasTrivialDestructor(false);
5653
5654      // C++ 9.5p1: An object of a class with a non-trivial
5655      // constructor, a non-trivial copy constructor, a non-trivial
5656      // destructor, or a non-trivial copy assignment operator
5657      // cannot be a member of a union, nor can an array of such
5658      // objects.
5659      // TODO: C++0x alters this restriction significantly.
5660      if (Record->isUnion()) {
5661        // We check for copy constructors before constructors
5662        // because otherwise we'll never get complaints about
5663        // copy constructors.
5664
5665        CXXSpecialMember member = CXXInvalid;
5666        if (!RDecl->hasTrivialCopyConstructor())
5667          member = CXXCopyConstructor;
5668        else if (!RDecl->hasTrivialConstructor())
5669          member = CXXConstructor;
5670        else if (!RDecl->hasTrivialCopyAssignment())
5671          member = CXXCopyAssignment;
5672        else if (!RDecl->hasTrivialDestructor())
5673          member = CXXDestructor;
5674
5675        if (member != CXXInvalid) {
5676          Diag(Loc, diag::err_illegal_union_member) << Name << member;
5677          DiagnoseNontrivial(RT, member);
5678          NewFD->setInvalidDecl();
5679        }
5680      }
5681    }
5682  }
5683
5684  // FIXME: We need to pass in the attributes given an AST
5685  // representation, not a parser representation.
5686  if (D)
5687    // FIXME: What to pass instead of TUScope?
5688    ProcessDeclAttributes(TUScope, NewFD, *D);
5689
5690  if (T.isObjCGCWeak())
5691    Diag(Loc, diag::warn_attribute_weak_on_field);
5692
5693  NewFD->setAccess(AS);
5694
5695  // C++ [dcl.init.aggr]p1:
5696  //   An aggregate is an array or a class (clause 9) with [...] no
5697  //   private or protected non-static data members (clause 11).
5698  // A POD must be an aggregate.
5699  if (getLangOptions().CPlusPlus &&
5700      (AS == AS_private || AS == AS_protected)) {
5701    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5702    CXXRecord->setAggregate(false);
5703    CXXRecord->setPOD(false);
5704  }
5705
5706  return NewFD;
5707}
5708
5709/// DiagnoseNontrivial - Given that a class has a non-trivial
5710/// special member, figure out why.
5711void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5712  QualType QT(T, 0U);
5713  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5714
5715  // Check whether the member was user-declared.
5716  switch (member) {
5717  case CXXInvalid:
5718    break;
5719
5720  case CXXConstructor:
5721    if (RD->hasUserDeclaredConstructor()) {
5722      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5723      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5724        const FunctionDecl *body = 0;
5725        ci->getBody(body);
5726        if (!body || !cast<CXXConstructorDecl>(body)->isImplicitlyDefined()) {
5727          SourceLocation CtorLoc = ci->getLocation();
5728          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5729          return;
5730        }
5731      }
5732
5733      assert(0 && "found no user-declared constructors");
5734      return;
5735    }
5736    break;
5737
5738  case CXXCopyConstructor:
5739    if (RD->hasUserDeclaredCopyConstructor()) {
5740      SourceLocation CtorLoc =
5741        RD->getCopyConstructor(Context, 0)->getLocation();
5742      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5743      return;
5744    }
5745    break;
5746
5747  case CXXCopyAssignment:
5748    if (RD->hasUserDeclaredCopyAssignment()) {
5749      // FIXME: this should use the location of the copy
5750      // assignment, not the type.
5751      SourceLocation TyLoc = RD->getSourceRange().getBegin();
5752      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5753      return;
5754    }
5755    break;
5756
5757  case CXXDestructor:
5758    if (RD->hasUserDeclaredDestructor()) {
5759      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5760      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5761      return;
5762    }
5763    break;
5764  }
5765
5766  typedef CXXRecordDecl::base_class_iterator base_iter;
5767
5768  // Virtual bases and members inhibit trivial copying/construction,
5769  // but not trivial destruction.
5770  if (member != CXXDestructor) {
5771    // Check for virtual bases.  vbases includes indirect virtual bases,
5772    // so we just iterate through the direct bases.
5773    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5774      if (bi->isVirtual()) {
5775        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5776        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5777        return;
5778      }
5779
5780    // Check for virtual methods.
5781    typedef CXXRecordDecl::method_iterator meth_iter;
5782    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5783         ++mi) {
5784      if (mi->isVirtual()) {
5785        SourceLocation MLoc = mi->getSourceRange().getBegin();
5786        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5787        return;
5788      }
5789    }
5790  }
5791
5792  bool (CXXRecordDecl::*hasTrivial)() const;
5793  switch (member) {
5794  case CXXConstructor:
5795    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5796  case CXXCopyConstructor:
5797    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5798  case CXXCopyAssignment:
5799    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5800  case CXXDestructor:
5801    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5802  default:
5803    assert(0 && "unexpected special member"); return;
5804  }
5805
5806  // Check for nontrivial bases (and recurse).
5807  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5808    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5809    assert(BaseRT && "Don't know how to handle dependent bases");
5810    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5811    if (!(BaseRecTy->*hasTrivial)()) {
5812      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5813      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5814      DiagnoseNontrivial(BaseRT, member);
5815      return;
5816    }
5817  }
5818
5819  // Check for nontrivial members (and recurse).
5820  typedef RecordDecl::field_iterator field_iter;
5821  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5822       ++fi) {
5823    QualType EltTy = Context.getBaseElementType((*fi)->getType());
5824    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5825      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5826
5827      if (!(EltRD->*hasTrivial)()) {
5828        SourceLocation FLoc = (*fi)->getLocation();
5829        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5830        DiagnoseNontrivial(EltRT, member);
5831        return;
5832      }
5833    }
5834  }
5835
5836  assert(0 && "found no explanation for non-trivial member");
5837}
5838
5839/// TranslateIvarVisibility - Translate visibility from a token ID to an
5840///  AST enum value.
5841static ObjCIvarDecl::AccessControl
5842TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5843  switch (ivarVisibility) {
5844  default: assert(0 && "Unknown visitibility kind");
5845  case tok::objc_private: return ObjCIvarDecl::Private;
5846  case tok::objc_public: return ObjCIvarDecl::Public;
5847  case tok::objc_protected: return ObjCIvarDecl::Protected;
5848  case tok::objc_package: return ObjCIvarDecl::Package;
5849  }
5850}
5851
5852/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5853/// in order to create an IvarDecl object for it.
5854Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5855                                SourceLocation DeclStart,
5856                                DeclPtrTy IntfDecl,
5857                                Declarator &D, ExprTy *BitfieldWidth,
5858                                tok::ObjCKeywordKind Visibility) {
5859
5860  IdentifierInfo *II = D.getIdentifier();
5861  Expr *BitWidth = (Expr*)BitfieldWidth;
5862  SourceLocation Loc = DeclStart;
5863  if (II) Loc = D.getIdentifierLoc();
5864
5865  // FIXME: Unnamed fields can be handled in various different ways, for
5866  // example, unnamed unions inject all members into the struct namespace!
5867
5868  TypeSourceInfo *TInfo = 0;
5869  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5870
5871  if (BitWidth) {
5872    // 6.7.2.1p3, 6.7.2.1p4
5873    if (VerifyBitField(Loc, II, T, BitWidth)) {
5874      D.setInvalidType();
5875      DeleteExpr(BitWidth);
5876      BitWidth = 0;
5877    }
5878  } else {
5879    // Not a bitfield.
5880
5881    // validate II.
5882
5883  }
5884  if (T->isReferenceType()) {
5885    Diag(Loc, diag::err_ivar_reference_type);
5886    D.setInvalidType();
5887  }
5888  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5889  // than a variably modified type.
5890  else if (T->isVariablyModifiedType()) {
5891    Diag(Loc, diag::err_typecheck_ivar_variable_size);
5892    D.setInvalidType();
5893  }
5894
5895  // Get the visibility (access control) for this ivar.
5896  ObjCIvarDecl::AccessControl ac =
5897    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5898                                        : ObjCIvarDecl::None;
5899  // Must set ivar's DeclContext to its enclosing interface.
5900  ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>();
5901  ObjCContainerDecl *EnclosingContext;
5902  if (ObjCImplementationDecl *IMPDecl =
5903      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5904    // Case of ivar declared in an implementation. Context is that of its class.
5905    EnclosingContext = IMPDecl->getClassInterface();
5906    assert(EnclosingContext && "Implementation has no class interface!");
5907  } else {
5908    if (ObjCCategoryDecl *CDecl =
5909        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
5910      if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
5911        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
5912        return DeclPtrTy();
5913      }
5914    }
5915    EnclosingContext = EnclosingDecl;
5916  }
5917
5918  // Construct the decl.
5919  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5920                                             EnclosingContext, Loc, II, T,
5921                                             TInfo, ac, (Expr *)BitfieldWidth);
5922
5923  if (II) {
5924    NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
5925                                           ForRedeclaration);
5926    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5927        && !isa<TagDecl>(PrevDecl)) {
5928      Diag(Loc, diag::err_duplicate_member) << II;
5929      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5930      NewID->setInvalidDecl();
5931    }
5932  }
5933
5934  // Process attributes attached to the ivar.
5935  ProcessDeclAttributes(S, NewID, D);
5936
5937  if (D.isInvalidType())
5938    NewID->setInvalidDecl();
5939
5940  if (II) {
5941    // FIXME: When interfaces are DeclContexts, we'll need to add
5942    // these to the interface.
5943    S->AddDecl(DeclPtrTy::make(NewID));
5944    IdResolver.AddDecl(NewID);
5945  }
5946
5947  return DeclPtrTy::make(NewID);
5948}
5949
5950void Sema::ActOnFields(Scope* S,
5951                       SourceLocation RecLoc, DeclPtrTy RecDecl,
5952                       DeclPtrTy *Fields, unsigned NumFields,
5953                       SourceLocation LBrac, SourceLocation RBrac,
5954                       AttributeList *Attr) {
5955  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5956  assert(EnclosingDecl && "missing record or interface decl");
5957
5958  // If the decl this is being inserted into is invalid, then it may be a
5959  // redeclaration or some other bogus case.  Don't try to add fields to it.
5960  if (EnclosingDecl->isInvalidDecl()) {
5961    // FIXME: Deallocate fields?
5962    return;
5963  }
5964
5965
5966  // Verify that all the fields are okay.
5967  unsigned NumNamedMembers = 0;
5968  llvm::SmallVector<FieldDecl*, 32> RecFields;
5969
5970  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5971  for (unsigned i = 0; i != NumFields; ++i) {
5972    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5973
5974    // Get the type for the field.
5975    Type *FDTy = FD->getType().getTypePtr();
5976
5977    if (!FD->isAnonymousStructOrUnion()) {
5978      // Remember all fields written by the user.
5979      RecFields.push_back(FD);
5980    }
5981
5982    // If the field is already invalid for some reason, don't emit more
5983    // diagnostics about it.
5984    if (FD->isInvalidDecl()) {
5985      EnclosingDecl->setInvalidDecl();
5986      continue;
5987    }
5988
5989    // C99 6.7.2.1p2:
5990    //   A structure or union shall not contain a member with
5991    //   incomplete or function type (hence, a structure shall not
5992    //   contain an instance of itself, but may contain a pointer to
5993    //   an instance of itself), except that the last member of a
5994    //   structure with more than one named member may have incomplete
5995    //   array type; such a structure (and any union containing,
5996    //   possibly recursively, a member that is such a structure)
5997    //   shall not be a member of a structure or an element of an
5998    //   array.
5999    if (FDTy->isFunctionType()) {
6000      // Field declared as a function.
6001      Diag(FD->getLocation(), diag::err_field_declared_as_function)
6002        << FD->getDeclName();
6003      FD->setInvalidDecl();
6004      EnclosingDecl->setInvalidDecl();
6005      continue;
6006    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
6007               Record && Record->isStruct()) {
6008      // Flexible array member.
6009      if (NumNamedMembers < 1) {
6010        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
6011          << FD->getDeclName();
6012        FD->setInvalidDecl();
6013        EnclosingDecl->setInvalidDecl();
6014        continue;
6015      }
6016      // Okay, we have a legal flexible array member at the end of the struct.
6017      if (Record)
6018        Record->setHasFlexibleArrayMember(true);
6019    } else if (!FDTy->isDependentType() &&
6020               RequireCompleteType(FD->getLocation(), FD->getType(),
6021                                   diag::err_field_incomplete)) {
6022      // Incomplete type
6023      FD->setInvalidDecl();
6024      EnclosingDecl->setInvalidDecl();
6025      continue;
6026    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
6027      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
6028        // If this is a member of a union, then entire union becomes "flexible".
6029        if (Record && Record->isUnion()) {
6030          Record->setHasFlexibleArrayMember(true);
6031        } else {
6032          // If this is a struct/class and this is not the last element, reject
6033          // it.  Note that GCC supports variable sized arrays in the middle of
6034          // structures.
6035          if (i != NumFields-1)
6036            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
6037              << FD->getDeclName() << FD->getType();
6038          else {
6039            // We support flexible arrays at the end of structs in
6040            // other structs as an extension.
6041            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
6042              << FD->getDeclName();
6043            if (Record)
6044              Record->setHasFlexibleArrayMember(true);
6045          }
6046        }
6047      }
6048      if (Record && FDTTy->getDecl()->hasObjectMember())
6049        Record->setHasObjectMember(true);
6050    } else if (FDTy->isObjCInterfaceType()) {
6051      /// A field cannot be an Objective-c object
6052      Diag(FD->getLocation(), diag::err_statically_allocated_object);
6053      FD->setInvalidDecl();
6054      EnclosingDecl->setInvalidDecl();
6055      continue;
6056    } else if (getLangOptions().ObjC1 &&
6057               getLangOptions().getGCMode() != LangOptions::NonGC &&
6058               Record &&
6059               (FD->getType()->isObjCObjectPointerType() ||
6060                FD->getType().isObjCGCStrong()))
6061      Record->setHasObjectMember(true);
6062    // Keep track of the number of named members.
6063    if (FD->getIdentifier())
6064      ++NumNamedMembers;
6065  }
6066
6067  // Okay, we successfully defined 'Record'.
6068  if (Record) {
6069    Record->completeDefinition();
6070  } else {
6071    ObjCIvarDecl **ClsFields =
6072      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
6073    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
6074      ID->setLocEnd(RBrac);
6075      // Add ivar's to class's DeclContext.
6076      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6077        ClsFields[i]->setLexicalDeclContext(ID);
6078        ID->addDecl(ClsFields[i]);
6079      }
6080      // Must enforce the rule that ivars in the base classes may not be
6081      // duplicates.
6082      if (ID->getSuperClass())
6083        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
6084    } else if (ObjCImplementationDecl *IMPDecl =
6085                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
6086      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
6087      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
6088        // Ivar declared in @implementation never belongs to the implementation.
6089        // Only it is in implementation's lexical context.
6090        ClsFields[I]->setLexicalDeclContext(IMPDecl);
6091      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
6092    } else if (ObjCCategoryDecl *CDecl =
6093                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
6094      // case of ivars in class extension; all other cases have been
6095      // reported as errors elsewhere.
6096      // FIXME. Class extension does not have a LocEnd field.
6097      // CDecl->setLocEnd(RBrac);
6098      // Add ivar's to class extension's DeclContext.
6099      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
6100        ClsFields[i]->setLexicalDeclContext(CDecl);
6101        CDecl->addDecl(ClsFields[i]);
6102      }
6103    }
6104  }
6105
6106  if (Attr)
6107    ProcessDeclAttributeList(S, Record, Attr);
6108}
6109
6110/// \brief Determine whether the given integral value is representable within
6111/// the given type T.
6112static bool isRepresentableIntegerValue(ASTContext &Context,
6113                                        llvm::APSInt &Value,
6114                                        QualType T) {
6115  assert(T->isIntegralType() && "Integral type required!");
6116  unsigned BitWidth = Context.getIntWidth(T);
6117
6118  if (Value.isUnsigned() || Value.isNonNegative())
6119    return Value.getActiveBits() < BitWidth;
6120
6121  return Value.getMinSignedBits() <= BitWidth;
6122}
6123
6124// \brief Given an integral type, return the next larger integral type
6125// (or a NULL type of no such type exists).
6126static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
6127  // FIXME: Int128/UInt128 support, which also needs to be introduced into
6128  // enum checking below.
6129  assert(T->isIntegralType() && "Integral type required!");
6130  const unsigned NumTypes = 4;
6131  QualType SignedIntegralTypes[NumTypes] = {
6132    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
6133  };
6134  QualType UnsignedIntegralTypes[NumTypes] = {
6135    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
6136    Context.UnsignedLongLongTy
6137  };
6138
6139  unsigned BitWidth = Context.getTypeSize(T);
6140  QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
6141                                            : UnsignedIntegralTypes;
6142  for (unsigned I = 0; I != NumTypes; ++I)
6143    if (Context.getTypeSize(Types[I]) > BitWidth)
6144      return Types[I];
6145
6146  return QualType();
6147}
6148
6149EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
6150                                          EnumConstantDecl *LastEnumConst,
6151                                          SourceLocation IdLoc,
6152                                          IdentifierInfo *Id,
6153                                          ExprArg val) {
6154  Expr *Val = (Expr *)val.get();
6155
6156  unsigned IntWidth = Context.Target.getIntWidth();
6157  llvm::APSInt EnumVal(IntWidth);
6158  QualType EltTy;
6159  if (Val) {
6160    if (Enum->isDependentType() || Val->isTypeDependent())
6161      EltTy = Context.DependentTy;
6162    else {
6163      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
6164      SourceLocation ExpLoc;
6165      if (!Val->isValueDependent() &&
6166          VerifyIntegerConstantExpression(Val, &EnumVal)) {
6167        Val = 0;
6168      } else {
6169        if (!getLangOptions().CPlusPlus) {
6170          // C99 6.7.2.2p2:
6171          //   The expression that defines the value of an enumeration constant
6172          //   shall be an integer constant expression that has a value
6173          //   representable as an int.
6174
6175          // Complain if the value is not representable in an int.
6176          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
6177            Diag(IdLoc, diag::ext_enum_value_not_int)
6178              << EnumVal.toString(10) << Val->getSourceRange()
6179              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
6180          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
6181            // Force the type of the expression to 'int'.
6182            ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
6183
6184            if (Val != val.get()) {
6185              val.release();
6186              val = Val;
6187            }
6188          }
6189        }
6190
6191        // C++0x [dcl.enum]p5:
6192        //   If the underlying type is not fixed, the type of each enumerator
6193        //   is the type of its initializing value:
6194        //     - If an initializer is specified for an enumerator, the
6195        //       initializing value has the same type as the expression.
6196        EltTy = Val->getType();
6197      }
6198    }
6199  }
6200
6201  if (!Val) {
6202    if (Enum->isDependentType())
6203      EltTy = Context.DependentTy;
6204    else if (!LastEnumConst) {
6205      // C++0x [dcl.enum]p5:
6206      //   If the underlying type is not fixed, the type of each enumerator
6207      //   is the type of its initializing value:
6208      //     - If no initializer is specified for the first enumerator, the
6209      //       initializing value has an unspecified integral type.
6210      //
6211      // GCC uses 'int' for its unspecified integral type, as does
6212      // C99 6.7.2.2p3.
6213      EltTy = Context.IntTy;
6214    } else {
6215      // Assign the last value + 1.
6216      EnumVal = LastEnumConst->getInitVal();
6217      ++EnumVal;
6218      EltTy = LastEnumConst->getType();
6219
6220      // Check for overflow on increment.
6221      if (EnumVal < LastEnumConst->getInitVal()) {
6222        // C++0x [dcl.enum]p5:
6223        //   If the underlying type is not fixed, the type of each enumerator
6224        //   is the type of its initializing value:
6225        //
6226        //     - Otherwise the type of the initializing value is the same as
6227        //       the type of the initializing value of the preceding enumerator
6228        //       unless the incremented value is not representable in that type,
6229        //       in which case the type is an unspecified integral type
6230        //       sufficient to contain the incremented value. If no such type
6231        //       exists, the program is ill-formed.
6232        QualType T = getNextLargerIntegralType(Context, EltTy);
6233        if (T.isNull()) {
6234          // There is no integral type larger enough to represent this
6235          // value. Complain, then allow the value to wrap around.
6236          EnumVal = LastEnumConst->getInitVal();
6237          EnumVal.zext(EnumVal.getBitWidth() * 2);
6238          Diag(IdLoc, diag::warn_enumerator_too_large)
6239            << EnumVal.toString(10);
6240        } else {
6241          EltTy = T;
6242        }
6243
6244        // Retrieve the last enumerator's value, extent that type to the
6245        // type that is supposed to be large enough to represent the incremented
6246        // value, then increment.
6247        EnumVal = LastEnumConst->getInitVal();
6248        EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6249        EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
6250        ++EnumVal;
6251
6252        // If we're not in C++, diagnose the overflow of enumerator values,
6253        // which in C99 means that the enumerator value is not representable in
6254        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
6255        // permits enumerator values that are representable in some larger
6256        // integral type.
6257        if (!getLangOptions().CPlusPlus && !T.isNull())
6258          Diag(IdLoc, diag::warn_enum_value_overflow);
6259      } else if (!getLangOptions().CPlusPlus &&
6260                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
6261        // Enforce C99 6.7.2.2p2 even when we compute the next value.
6262        Diag(IdLoc, diag::ext_enum_value_not_int)
6263          << EnumVal.toString(10) << 1;
6264      }
6265    }
6266  }
6267
6268  if (!EltTy->isDependentType()) {
6269    // Make the enumerator value match the signedness and size of the
6270    // enumerator's type.
6271    EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
6272    EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6273  }
6274
6275  val.release();
6276  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
6277                                  Val, EnumVal);
6278}
6279
6280
6281Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
6282                                        DeclPtrTy lastEnumConst,
6283                                        SourceLocation IdLoc,
6284                                        IdentifierInfo *Id,
6285                                        SourceLocation EqualLoc, ExprTy *val) {
6286  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
6287  EnumConstantDecl *LastEnumConst =
6288    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
6289  Expr *Val = static_cast<Expr*>(val);
6290
6291  // The scope passed in may not be a decl scope.  Zip up the scope tree until
6292  // we find one that is.
6293  S = getNonFieldDeclScope(S);
6294
6295  // Verify that there isn't already something declared with this name in this
6296  // scope.
6297  NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
6298                                         ForRedeclaration);
6299  if (PrevDecl && PrevDecl->isTemplateParameter()) {
6300    // Maybe we will complain about the shadowed template parameter.
6301    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
6302    // Just pretend that we didn't see the previous declaration.
6303    PrevDecl = 0;
6304  }
6305
6306  if (PrevDecl) {
6307    // When in C++, we may get a TagDecl with the same name; in this case the
6308    // enum constant will 'hide' the tag.
6309    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
6310           "Received TagDecl when not in C++!");
6311    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
6312      if (isa<EnumConstantDecl>(PrevDecl))
6313        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
6314      else
6315        Diag(IdLoc, diag::err_redefinition) << Id;
6316      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6317      if (Val) Val->Destroy(Context);
6318      return DeclPtrTy();
6319    }
6320  }
6321
6322  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
6323                                            IdLoc, Id, Owned(Val));
6324
6325  // Register this decl in the current scope stack.
6326  if (New) {
6327    New->setAccess(TheEnumDecl->getAccess());
6328    PushOnScopeChains(New, S);
6329  }
6330
6331  return DeclPtrTy::make(New);
6332}
6333
6334void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
6335                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
6336                         DeclPtrTy *Elements, unsigned NumElements,
6337                         Scope *S, AttributeList *Attr) {
6338  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
6339  QualType EnumType = Context.getTypeDeclType(Enum);
6340
6341  if (Attr)
6342    ProcessDeclAttributeList(S, Enum, Attr);
6343
6344  if (Enum->isDependentType()) {
6345    for (unsigned i = 0; i != NumElements; ++i) {
6346      EnumConstantDecl *ECD =
6347        cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6348      if (!ECD) continue;
6349
6350      ECD->setType(EnumType);
6351    }
6352
6353    Enum->completeDefinition(Context.DependentTy, Context.DependentTy);
6354    return;
6355  }
6356
6357  // TODO: If the result value doesn't fit in an int, it must be a long or long
6358  // long value.  ISO C does not support this, but GCC does as an extension,
6359  // emit a warning.
6360  unsigned IntWidth = Context.Target.getIntWidth();
6361  unsigned CharWidth = Context.Target.getCharWidth();
6362  unsigned ShortWidth = Context.Target.getShortWidth();
6363
6364  // Verify that all the values are okay, compute the size of the values, and
6365  // reverse the list.
6366  unsigned NumNegativeBits = 0;
6367  unsigned NumPositiveBits = 0;
6368
6369  // Keep track of whether all elements have type int.
6370  bool AllElementsInt = true;
6371
6372  for (unsigned i = 0; i != NumElements; ++i) {
6373    EnumConstantDecl *ECD =
6374      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6375    if (!ECD) continue;  // Already issued a diagnostic.
6376
6377    const llvm::APSInt &InitVal = ECD->getInitVal();
6378
6379    // Keep track of the size of positive and negative values.
6380    if (InitVal.isUnsigned() || InitVal.isNonNegative())
6381      NumPositiveBits = std::max(NumPositiveBits,
6382                                 (unsigned)InitVal.getActiveBits());
6383    else
6384      NumNegativeBits = std::max(NumNegativeBits,
6385                                 (unsigned)InitVal.getMinSignedBits());
6386
6387    // Keep track of whether every enum element has type int (very commmon).
6388    if (AllElementsInt)
6389      AllElementsInt = ECD->getType() == Context.IntTy;
6390  }
6391
6392  // Figure out the type that should be used for this enum.
6393  // FIXME: Support -fshort-enums.
6394  QualType BestType;
6395  unsigned BestWidth;
6396
6397  // C++0x N3000 [conv.prom]p3:
6398  //   An rvalue of an unscoped enumeration type whose underlying
6399  //   type is not fixed can be converted to an rvalue of the first
6400  //   of the following types that can represent all the values of
6401  //   the enumeration: int, unsigned int, long int, unsigned long
6402  //   int, long long int, or unsigned long long int.
6403  // C99 6.4.4.3p2:
6404  //   An identifier declared as an enumeration constant has type int.
6405  // The C99 rule is modified by a gcc extension
6406  QualType BestPromotionType;
6407
6408  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
6409
6410  if (NumNegativeBits) {
6411    // If there is a negative value, figure out the smallest integer type (of
6412    // int/long/longlong) that fits.
6413    // If it's packed, check also if it fits a char or a short.
6414    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
6415      BestType = Context.SignedCharTy;
6416      BestWidth = CharWidth;
6417    } else if (Packed && NumNegativeBits <= ShortWidth &&
6418               NumPositiveBits < ShortWidth) {
6419      BestType = Context.ShortTy;
6420      BestWidth = ShortWidth;
6421    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
6422      BestType = Context.IntTy;
6423      BestWidth = IntWidth;
6424    } else {
6425      BestWidth = Context.Target.getLongWidth();
6426
6427      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
6428        BestType = Context.LongTy;
6429      } else {
6430        BestWidth = Context.Target.getLongLongWidth();
6431
6432        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
6433          Diag(Enum->getLocation(), diag::warn_enum_too_large);
6434        BestType = Context.LongLongTy;
6435      }
6436    }
6437    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
6438  } else {
6439    // If there is no negative value, figure out the smallest type that fits
6440    // all of the enumerator values.
6441    // If it's packed, check also if it fits a char or a short.
6442    if (Packed && NumPositiveBits <= CharWidth) {
6443      BestType = Context.UnsignedCharTy;
6444      BestPromotionType = Context.IntTy;
6445      BestWidth = CharWidth;
6446    } else if (Packed && NumPositiveBits <= ShortWidth) {
6447      BestType = Context.UnsignedShortTy;
6448      BestPromotionType = Context.IntTy;
6449      BestWidth = ShortWidth;
6450    } else if (NumPositiveBits <= IntWidth) {
6451      BestType = Context.UnsignedIntTy;
6452      BestWidth = IntWidth;
6453      BestPromotionType
6454        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6455                           ? Context.UnsignedIntTy : Context.IntTy;
6456    } else if (NumPositiveBits <=
6457               (BestWidth = Context.Target.getLongWidth())) {
6458      BestType = Context.UnsignedLongTy;
6459      BestPromotionType
6460        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6461                           ? Context.UnsignedLongTy : Context.LongTy;
6462    } else {
6463      BestWidth = Context.Target.getLongLongWidth();
6464      assert(NumPositiveBits <= BestWidth &&
6465             "How could an initializer get larger than ULL?");
6466      BestType = Context.UnsignedLongLongTy;
6467      BestPromotionType
6468        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6469                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
6470    }
6471  }
6472
6473  // Loop over all of the enumerator constants, changing their types to match
6474  // the type of the enum if needed.
6475  for (unsigned i = 0; i != NumElements; ++i) {
6476    EnumConstantDecl *ECD =
6477      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6478    if (!ECD) continue;  // Already issued a diagnostic.
6479
6480    // Standard C says the enumerators have int type, but we allow, as an
6481    // extension, the enumerators to be larger than int size.  If each
6482    // enumerator value fits in an int, type it as an int, otherwise type it the
6483    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
6484    // that X has type 'int', not 'unsigned'.
6485
6486    // Determine whether the value fits into an int.
6487    llvm::APSInt InitVal = ECD->getInitVal();
6488
6489    // If it fits into an integer type, force it.  Otherwise force it to match
6490    // the enum decl type.
6491    QualType NewTy;
6492    unsigned NewWidth;
6493    bool NewSign;
6494    if (!getLangOptions().CPlusPlus &&
6495        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
6496      NewTy = Context.IntTy;
6497      NewWidth = IntWidth;
6498      NewSign = true;
6499    } else if (ECD->getType() == BestType) {
6500      // Already the right type!
6501      if (getLangOptions().CPlusPlus)
6502        // C++ [dcl.enum]p4: Following the closing brace of an
6503        // enum-specifier, each enumerator has the type of its
6504        // enumeration.
6505        ECD->setType(EnumType);
6506      continue;
6507    } else {
6508      NewTy = BestType;
6509      NewWidth = BestWidth;
6510      NewSign = BestType->isSignedIntegerType();
6511    }
6512
6513    // Adjust the APSInt value.
6514    InitVal.extOrTrunc(NewWidth);
6515    InitVal.setIsSigned(NewSign);
6516    ECD->setInitVal(InitVal);
6517
6518    // Adjust the Expr initializer and type.
6519    if (ECD->getInitExpr())
6520      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
6521                                                      CastExpr::CK_IntegralCast,
6522                                                      ECD->getInitExpr(),
6523                                                      CXXBaseSpecifierArray(),
6524                                                      /*isLvalue=*/false));
6525    if (getLangOptions().CPlusPlus)
6526      // C++ [dcl.enum]p4: Following the closing brace of an
6527      // enum-specifier, each enumerator has the type of its
6528      // enumeration.
6529      ECD->setType(EnumType);
6530    else
6531      ECD->setType(NewTy);
6532  }
6533
6534  Enum->completeDefinition(BestType, BestPromotionType);
6535}
6536
6537Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6538                                            ExprArg expr) {
6539  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6540
6541  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6542                                                   Loc, AsmString);
6543  CurContext->addDecl(New);
6544  return DeclPtrTy::make(New);
6545}
6546
6547void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6548                             SourceLocation PragmaLoc,
6549                             SourceLocation NameLoc) {
6550  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
6551
6552  if (PrevDecl) {
6553    PrevDecl->addAttr(::new (Context) WeakAttr());
6554  } else {
6555    (void)WeakUndeclaredIdentifiers.insert(
6556      std::pair<IdentifierInfo*,WeakInfo>
6557        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6558  }
6559}
6560
6561void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6562                                IdentifierInfo* AliasName,
6563                                SourceLocation PragmaLoc,
6564                                SourceLocation NameLoc,
6565                                SourceLocation AliasNameLoc) {
6566  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
6567                                    LookupOrdinaryName);
6568  WeakInfo W = WeakInfo(Name, NameLoc);
6569
6570  if (PrevDecl) {
6571    if (!PrevDecl->hasAttr<AliasAttr>())
6572      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6573        DeclApplyPragmaWeak(TUScope, ND, W);
6574  } else {
6575    (void)WeakUndeclaredIdentifiers.insert(
6576      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
6577  }
6578}
6579