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