SemaDecl.cpp revision ba9d853bec0d9cc10ac5fdeab807cc4b13d65791
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  // Make sure this is set before checking the function declaration.
3193  // We'll override the visibility type later.
3194  if (isFriend) NewFD->setObjectOfFriendDecl(false);
3195
3196  // Perform semantic checking on the function declaration.
3197  bool OverloadableAttrRequired = false; // FIXME: HACK!
3198  CheckFunctionDeclaration(S, NewFD, Previous, isExplicitSpecialization,
3199                           Redeclaration, /*FIXME:*/OverloadableAttrRequired);
3200
3201  assert((NewFD->isInvalidDecl() || !Redeclaration ||
3202          Previous.getResultKind() != LookupResult::FoundOverloaded) &&
3203         "previous declaration set still overloaded");
3204
3205  if (isFriend && Redeclaration) {
3206    AccessSpecifier Access = AS_public;
3207    if (!NewFD->isInvalidDecl())
3208      Access = NewFD->getPreviousDeclaration()->getAccess();
3209
3210    if (FunctionTemplate) {
3211      FunctionTemplate->setObjectOfFriendDecl(true);
3212      FunctionTemplate->setAccess(Access);
3213    } else {
3214      NewFD->setObjectOfFriendDecl(true);
3215    }
3216    NewFD->setAccess(Access);
3217  }
3218
3219  // If we have a function template, check the template parameter
3220  // list. This will check and merge default template arguments.
3221  if (FunctionTemplate) {
3222    FunctionTemplateDecl *PrevTemplate = FunctionTemplate->getPreviousDeclaration();
3223    CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
3224                      PrevTemplate? PrevTemplate->getTemplateParameters() : 0,
3225             D.getDeclSpec().isFriendSpecified()? TPC_FriendFunctionTemplate
3226                                                : TPC_FunctionTemplate);
3227  }
3228
3229  if (D.getCXXScopeSpec().isSet() && !NewFD->isInvalidDecl()) {
3230    // Fake up an access specifier if it's supposed to be a class member.
3231    if (!Redeclaration && isa<CXXRecordDecl>(NewFD->getDeclContext()))
3232      NewFD->setAccess(AS_public);
3233
3234    // An out-of-line member function declaration must also be a
3235    // definition (C++ [dcl.meaning]p1).
3236    // Note that this is not the case for explicit specializations of
3237    // function templates or member functions of class templates, per
3238    // C++ [temp.expl.spec]p2.
3239    if (!IsFunctionDefinition && !isFriend &&
3240        !isFunctionTemplateSpecialization && !isExplicitSpecialization) {
3241      Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
3242        << D.getCXXScopeSpec().getRange();
3243      NewFD->setInvalidDecl();
3244    } else if (!Redeclaration &&
3245               !(isFriend && CurContext->isDependentContext())) {
3246      // The user tried to provide an out-of-line definition for a
3247      // function that is a member of a class or namespace, but there
3248      // was no such member function declared (C++ [class.mfct]p2,
3249      // C++ [namespace.memdef]p2). For example:
3250      //
3251      // class X {
3252      //   void f() const;
3253      // };
3254      //
3255      // void X::f() { } // ill-formed
3256      //
3257      // Complain about this problem, and attempt to suggest close
3258      // matches (e.g., those that differ only in cv-qualifiers and
3259      // whether the parameter types are references).
3260      Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
3261        << Name << DC << D.getCXXScopeSpec().getRange();
3262      NewFD->setInvalidDecl();
3263
3264      LookupResult Prev(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
3265                        ForRedeclaration);
3266      LookupQualifiedName(Prev, DC);
3267      assert(!Prev.isAmbiguous() &&
3268             "Cannot have an ambiguity in previous-declaration lookup");
3269      for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
3270           Func != FuncEnd; ++Func) {
3271        if (isa<FunctionDecl>(*Func) &&
3272            isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
3273          Diag((*Func)->getLocation(), diag::note_member_def_close_match);
3274      }
3275    }
3276  }
3277
3278  // Handle attributes. We need to have merged decls when handling attributes
3279  // (for example to check for conflicts, etc).
3280  // FIXME: This needs to happen before we merge declarations. Then,
3281  // let attribute merging cope with attribute conflicts.
3282  ProcessDeclAttributes(S, NewFD, D);
3283
3284  // attributes declared post-definition are currently ignored
3285  if (Redeclaration && Previous.isSingleResult()) {
3286    const FunctionDecl *Def;
3287    FunctionDecl *PrevFD = dyn_cast<FunctionDecl>(Previous.getFoundDecl());
3288    if (PrevFD && PrevFD->getBody(Def) && D.hasAttributes()) {
3289      Diag(NewFD->getLocation(), diag::warn_attribute_precede_definition);
3290      Diag(Def->getLocation(), diag::note_previous_definition);
3291    }
3292  }
3293
3294  AddKnownFunctionAttributes(NewFD);
3295
3296  if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
3297    // If a function name is overloadable in C, then every function
3298    // with that name must be marked "overloadable".
3299    Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
3300      << Redeclaration << NewFD;
3301    if (!Previous.empty())
3302      Diag(Previous.getRepresentativeDecl()->getLocation(),
3303           diag::note_attribute_overloadable_prev_overload);
3304    NewFD->addAttr(::new (Context) OverloadableAttr());
3305  }
3306
3307  // If this is a locally-scoped extern C function, update the
3308  // map of such names.
3309  if (CurContext->isFunctionOrMethod() && NewFD->isExternC()
3310      && !NewFD->isInvalidDecl())
3311    RegisterLocallyScopedExternCDecl(NewFD, Previous, S);
3312
3313  // Set this FunctionDecl's range up to the right paren.
3314  NewFD->setLocEnd(D.getSourceRange().getEnd());
3315
3316  if (FunctionTemplate && NewFD->isInvalidDecl())
3317    FunctionTemplate->setInvalidDecl();
3318
3319  if (FunctionTemplate)
3320    return FunctionTemplate;
3321
3322
3323  // Keep track of static, non-inlined function definitions that
3324  // have not been used. We will warn later.
3325  // FIXME: Also include static functions declared but not defined.
3326  if (!NewFD->isInvalidDecl() && IsFunctionDefinition
3327      && !NewFD->isInlined() && NewFD->getLinkage() == InternalLinkage
3328      && !NewFD->isUsed() && !NewFD->hasAttr<UnusedAttr>()
3329      && !NewFD->hasAttr<ConstructorAttr>()
3330      && !NewFD->hasAttr<DestructorAttr>())
3331    UnusedStaticFuncs.push_back(NewFD);
3332
3333  return NewFD;
3334}
3335
3336/// \brief Perform semantic checking of a new function declaration.
3337///
3338/// Performs semantic analysis of the new function declaration
3339/// NewFD. This routine performs all semantic checking that does not
3340/// require the actual declarator involved in the declaration, and is
3341/// used both for the declaration of functions as they are parsed
3342/// (called via ActOnDeclarator) and for the declaration of functions
3343/// that have been instantiated via C++ template instantiation (called
3344/// via InstantiateDecl).
3345///
3346/// \param IsExplicitSpecialiation whether this new function declaration is
3347/// an explicit specialization of the previous declaration.
3348///
3349/// This sets NewFD->isInvalidDecl() to true if there was an error.
3350void Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
3351                                    LookupResult &Previous,
3352                                    bool IsExplicitSpecialization,
3353                                    bool &Redeclaration,
3354                                    bool &OverloadableAttrRequired) {
3355  // If NewFD is already known erroneous, don't do any of this checking.
3356  if (NewFD->isInvalidDecl())
3357    return;
3358
3359  if (NewFD->getResultType()->isVariablyModifiedType()) {
3360    // Functions returning a variably modified type violate C99 6.7.5.2p2
3361    // because all functions have linkage.
3362    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
3363    return NewFD->setInvalidDecl();
3364  }
3365
3366  if (NewFD->isMain())
3367    CheckMain(NewFD);
3368
3369  // Check for a previous declaration of this name.
3370  if (Previous.empty() && NewFD->isExternC()) {
3371    // Since we did not find anything by this name and we're declaring
3372    // an extern "C" function, look for a non-visible extern "C"
3373    // declaration with the same name.
3374    llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
3375      = LocallyScopedExternalDecls.find(NewFD->getDeclName());
3376    if (Pos != LocallyScopedExternalDecls.end())
3377      Previous.addDecl(Pos->second);
3378  }
3379
3380  // Merge or overload the declaration with an existing declaration of
3381  // the same name, if appropriate.
3382  if (!Previous.empty()) {
3383    // Determine whether NewFD is an overload of PrevDecl or
3384    // a declaration that requires merging. If it's an overload,
3385    // there's no more work to do here; we'll just add the new
3386    // function to the scope.
3387
3388    NamedDecl *OldDecl = 0;
3389    if (!AllowOverloadingOfFunction(Previous, Context)) {
3390      Redeclaration = true;
3391      OldDecl = Previous.getFoundDecl();
3392    } else {
3393      if (!getLangOptions().CPlusPlus) {
3394        OverloadableAttrRequired = true;
3395
3396        // Functions marked "overloadable" must have a prototype (that
3397        // we can't get through declaration merging).
3398        if (!NewFD->getType()->getAs<FunctionProtoType>()) {
3399          Diag(NewFD->getLocation(),
3400               diag::err_attribute_overloadable_no_prototype)
3401            << NewFD;
3402          Redeclaration = true;
3403
3404          // Turn this into a variadic function with no parameters.
3405          QualType R = Context.getFunctionType(
3406                     NewFD->getType()->getAs<FunctionType>()->getResultType(),
3407                     0, 0, true, 0, false, false, 0, 0,
3408                     FunctionType::ExtInfo());
3409          NewFD->setType(R);
3410          return NewFD->setInvalidDecl();
3411        }
3412      }
3413
3414      switch (CheckOverload(NewFD, Previous, OldDecl)) {
3415      case Ovl_Match:
3416        Redeclaration = true;
3417        if (isa<UsingShadowDecl>(OldDecl) && CurContext->isRecord()) {
3418          HideUsingShadowDecl(S, cast<UsingShadowDecl>(OldDecl));
3419          Redeclaration = false;
3420        }
3421        break;
3422
3423      case Ovl_NonFunction:
3424        Redeclaration = true;
3425        break;
3426
3427      case Ovl_Overload:
3428        Redeclaration = false;
3429        break;
3430      }
3431    }
3432
3433    if (Redeclaration) {
3434      // NewFD and OldDecl represent declarations that need to be
3435      // merged.
3436      if (MergeFunctionDecl(NewFD, OldDecl))
3437        return NewFD->setInvalidDecl();
3438
3439      Previous.clear();
3440      Previous.addDecl(OldDecl);
3441
3442      if (FunctionTemplateDecl *OldTemplateDecl
3443                                    = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
3444        NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
3445        FunctionTemplateDecl *NewTemplateDecl
3446          = NewFD->getDescribedFunctionTemplate();
3447        assert(NewTemplateDecl && "Template/non-template mismatch");
3448        if (CXXMethodDecl *Method
3449              = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
3450          Method->setAccess(OldTemplateDecl->getAccess());
3451          NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
3452        }
3453
3454        // If this is an explicit specialization of a member that is a function
3455        // template, mark it as a member specialization.
3456        if (IsExplicitSpecialization &&
3457            NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
3458          NewTemplateDecl->setMemberSpecialization();
3459          assert(OldTemplateDecl->isMemberSpecialization());
3460        }
3461      } else {
3462        if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions
3463          NewFD->setAccess(OldDecl->getAccess());
3464        NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
3465      }
3466    }
3467  }
3468
3469  // Semantic checking for this function declaration (in isolation).
3470  if (getLangOptions().CPlusPlus) {
3471    // C++-specific checks.
3472    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
3473      CheckConstructor(Constructor);
3474    } else if (CXXDestructorDecl *Destructor =
3475                dyn_cast<CXXDestructorDecl>(NewFD)) {
3476      CXXRecordDecl *Record = Destructor->getParent();
3477      QualType ClassType = Context.getTypeDeclType(Record);
3478
3479      // FIXME: Shouldn't we be able to perform thisc heck even when the class
3480      // type is dependent? Both gcc and edg can handle that.
3481      if (!ClassType->isDependentType()) {
3482        DeclarationName Name
3483          = Context.DeclarationNames.getCXXDestructorName(
3484                                        Context.getCanonicalType(ClassType));
3485        if (NewFD->getDeclName() != Name) {
3486          Diag(NewFD->getLocation(), diag::err_destructor_name);
3487          return NewFD->setInvalidDecl();
3488        }
3489      }
3490
3491      Record->setUserDeclaredDestructor(true);
3492      // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
3493      // user-defined destructor.
3494      Record->setPOD(false);
3495
3496      // C++ [class.dtor]p3: A destructor is trivial if it is an implicitly-
3497      // declared destructor.
3498      // FIXME: C++0x: don't do this for "= default" destructors
3499      Record->setHasTrivialDestructor(false);
3500    } else if (CXXConversionDecl *Conversion
3501               = dyn_cast<CXXConversionDecl>(NewFD)) {
3502      ActOnConversionDeclarator(Conversion);
3503    }
3504
3505    // Find any virtual functions that this function overrides.
3506    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
3507      if (!Method->isFunctionTemplateSpecialization() &&
3508          !Method->getDescribedFunctionTemplate())
3509        AddOverriddenMethods(Method->getParent(), Method);
3510    }
3511
3512    // Additional checks for the destructor; make sure we do this after we
3513    // figure out whether the destructor is virtual.
3514    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
3515      if (!Destructor->getParent()->isDependentType())
3516        CheckDestructor(Destructor);
3517
3518    // Extra checking for C++ overloaded operators (C++ [over.oper]).
3519    if (NewFD->isOverloadedOperator() &&
3520        CheckOverloadedOperatorDeclaration(NewFD))
3521      return NewFD->setInvalidDecl();
3522
3523    // Extra checking for C++0x literal operators (C++0x [over.literal]).
3524    if (NewFD->getLiteralIdentifier() &&
3525        CheckLiteralOperatorDeclaration(NewFD))
3526      return NewFD->setInvalidDecl();
3527
3528    // In C++, check default arguments now that we have merged decls. Unless
3529    // the lexical context is the class, because in this case this is done
3530    // during delayed parsing anyway.
3531    if (!CurContext->isRecord())
3532      CheckCXXDefaultArguments(NewFD);
3533  }
3534}
3535
3536void Sema::CheckMain(FunctionDecl* FD) {
3537  // C++ [basic.start.main]p3:  A program that declares main to be inline
3538  //   or static is ill-formed.
3539  // C99 6.7.4p4:  In a hosted environment, the inline function specifier
3540  //   shall not appear in a declaration of main.
3541  // static main is not an error under C99, but we should warn about it.
3542  bool isInline = FD->isInlineSpecified();
3543  bool isStatic = FD->getStorageClass() == FunctionDecl::Static;
3544  if (isInline || isStatic) {
3545    unsigned diagID = diag::warn_unusual_main_decl;
3546    if (isInline || getLangOptions().CPlusPlus)
3547      diagID = diag::err_unusual_main_decl;
3548
3549    int which = isStatic + (isInline << 1) - 1;
3550    Diag(FD->getLocation(), diagID) << which;
3551  }
3552
3553  QualType T = FD->getType();
3554  assert(T->isFunctionType() && "function decl is not of function type");
3555  const FunctionType* FT = T->getAs<FunctionType>();
3556
3557  if (!Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) {
3558    // TODO: add a replacement fixit to turn the return type into 'int'.
3559    Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint);
3560    FD->setInvalidDecl(true);
3561  }
3562
3563  // Treat protoless main() as nullary.
3564  if (isa<FunctionNoProtoType>(FT)) return;
3565
3566  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
3567  unsigned nparams = FTP->getNumArgs();
3568  assert(FD->getNumParams() == nparams);
3569
3570  bool HasExtraParameters = (nparams > 3);
3571
3572  // Darwin passes an undocumented fourth argument of type char**.  If
3573  // other platforms start sprouting these, the logic below will start
3574  // getting shifty.
3575  if (nparams == 4 &&
3576      Context.Target.getTriple().getOS() == llvm::Triple::Darwin)
3577    HasExtraParameters = false;
3578
3579  if (HasExtraParameters) {
3580    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
3581    FD->setInvalidDecl(true);
3582    nparams = 3;
3583  }
3584
3585  // FIXME: a lot of the following diagnostics would be improved
3586  // if we had some location information about types.
3587
3588  QualType CharPP =
3589    Context.getPointerType(Context.getPointerType(Context.CharTy));
3590  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
3591
3592  for (unsigned i = 0; i < nparams; ++i) {
3593    QualType AT = FTP->getArgType(i);
3594
3595    bool mismatch = true;
3596
3597    if (Context.hasSameUnqualifiedType(AT, Expected[i]))
3598      mismatch = false;
3599    else if (Expected[i] == CharPP) {
3600      // As an extension, the following forms are okay:
3601      //   char const **
3602      //   char const * const *
3603      //   char * const *
3604
3605      QualifierCollector qs;
3606      const PointerType* PT;
3607      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
3608          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
3609          (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) {
3610        qs.removeConst();
3611        mismatch = !qs.empty();
3612      }
3613    }
3614
3615    if (mismatch) {
3616      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
3617      // TODO: suggest replacing given type with expected type
3618      FD->setInvalidDecl(true);
3619    }
3620  }
3621
3622  if (nparams == 1 && !FD->isInvalidDecl()) {
3623    Diag(FD->getLocation(), diag::warn_main_one_arg);
3624  }
3625}
3626
3627bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
3628  // FIXME: Need strict checking.  In C89, we need to check for
3629  // any assignment, increment, decrement, function-calls, or
3630  // commas outside of a sizeof.  In C99, it's the same list,
3631  // except that the aforementioned are allowed in unevaluated
3632  // expressions.  Everything else falls under the
3633  // "may accept other forms of constant expressions" exception.
3634  // (We never end up here for C++, so the constant expression
3635  // rules there don't matter.)
3636  if (Init->isConstantInitializer(Context))
3637    return false;
3638  Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
3639    << Init->getSourceRange();
3640  return true;
3641}
3642
3643void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init) {
3644  AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
3645}
3646
3647/// AddInitializerToDecl - Adds the initializer Init to the
3648/// declaration dcl. If DirectInit is true, this is C++ direct
3649/// initialization rather than copy initialization.
3650void Sema::AddInitializerToDecl(DeclPtrTy dcl, ExprArg init, bool DirectInit) {
3651  Decl *RealDecl = dcl.getAs<Decl>();
3652  // If there is no declaration, there was an error parsing it.  Just ignore
3653  // the initializer.
3654  if (RealDecl == 0)
3655    return;
3656
3657  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
3658    // With declarators parsed the way they are, the parser cannot
3659    // distinguish between a normal initializer and a pure-specifier.
3660    // Thus this grotesque test.
3661    IntegerLiteral *IL;
3662    Expr *Init = static_cast<Expr *>(init.get());
3663    if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
3664        Context.getCanonicalType(IL->getType()) == Context.IntTy)
3665      CheckPureMethod(Method, Init->getSourceRange());
3666    else {
3667      Diag(Method->getLocation(), diag::err_member_function_initialization)
3668        << Method->getDeclName() << Init->getSourceRange();
3669      Method->setInvalidDecl();
3670    }
3671    return;
3672  }
3673
3674  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
3675  if (!VDecl) {
3676    if (getLangOptions().CPlusPlus &&
3677        RealDecl->getLexicalDeclContext()->isRecord() &&
3678        isa<NamedDecl>(RealDecl))
3679      Diag(RealDecl->getLocation(), diag::err_member_initialization)
3680        << cast<NamedDecl>(RealDecl)->getDeclName();
3681    else
3682      Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
3683    RealDecl->setInvalidDecl();
3684    return;
3685  }
3686
3687  // A definition must end up with a complete type, which means it must be
3688  // complete with the restriction that an array type might be completed by the
3689  // initializer; note that later code assumes this restriction.
3690  QualType BaseDeclType = VDecl->getType();
3691  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
3692    BaseDeclType = Array->getElementType();
3693  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
3694                          diag::err_typecheck_decl_incomplete_type)) {
3695    RealDecl->setInvalidDecl();
3696    return;
3697  }
3698
3699  // The variable can not have an abstract class type.
3700  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
3701                             diag::err_abstract_type_in_decl,
3702                             AbstractVariableType))
3703    VDecl->setInvalidDecl();
3704
3705  const VarDecl *Def;
3706  if ((Def = VDecl->getDefinition()) && Def != VDecl) {
3707    Diag(VDecl->getLocation(), diag::err_redefinition)
3708      << VDecl->getDeclName();
3709    Diag(Def->getLocation(), diag::note_previous_definition);
3710    VDecl->setInvalidDecl();
3711    return;
3712  }
3713
3714  // Take ownership of the expression, now that we're sure we have somewhere
3715  // to put it.
3716  Expr *Init = init.takeAs<Expr>();
3717  assert(Init && "missing initializer");
3718
3719  // Capture the variable that is being initialized and the style of
3720  // initialization.
3721  InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
3722
3723  // FIXME: Poor source location information.
3724  InitializationKind Kind
3725    = DirectInit? InitializationKind::CreateDirect(VDecl->getLocation(),
3726                                                   Init->getLocStart(),
3727                                                   Init->getLocEnd())
3728                : InitializationKind::CreateCopy(VDecl->getLocation(),
3729                                                 Init->getLocStart());
3730
3731  // Get the decls type and save a reference for later, since
3732  // CheckInitializerTypes may change it.
3733  QualType DclT = VDecl->getType(), SavT = DclT;
3734  if (VDecl->isBlockVarDecl()) {
3735    if (VDecl->hasExternalStorage()) { // C99 6.7.8p5
3736      Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
3737      VDecl->setInvalidDecl();
3738    } else if (!VDecl->isInvalidDecl()) {
3739      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3740      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3741                                          MultiExprArg(*this, (void**)&Init, 1),
3742                                                &DclT);
3743      if (Result.isInvalid()) {
3744        VDecl->setInvalidDecl();
3745        return;
3746      }
3747
3748      Init = Result.takeAs<Expr>();
3749
3750      // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3751      // Don't check invalid declarations to avoid emitting useless diagnostics.
3752      if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3753        if (VDecl->getStorageClass() == VarDecl::Static) // C99 6.7.8p4.
3754          CheckForConstantInitializer(Init, DclT);
3755      }
3756    }
3757  } else if (VDecl->isStaticDataMember() &&
3758             VDecl->getLexicalDeclContext()->isRecord()) {
3759    // This is an in-class initialization for a static data member, e.g.,
3760    //
3761    // struct S {
3762    //   static const int value = 17;
3763    // };
3764
3765    // Attach the initializer
3766    VDecl->setInit(Init);
3767
3768    // C++ [class.mem]p4:
3769    //   A member-declarator can contain a constant-initializer only
3770    //   if it declares a static member (9.4) of const integral or
3771    //   const enumeration type, see 9.4.2.
3772    QualType T = VDecl->getType();
3773    if (!T->isDependentType() &&
3774        (!Context.getCanonicalType(T).isConstQualified() ||
3775         !T->isIntegralType())) {
3776      Diag(VDecl->getLocation(), diag::err_member_initialization)
3777        << VDecl->getDeclName() << Init->getSourceRange();
3778      VDecl->setInvalidDecl();
3779    } else {
3780      // C++ [class.static.data]p4:
3781      //   If a static data member is of const integral or const
3782      //   enumeration type, its declaration in the class definition
3783      //   can specify a constant-initializer which shall be an
3784      //   integral constant expression (5.19).
3785      if (!Init->isTypeDependent() &&
3786          !Init->getType()->isIntegralType()) {
3787        // We have a non-dependent, non-integral or enumeration type.
3788        Diag(Init->getSourceRange().getBegin(),
3789             diag::err_in_class_initializer_non_integral_type)
3790          << Init->getType() << Init->getSourceRange();
3791        VDecl->setInvalidDecl();
3792      } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
3793        // Check whether the expression is a constant expression.
3794        llvm::APSInt Value;
3795        SourceLocation Loc;
3796        if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
3797          Diag(Loc, diag::err_in_class_initializer_non_constant)
3798            << Init->getSourceRange();
3799          VDecl->setInvalidDecl();
3800        } else if (!VDecl->getType()->isDependentType())
3801          ImpCastExprToType(Init, VDecl->getType(), CastExpr::CK_IntegralCast);
3802      }
3803    }
3804  } else if (VDecl->isFileVarDecl()) {
3805    if (VDecl->getStorageClass() == VarDecl::Extern)
3806      Diag(VDecl->getLocation(), diag::warn_extern_init);
3807    if (!VDecl->isInvalidDecl()) {
3808      InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
3809      OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3810                                          MultiExprArg(*this, (void**)&Init, 1),
3811                                                &DclT);
3812      if (Result.isInvalid()) {
3813        VDecl->setInvalidDecl();
3814        return;
3815      }
3816
3817      Init = Result.takeAs<Expr>();
3818    }
3819
3820    // C++ 3.6.2p2, allow dynamic initialization of static initializers.
3821    // Don't check invalid declarations to avoid emitting useless diagnostics.
3822    if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
3823      // C99 6.7.8p4. All file scoped initializers need to be constant.
3824      CheckForConstantInitializer(Init, DclT);
3825    }
3826  }
3827  // If the type changed, it means we had an incomplete type that was
3828  // completed by the initializer. For example:
3829  //   int ary[] = { 1, 3, 5 };
3830  // "ary" transitions from a VariableArrayType to a ConstantArrayType.
3831  if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
3832    VDecl->setType(DclT);
3833    Init->setType(DclT);
3834  }
3835
3836  Init = MaybeCreateCXXExprWithTemporaries(Init);
3837  // Attach the initializer to the decl.
3838  VDecl->setInit(Init);
3839
3840  if (getLangOptions().CPlusPlus) {
3841    // Make sure we mark the destructor as used if necessary.
3842    QualType InitType = VDecl->getType();
3843    while (const ArrayType *Array = Context.getAsArrayType(InitType))
3844      InitType = Context.getBaseElementType(Array);
3845    if (const RecordType *Record = InitType->getAs<RecordType>())
3846      FinalizeVarWithDestructor(VDecl, Record);
3847  }
3848
3849  return;
3850}
3851
3852/// ActOnInitializerError - Given that there was an error parsing an
3853/// initializer for the given declaration, try to return to some form
3854/// of sanity.
3855void Sema::ActOnInitializerError(DeclPtrTy dcl) {
3856  // Our main concern here is re-establishing invariants like "a
3857  // variable's type is either dependent or complete".
3858  Decl *D = dcl.getAs<Decl>();
3859  if (!D || D->isInvalidDecl()) return;
3860
3861  VarDecl *VD = dyn_cast<VarDecl>(D);
3862  if (!VD) return;
3863
3864  QualType Ty = VD->getType();
3865  if (Ty->isDependentType()) return;
3866
3867  // Require a complete type.
3868  if (RequireCompleteType(VD->getLocation(),
3869                          Context.getBaseElementType(Ty),
3870                          diag::err_typecheck_decl_incomplete_type)) {
3871    VD->setInvalidDecl();
3872    return;
3873  }
3874
3875  // Require an abstract type.
3876  if (RequireNonAbstractType(VD->getLocation(), Ty,
3877                             diag::err_abstract_type_in_decl,
3878                             AbstractVariableType)) {
3879    VD->setInvalidDecl();
3880    return;
3881  }
3882
3883  // Don't bother complaining about constructors or destructors,
3884  // though.
3885}
3886
3887void Sema::ActOnUninitializedDecl(DeclPtrTy dcl,
3888                                  bool TypeContainsUndeducedAuto) {
3889  Decl *RealDecl = dcl.getAs<Decl>();
3890
3891  // If there is no declaration, there was an error parsing it. Just ignore it.
3892  if (RealDecl == 0)
3893    return;
3894
3895  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
3896    QualType Type = Var->getType();
3897
3898    // C++0x [dcl.spec.auto]p3
3899    if (TypeContainsUndeducedAuto) {
3900      Diag(Var->getLocation(), diag::err_auto_var_requires_init)
3901        << Var->getDeclName() << Type;
3902      Var->setInvalidDecl();
3903      return;
3904    }
3905
3906    switch (Var->isThisDeclarationADefinition()) {
3907    case VarDecl::Definition:
3908      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
3909        break;
3910
3911      // We have an out-of-line definition of a static data member
3912      // that has an in-class initializer, so we type-check this like
3913      // a declaration.
3914      //
3915      // Fall through
3916
3917    case VarDecl::DeclarationOnly:
3918      // It's only a declaration.
3919
3920      // Block scope. C99 6.7p7: If an identifier for an object is
3921      // declared with no linkage (C99 6.2.2p6), the type for the
3922      // object shall be complete.
3923      if (!Type->isDependentType() && Var->isBlockVarDecl() &&
3924          !Var->getLinkage() && !Var->isInvalidDecl() &&
3925          RequireCompleteType(Var->getLocation(), Type,
3926                              diag::err_typecheck_decl_incomplete_type))
3927        Var->setInvalidDecl();
3928
3929      // Make sure that the type is not abstract.
3930      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
3931          RequireNonAbstractType(Var->getLocation(), Type,
3932                                 diag::err_abstract_type_in_decl,
3933                                 AbstractVariableType))
3934        Var->setInvalidDecl();
3935      return;
3936
3937    case VarDecl::TentativeDefinition:
3938      // File scope. C99 6.9.2p2: A declaration of an identifier for an
3939      // object that has file scope without an initializer, and without a
3940      // storage-class specifier or with the storage-class specifier "static",
3941      // constitutes a tentative definition. Note: A tentative definition with
3942      // external linkage is valid (C99 6.2.2p5).
3943      if (!Var->isInvalidDecl()) {
3944        if (const IncompleteArrayType *ArrayT
3945                                    = Context.getAsIncompleteArrayType(Type)) {
3946          if (RequireCompleteType(Var->getLocation(),
3947                                  ArrayT->getElementType(),
3948                                  diag::err_illegal_decl_array_incomplete_type))
3949            Var->setInvalidDecl();
3950        } else if (Var->getStorageClass() == VarDecl::Static) {
3951          // C99 6.9.2p3: If the declaration of an identifier for an object is
3952          // a tentative definition and has internal linkage (C99 6.2.2p3), the
3953          // declared type shall not be an incomplete type.
3954          // NOTE: code such as the following
3955          //     static struct s;
3956          //     struct s { int a; };
3957          // is accepted by gcc. Hence here we issue a warning instead of
3958          // an error and we do not invalidate the static declaration.
3959          // NOTE: to avoid multiple warnings, only check the first declaration.
3960          if (Var->getPreviousDeclaration() == 0)
3961            RequireCompleteType(Var->getLocation(), Type,
3962                                diag::ext_typecheck_decl_incomplete_type);
3963        }
3964      }
3965
3966      // Record the tentative definition; we're done.
3967      if (!Var->isInvalidDecl())
3968        TentativeDefinitions.push_back(Var);
3969      return;
3970    }
3971
3972    // Provide a specific diagnostic for uninitialized variable
3973    // definitions with incomplete array type.
3974    if (Type->isIncompleteArrayType()) {
3975      Diag(Var->getLocation(),
3976           diag::err_typecheck_incomplete_array_needs_initializer);
3977      Var->setInvalidDecl();
3978      return;
3979    }
3980
3981   // Provide a specific diagnostic for uninitialized variable
3982   // definitions with reference type.
3983   if (Type->isReferenceType()) {
3984     Diag(Var->getLocation(), diag::err_reference_var_requires_init)
3985       << Var->getDeclName()
3986       << SourceRange(Var->getLocation(), Var->getLocation());
3987     Var->setInvalidDecl();
3988     return;
3989   }
3990
3991    // Do not attempt to type-check the default initializer for a
3992    // variable with dependent type.
3993    if (Type->isDependentType())
3994      return;
3995
3996    if (Var->isInvalidDecl())
3997      return;
3998
3999    if (RequireCompleteType(Var->getLocation(),
4000                            Context.getBaseElementType(Type),
4001                            diag::err_typecheck_decl_incomplete_type)) {
4002      Var->setInvalidDecl();
4003      return;
4004    }
4005
4006    // The variable can not have an abstract class type.
4007    if (RequireNonAbstractType(Var->getLocation(), Type,
4008                               diag::err_abstract_type_in_decl,
4009                               AbstractVariableType)) {
4010      Var->setInvalidDecl();
4011      return;
4012    }
4013
4014    const RecordType *Record
4015      = Context.getBaseElementType(Type)->getAs<RecordType>();
4016    if (Record && getLangOptions().CPlusPlus && !getLangOptions().CPlusPlus0x &&
4017        cast<CXXRecordDecl>(Record->getDecl())->isPOD()) {
4018      // C++03 [dcl.init]p9:
4019      //   If no initializer is specified for an object, and the
4020      //   object is of (possibly cv-qualified) non-POD class type (or
4021      //   array thereof), the object shall be default-initialized; if
4022      //   the object is of const-qualified type, the underlying class
4023      //   type shall have a user-declared default
4024      //   constructor. Otherwise, if no initializer is specified for
4025      //   a non- static object, the object and its subobjects, if
4026      //   any, have an indeterminate initial value); if the object
4027      //   or any of its subobjects are of const-qualified type, the
4028      //   program is ill-formed.
4029      // FIXME: DPG thinks it is very fishy that C++0x disables this.
4030    } else {
4031      InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
4032      InitializationKind Kind
4033        = InitializationKind::CreateDefault(Var->getLocation());
4034
4035      InitializationSequence InitSeq(*this, Entity, Kind, 0, 0);
4036      OwningExprResult Init = InitSeq.Perform(*this, Entity, Kind,
4037                                              MultiExprArg(*this, 0, 0));
4038      if (Init.isInvalid())
4039        Var->setInvalidDecl();
4040      else if (Init.get())
4041        Var->setInit(MaybeCreateCXXExprWithTemporaries(Init.takeAs<Expr>()));
4042    }
4043
4044    if (!Var->isInvalidDecl() && getLangOptions().CPlusPlus && Record)
4045      FinalizeVarWithDestructor(Var, Record);
4046  }
4047}
4048
4049Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
4050                                                   DeclPtrTy *Group,
4051                                                   unsigned NumDecls) {
4052  llvm::SmallVector<Decl*, 8> Decls;
4053
4054  if (DS.isTypeSpecOwned())
4055    Decls.push_back((Decl*)DS.getTypeRep());
4056
4057  for (unsigned i = 0; i != NumDecls; ++i)
4058    if (Decl *D = Group[i].getAs<Decl>())
4059      Decls.push_back(D);
4060
4061  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context,
4062                                                   Decls.data(), Decls.size()));
4063}
4064
4065
4066/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
4067/// to introduce parameters into function prototype scope.
4068Sema::DeclPtrTy
4069Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
4070  const DeclSpec &DS = D.getDeclSpec();
4071
4072  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
4073  VarDecl::StorageClass StorageClass = VarDecl::None;
4074  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4075    StorageClass = VarDecl::Register;
4076  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
4077    Diag(DS.getStorageClassSpecLoc(),
4078         diag::err_invalid_storage_class_in_func_decl);
4079    D.getMutableDeclSpec().ClearStorageClassSpecs();
4080  }
4081
4082  if (D.getDeclSpec().isThreadSpecified())
4083    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
4084
4085  DiagnoseFunctionSpecifiers(D);
4086
4087  // Check that there are no default arguments inside the type of this
4088  // parameter (C++ only).
4089  if (getLangOptions().CPlusPlus)
4090    CheckExtraCXXDefaultArguments(D);
4091
4092  TypeSourceInfo *TInfo = 0;
4093  TagDecl *OwnedDecl = 0;
4094  QualType parmDeclType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
4095
4096  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
4097    // C++ [dcl.fct]p6:
4098    //   Types shall not be defined in return or parameter types.
4099    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
4100      << Context.getTypeDeclType(OwnedDecl);
4101  }
4102
4103  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
4104  IdentifierInfo *II = D.getIdentifier();
4105  if (II) {
4106    LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
4107                   ForRedeclaration);
4108    LookupName(R, S);
4109    if (R.isSingleResult()) {
4110      NamedDecl *PrevDecl = R.getFoundDecl();
4111      if (PrevDecl->isTemplateParameter()) {
4112        // Maybe we will complain about the shadowed template parameter.
4113        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
4114        // Just pretend that we didn't see the previous declaration.
4115        PrevDecl = 0;
4116      } else if (S->isDeclScope(DeclPtrTy::make(PrevDecl))) {
4117        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
4118        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4119
4120        // Recover by removing the name
4121        II = 0;
4122        D.SetIdentifier(0, D.getIdentifierLoc());
4123        D.setInvalidType(true);
4124      }
4125    }
4126  }
4127
4128  // Temporarily put parameter variables in the translation unit, not
4129  // the enclosing context.  This prevents them from accidentally
4130  // looking like class members in C++.
4131  ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
4132                                    TInfo, parmDeclType, II,
4133                                    D.getIdentifierLoc(), StorageClass);
4134
4135  if (D.isInvalidType())
4136    New->setInvalidDecl();
4137
4138  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4139  if (D.getCXXScopeSpec().isSet()) {
4140    Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
4141      << D.getCXXScopeSpec().getRange();
4142    New->setInvalidDecl();
4143  }
4144
4145  // Add the parameter declaration into this scope.
4146  S->AddDecl(DeclPtrTy::make(New));
4147  if (II)
4148    IdResolver.AddDecl(New);
4149
4150  ProcessDeclAttributes(S, New, D);
4151
4152  if (New->hasAttr<BlocksAttr>()) {
4153    Diag(New->getLocation(), diag::err_block_on_nonlocal);
4154  }
4155  return DeclPtrTy::make(New);
4156}
4157
4158ParmVarDecl *Sema::CheckParameter(DeclContext *DC,
4159                                  TypeSourceInfo *TSInfo, QualType T,
4160                                  IdentifierInfo *Name,
4161                                  SourceLocation NameLoc,
4162                                  VarDecl::StorageClass StorageClass) {
4163  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, NameLoc, Name,
4164                                         adjustParameterType(T), TSInfo,
4165                                         StorageClass, 0);
4166
4167  // Parameters can not be abstract class types.
4168  // For record types, this is done by the AbstractClassUsageDiagnoser once
4169  // the class has been completely parsed.
4170  if (!CurContext->isRecord() &&
4171      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
4172                             AbstractParamType))
4173    New->setInvalidDecl();
4174
4175  // Parameter declarators cannot be interface types. All ObjC objects are
4176  // passed by reference.
4177  if (T->isObjCInterfaceType()) {
4178    Diag(NameLoc,
4179         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T;
4180    New->setInvalidDecl();
4181  }
4182
4183  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4184  // duration shall not be qualified by an address-space qualifier."
4185  // Since all parameters have automatic store duration, they can not have
4186  // an address space.
4187  if (T.getAddressSpace() != 0) {
4188    Diag(NameLoc, diag::err_arg_with_address_space);
4189    New->setInvalidDecl();
4190  }
4191
4192  return New;
4193}
4194
4195void Sema::ActOnObjCCatchParam(DeclPtrTy D) {
4196  ParmVarDecl *Param = cast<ParmVarDecl>(D.getAs<Decl>());
4197  Param->setDeclContext(CurContext);
4198}
4199
4200void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
4201                                           SourceLocation LocAfterDecls) {
4202  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4203         "Not a function declarator!");
4204  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4205
4206  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
4207  // for a K&R function.
4208  if (!FTI.hasPrototype) {
4209    for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) {
4210      --i;
4211      if (FTI.ArgInfo[i].Param == 0) {
4212        llvm::SmallString<256> Code;
4213        llvm::raw_svector_ostream(Code) << "  int "
4214                                        << FTI.ArgInfo[i].Ident->getName()
4215                                        << ";\n";
4216        Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
4217          << FTI.ArgInfo[i].Ident
4218          << FixItHint::CreateInsertion(LocAfterDecls, Code.str());
4219
4220        // Implicitly declare the argument as type 'int' for lack of a better
4221        // type.
4222        DeclSpec DS;
4223        const char* PrevSpec; // unused
4224        unsigned DiagID; // unused
4225        DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
4226                           PrevSpec, DiagID);
4227        Declarator ParamD(DS, Declarator::KNRTypeListContext);
4228        ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
4229        FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
4230      }
4231    }
4232  }
4233}
4234
4235Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope,
4236                                              Declarator &D) {
4237  assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4238  assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4239         "Not a function declarator!");
4240  DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4241
4242  if (FTI.hasPrototype) {
4243    // FIXME: Diagnose arguments without names in C.
4244  }
4245
4246  Scope *ParentScope = FnBodyScope->getParent();
4247
4248  DeclPtrTy DP = HandleDeclarator(ParentScope, D,
4249                                  MultiTemplateParamsArg(*this),
4250                                  /*IsFunctionDefinition=*/true);
4251  return ActOnStartOfFunctionDef(FnBodyScope, DP);
4252}
4253
4254static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) {
4255  // Don't warn about invalid declarations.
4256  if (FD->isInvalidDecl())
4257    return false;
4258
4259  // Or declarations that aren't global.
4260  if (!FD->isGlobal())
4261    return false;
4262
4263  // Don't warn about C++ member functions.
4264  if (isa<CXXMethodDecl>(FD))
4265    return false;
4266
4267  // Don't warn about 'main'.
4268  if (FD->isMain())
4269    return false;
4270
4271  // Don't warn about inline functions.
4272  if (FD->isInlineSpecified())
4273    return false;
4274
4275  // Don't warn about function templates.
4276  if (FD->getDescribedFunctionTemplate())
4277    return false;
4278
4279  // Don't warn about function template specializations.
4280  if (FD->isFunctionTemplateSpecialization())
4281    return false;
4282
4283  bool MissingPrototype = true;
4284  for (const FunctionDecl *Prev = FD->getPreviousDeclaration();
4285       Prev; Prev = Prev->getPreviousDeclaration()) {
4286    // Ignore any declarations that occur in function or method
4287    // scope, because they aren't visible from the header.
4288    if (Prev->getDeclContext()->isFunctionOrMethod())
4289      continue;
4290
4291    MissingPrototype = !Prev->getType()->isFunctionProtoType();
4292    break;
4293  }
4294
4295  return MissingPrototype;
4296}
4297
4298Sema::DeclPtrTy Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclPtrTy D) {
4299  // Clear the last template instantiation error context.
4300  LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
4301
4302  if (!D)
4303    return D;
4304  FunctionDecl *FD = 0;
4305
4306  if (FunctionTemplateDecl *FunTmpl
4307        = dyn_cast<FunctionTemplateDecl>(D.getAs<Decl>()))
4308    FD = FunTmpl->getTemplatedDecl();
4309  else
4310    FD = cast<FunctionDecl>(D.getAs<Decl>());
4311
4312  // Enter a new function scope
4313  PushFunctionScope();
4314
4315  // See if this is a redefinition.
4316  // But don't complain if we're in GNU89 mode and the previous definition
4317  // was an extern inline function.
4318  const FunctionDecl *Definition;
4319  if (FD->getBody(Definition) &&
4320      !canRedefineFunction(Definition, getLangOptions())) {
4321    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
4322    Diag(Definition->getLocation(), diag::note_previous_definition);
4323  }
4324
4325  // Builtin functions cannot be defined.
4326  if (unsigned BuiltinID = FD->getBuiltinID()) {
4327    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4328      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
4329      FD->setInvalidDecl();
4330    }
4331  }
4332
4333  // The return type of a function definition must be complete
4334  // (C99 6.9.1p3, C++ [dcl.fct]p6).
4335  QualType ResultType = FD->getResultType();
4336  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
4337      !FD->isInvalidDecl() &&
4338      RequireCompleteType(FD->getLocation(), ResultType,
4339                          diag::err_func_def_incomplete_result))
4340    FD->setInvalidDecl();
4341
4342  // GNU warning -Wmissing-prototypes:
4343  //   Warn if a global function is defined without a previous
4344  //   prototype declaration. This warning is issued even if the
4345  //   definition itself provides a prototype. The aim is to detect
4346  //   global functions that fail to be declared in header files.
4347  if (ShouldWarnAboutMissingPrototype(FD))
4348    Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
4349
4350  if (FnBodyScope)
4351    PushDeclContext(FnBodyScope, FD);
4352
4353  // Check the validity of our function parameters
4354  CheckParmsForFunctionDef(FD);
4355
4356  bool ShouldCheckShadow =
4357    Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
4358
4359  // Introduce our parameters into the function scope
4360  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
4361    ParmVarDecl *Param = FD->getParamDecl(p);
4362    Param->setOwningFunction(FD);
4363
4364    // If this has an identifier, add it to the scope stack.
4365    if (Param->getIdentifier() && FnBodyScope) {
4366      if (ShouldCheckShadow)
4367        CheckShadow(FnBodyScope, Param);
4368
4369      PushOnScopeChains(Param, FnBodyScope);
4370    }
4371  }
4372
4373  // Checking attributes of current function definition
4374  // dllimport attribute.
4375  if (FD->getAttr<DLLImportAttr>() &&
4376      (!FD->getAttr<DLLExportAttr>())) {
4377    // dllimport attribute cannot be applied to definition.
4378    if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
4379      Diag(FD->getLocation(),
4380           diag::err_attribute_can_be_applied_only_to_symbol_declaration)
4381        << "dllimport";
4382      FD->setInvalidDecl();
4383      return DeclPtrTy::make(FD);
4384    }
4385
4386    // Visual C++ appears to not think this is an issue, so only issue
4387    // a warning when Microsoft extensions are disabled.
4388    if (!LangOpts.Microsoft) {
4389      // If a symbol previously declared dllimport is later defined, the
4390      // attribute is ignored in subsequent references, and a warning is
4391      // emitted.
4392      Diag(FD->getLocation(),
4393           diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
4394        << FD->getNameAsCString() << "dllimport";
4395    }
4396  }
4397  return DeclPtrTy::make(FD);
4398}
4399
4400Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg) {
4401  return ActOnFinishFunctionBody(D, move(BodyArg), false);
4402}
4403
4404Sema::DeclPtrTy Sema::ActOnFinishFunctionBody(DeclPtrTy D, StmtArg BodyArg,
4405                                              bool IsInstantiation) {
4406  Decl *dcl = D.getAs<Decl>();
4407  Stmt *Body = BodyArg.takeAs<Stmt>();
4408
4409  FunctionDecl *FD = 0;
4410  FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl);
4411  if (FunTmpl)
4412    FD = FunTmpl->getTemplatedDecl();
4413  else
4414    FD = dyn_cast_or_null<FunctionDecl>(dcl);
4415
4416  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
4417
4418  if (FD) {
4419    FD->setBody(Body);
4420    if (FD->isMain()) {
4421      // C and C++ allow for main to automagically return 0.
4422      // Implements C++ [basic.start.main]p5 and C99 5.1.2.2.3.
4423      FD->setHasImplicitReturnZero(true);
4424      WP.disableCheckFallThrough();
4425    }
4426
4427    if (!FD->isInvalidDecl())
4428      DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
4429
4430    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
4431      MaybeMarkVirtualMembersReferenced(Method->getLocation(), Method);
4432
4433    assert(FD == getCurFunctionDecl() && "Function parsing confused");
4434  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
4435    assert(MD == getCurMethodDecl() && "Method parsing confused");
4436    MD->setBody(Body);
4437    MD->setEndLoc(Body->getLocEnd());
4438    if (!MD->isInvalidDecl())
4439      DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
4440  } else {
4441    Body->Destroy(Context);
4442    return DeclPtrTy();
4443  }
4444
4445  // Verify and clean out per-function state.
4446
4447  // Check goto/label use.
4448  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
4449       I = getLabelMap().begin(), E = getLabelMap().end(); I != E; ++I) {
4450    LabelStmt *L = I->second;
4451
4452    // Verify that we have no forward references left.  If so, there was a goto
4453    // or address of a label taken, but no definition of it.  Label fwd
4454    // definitions are indicated with a null substmt.
4455    if (L->getSubStmt() != 0)
4456      continue;
4457
4458    // Emit error.
4459    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
4460
4461    // At this point, we have gotos that use the bogus label.  Stitch it into
4462    // the function body so that they aren't leaked and that the AST is well
4463    // formed.
4464    if (Body == 0) {
4465      // The whole function wasn't parsed correctly, just delete this.
4466      L->Destroy(Context);
4467      continue;
4468    }
4469
4470    // Otherwise, the body is valid: we want to stitch the label decl into the
4471    // function somewhere so that it is properly owned and so that the goto
4472    // has a valid target.  Do this by creating a new compound stmt with the
4473    // label in it.
4474
4475    // Give the label a sub-statement.
4476    L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
4477
4478    CompoundStmt *Compound = isa<CXXTryStmt>(Body) ?
4479                               cast<CXXTryStmt>(Body)->getTryBlock() :
4480                               cast<CompoundStmt>(Body);
4481    llvm::SmallVector<Stmt*, 64> Elements(Compound->body_begin(),
4482                                          Compound->body_end());
4483    Elements.push_back(L);
4484    Compound->setStmts(Context, Elements.data(), Elements.size());
4485  }
4486
4487  if (Body) {
4488    // C++ constructors that have function-try-blocks can't have return
4489    // statements in the handlers of that block. (C++ [except.handle]p14)
4490    // Verify this.
4491    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
4492      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
4493
4494    // Verify that that gotos and switch cases don't jump into scopes illegally.
4495    // Verify that that gotos and switch cases don't jump into scopes illegally.
4496    if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
4497      DiagnoseInvalidJumps(Body);
4498
4499    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl))
4500      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4501                                             Destructor->getParent());
4502
4503    // If any errors have occurred, clear out any temporaries that may have
4504    // been leftover. This ensures that these temporaries won't be picked up for
4505    // deletion in some later function.
4506    if (PP.getDiagnostics().hasErrorOccurred())
4507      ExprTemporaries.clear();
4508    else if (!isa<FunctionTemplateDecl>(dcl)) {
4509      // Since the body is valid, issue any analysis-based warnings that are
4510      // enabled.
4511      QualType ResultType;
4512      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(dcl)) {
4513        ResultType = FD->getResultType();
4514      }
4515      else {
4516        ObjCMethodDecl *MD = cast<ObjCMethodDecl>(dcl);
4517        ResultType = MD->getResultType();
4518      }
4519      AnalysisWarnings.IssueWarnings(WP, dcl);
4520    }
4521
4522    assert(ExprTemporaries.empty() && "Leftover temporaries in function");
4523  }
4524
4525  if (!IsInstantiation)
4526    PopDeclContext();
4527
4528  PopFunctionOrBlockScope();
4529
4530  // If any errors have occurred, clear out any temporaries that may have
4531  // been leftover. This ensures that these temporaries won't be picked up for
4532  // deletion in some later function.
4533  if (getDiagnostics().hasErrorOccurred())
4534    ExprTemporaries.clear();
4535
4536  return D;
4537}
4538
4539/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
4540/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
4541NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
4542                                          IdentifierInfo &II, Scope *S) {
4543  // Before we produce a declaration for an implicitly defined
4544  // function, see whether there was a locally-scoped declaration of
4545  // this name as a function or variable. If so, use that
4546  // (non-visible) declaration, and complain about it.
4547  llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
4548    = LocallyScopedExternalDecls.find(&II);
4549  if (Pos != LocallyScopedExternalDecls.end()) {
4550    Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
4551    Diag(Pos->second->getLocation(), diag::note_previous_declaration);
4552    return Pos->second;
4553  }
4554
4555  // Extension in C99.  Legal in C90, but warn about it.
4556  if (II.getName().startswith("__builtin_"))
4557    Diag(Loc, diag::warn_builtin_unknown) << &II;
4558  else if (getLangOptions().C99)
4559    Diag(Loc, diag::ext_implicit_function_decl) << &II;
4560  else
4561    Diag(Loc, diag::warn_implicit_function_decl) << &II;
4562
4563  // Set a Declarator for the implicit definition: int foo();
4564  const char *Dummy;
4565  DeclSpec DS;
4566  unsigned DiagID;
4567  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID);
4568  Error = Error; // Silence warning.
4569  assert(!Error && "Error setting up implicit decl!");
4570  Declarator D(DS, Declarator::BlockContext);
4571  D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0,
4572                                             0, 0, false, SourceLocation(),
4573                                             false, 0,0,0, Loc, Loc, D),
4574                SourceLocation());
4575  D.SetIdentifier(&II, Loc);
4576
4577  // Insert this function into translation-unit scope.
4578
4579  DeclContext *PrevDC = CurContext;
4580  CurContext = Context.getTranslationUnitDecl();
4581
4582  FunctionDecl *FD =
4583 dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D).getAs<Decl>());
4584  FD->setImplicit();
4585
4586  CurContext = PrevDC;
4587
4588  AddKnownFunctionAttributes(FD);
4589
4590  return FD;
4591}
4592
4593/// \brief Adds any function attributes that we know a priori based on
4594/// the declaration of this function.
4595///
4596/// These attributes can apply both to implicitly-declared builtins
4597/// (like __builtin___printf_chk) or to library-declared functions
4598/// like NSLog or printf.
4599void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
4600  if (FD->isInvalidDecl())
4601    return;
4602
4603  // If this is a built-in function, map its builtin attributes to
4604  // actual attributes.
4605  if (unsigned BuiltinID = FD->getBuiltinID()) {
4606    // Handle printf-formatting attributes.
4607    unsigned FormatIdx;
4608    bool HasVAListArg;
4609    if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
4610      if (!FD->getAttr<FormatAttr>())
4611        FD->addAttr(::new (Context) FormatAttr(Context, "printf", FormatIdx+1,
4612                                               HasVAListArg ? 0 : FormatIdx+2));
4613    }
4614
4615    // Mark const if we don't care about errno and that is the only
4616    // thing preventing the function from being const. This allows
4617    // IRgen to use LLVM intrinsics for such functions.
4618    if (!getLangOptions().MathErrno &&
4619        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
4620      if (!FD->getAttr<ConstAttr>())
4621        FD->addAttr(::new (Context) ConstAttr());
4622    }
4623
4624    if (Context.BuiltinInfo.isNoReturn(BuiltinID))
4625      FD->setType(Context.getNoReturnType(FD->getType()));
4626    if (Context.BuiltinInfo.isNoThrow(BuiltinID))
4627      FD->addAttr(::new (Context) NoThrowAttr());
4628    if (Context.BuiltinInfo.isConst(BuiltinID))
4629      FD->addAttr(::new (Context) ConstAttr());
4630  }
4631
4632  IdentifierInfo *Name = FD->getIdentifier();
4633  if (!Name)
4634    return;
4635  if ((!getLangOptions().CPlusPlus &&
4636       FD->getDeclContext()->isTranslationUnit()) ||
4637      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
4638       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
4639       LinkageSpecDecl::lang_c)) {
4640    // Okay: this could be a libc/libm/Objective-C function we know
4641    // about.
4642  } else
4643    return;
4644
4645  if (Name->isStr("NSLog") || Name->isStr("NSLogv")) {
4646    // FIXME: NSLog and NSLogv should be target specific
4647    if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
4648      // FIXME: We known better than our headers.
4649      const_cast<FormatAttr *>(Format)->setType(Context, "printf");
4650    } else
4651      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 1,
4652                                             Name->isStr("NSLogv") ? 0 : 2));
4653  } else if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
4654    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
4655    // target-specific builtins, perhaps?
4656    if (!FD->getAttr<FormatAttr>())
4657      FD->addAttr(::new (Context) FormatAttr(Context, "printf", 2,
4658                                             Name->isStr("vasprintf") ? 0 : 3));
4659  }
4660}
4661
4662TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
4663                                    TypeSourceInfo *TInfo) {
4664  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
4665  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
4666
4667  if (!TInfo) {
4668    assert(D.isInvalidType() && "no declarator info for valid type");
4669    TInfo = Context.getTrivialTypeSourceInfo(T);
4670  }
4671
4672  // Scope manipulation handled by caller.
4673  TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
4674                                           D.getIdentifierLoc(),
4675                                           D.getIdentifier(),
4676                                           TInfo);
4677
4678  if (const TagType *TT = T->getAs<TagType>()) {
4679    TagDecl *TD = TT->getDecl();
4680
4681    // If the TagDecl that the TypedefDecl points to is an anonymous decl
4682    // keep track of the TypedefDecl.
4683    if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
4684      TD->setTypedefForAnonDecl(NewTD);
4685  }
4686
4687  if (D.isInvalidType())
4688    NewTD->setInvalidDecl();
4689  return NewTD;
4690}
4691
4692
4693/// \brief Determine whether a tag with a given kind is acceptable
4694/// as a redeclaration of the given tag declaration.
4695///
4696/// \returns true if the new tag kind is acceptable, false otherwise.
4697bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
4698                                        TagDecl::TagKind NewTag,
4699                                        SourceLocation NewTagLoc,
4700                                        const IdentifierInfo &Name) {
4701  // C++ [dcl.type.elab]p3:
4702  //   The class-key or enum keyword present in the
4703  //   elaborated-type-specifier shall agree in kind with the
4704  //   declaration to which the name in theelaborated-type-specifier
4705  //   refers. This rule also applies to the form of
4706  //   elaborated-type-specifier that declares a class-name or
4707  //   friend class since it can be construed as referring to the
4708  //   definition of the class. Thus, in any
4709  //   elaborated-type-specifier, the enum keyword shall be used to
4710  //   refer to an enumeration (7.2), the union class-keyshall be
4711  //   used to refer to a union (clause 9), and either the class or
4712  //   struct class-key shall be used to refer to a class (clause 9)
4713  //   declared using the class or struct class-key.
4714  TagDecl::TagKind OldTag = Previous->getTagKind();
4715  if (OldTag == NewTag)
4716    return true;
4717
4718  if ((OldTag == TagDecl::TK_struct || OldTag == TagDecl::TK_class) &&
4719      (NewTag == TagDecl::TK_struct || NewTag == TagDecl::TK_class)) {
4720    // Warn about the struct/class tag mismatch.
4721    bool isTemplate = false;
4722    if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
4723      isTemplate = Record->getDescribedClassTemplate();
4724
4725    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
4726      << (NewTag == TagDecl::TK_class)
4727      << isTemplate << &Name
4728      << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
4729                              OldTag == TagDecl::TK_class? "class" : "struct");
4730    Diag(Previous->getLocation(), diag::note_previous_use);
4731    return true;
4732  }
4733  return false;
4734}
4735
4736/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'.  In the
4737/// former case, Name will be non-null.  In the later case, Name will be null.
4738/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
4739/// reference/declaration/definition of a tag.
4740Sema::DeclPtrTy Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
4741                               SourceLocation KWLoc, CXXScopeSpec &SS,
4742                               IdentifierInfo *Name, SourceLocation NameLoc,
4743                               AttributeList *Attr, AccessSpecifier AS,
4744                               MultiTemplateParamsArg TemplateParameterLists,
4745                               bool &OwnedDecl, bool &IsDependent) {
4746  // If this is not a definition, it must have a name.
4747  assert((Name != 0 || TUK == TUK_Definition) &&
4748         "Nameless record must be a definition!");
4749
4750  OwnedDecl = false;
4751  TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec);
4752
4753  // FIXME: Check explicit specializations more carefully.
4754  bool isExplicitSpecialization = false;
4755  if (TUK != TUK_Reference) {
4756    if (TemplateParameterList *TemplateParams
4757          = MatchTemplateParametersToScopeSpecifier(KWLoc, SS,
4758                        (TemplateParameterList**)TemplateParameterLists.get(),
4759                                              TemplateParameterLists.size(),
4760                                                    isExplicitSpecialization)) {
4761      if (TemplateParams->size() > 0) {
4762        // This is a declaration or definition of a class template (which may
4763        // be a member of another template).
4764        OwnedDecl = false;
4765        DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
4766                                               SS, Name, NameLoc, Attr,
4767                                               TemplateParams,
4768                                               AS);
4769        TemplateParameterLists.release();
4770        return Result.get();
4771      } else {
4772        // The "template<>" header is extraneous.
4773        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
4774          << ElaboratedType::getNameForTagKind(Kind) << Name;
4775        isExplicitSpecialization = true;
4776      }
4777    }
4778
4779    TemplateParameterLists.release();
4780  }
4781
4782  DeclContext *SearchDC = CurContext;
4783  DeclContext *DC = CurContext;
4784  bool isStdBadAlloc = false;
4785  bool Invalid = false;
4786
4787  RedeclarationKind Redecl = ForRedeclaration;
4788  if (TUK == TUK_Friend || TUK == TUK_Reference)
4789    Redecl = NotForRedeclaration;
4790
4791  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
4792
4793  if (Name && SS.isNotEmpty()) {
4794    // We have a nested-name tag ('struct foo::bar').
4795
4796    // Check for invalid 'foo::'.
4797    if (SS.isInvalid()) {
4798      Name = 0;
4799      goto CreateNewDecl;
4800    }
4801
4802    // If this is a friend or a reference to a class in a dependent
4803    // context, don't try to make a decl for it.
4804    if (TUK == TUK_Friend || TUK == TUK_Reference) {
4805      DC = computeDeclContext(SS, false);
4806      if (!DC) {
4807        IsDependent = true;
4808        return DeclPtrTy();
4809      }
4810    }
4811
4812    if (RequireCompleteDeclContext(SS))
4813      return DeclPtrTy::make((Decl *)0);
4814
4815    DC = computeDeclContext(SS, true);
4816    SearchDC = DC;
4817    // Look-up name inside 'foo::'.
4818    LookupQualifiedName(Previous, DC);
4819
4820    if (Previous.isAmbiguous())
4821      return DeclPtrTy();
4822
4823    if (Previous.empty()) {
4824      // Name lookup did not find anything. However, if the
4825      // nested-name-specifier refers to the current instantiation,
4826      // and that current instantiation has any dependent base
4827      // classes, we might find something at instantiation time: treat
4828      // this as a dependent elaborated-type-specifier.
4829      if (Previous.wasNotFoundInCurrentInstantiation()) {
4830        IsDependent = true;
4831        return DeclPtrTy();
4832      }
4833
4834      // A tag 'foo::bar' must already exist.
4835      Diag(NameLoc, diag::err_not_tag_in_scope)
4836        << Kind << Name << DC << SS.getRange();
4837      Name = 0;
4838      Invalid = true;
4839      goto CreateNewDecl;
4840    }
4841  } else if (Name) {
4842    // If this is a named struct, check to see if there was a previous forward
4843    // declaration or definition.
4844    // FIXME: We're looking into outer scopes here, even when we
4845    // shouldn't be. Doing so can result in ambiguities that we
4846    // shouldn't be diagnosing.
4847    LookupName(Previous, S);
4848
4849    // Note:  there used to be some attempt at recovery here.
4850    if (Previous.isAmbiguous())
4851      return DeclPtrTy();
4852
4853    if (!getLangOptions().CPlusPlus && TUK != TUK_Reference) {
4854      // FIXME: This makes sure that we ignore the contexts associated
4855      // with C structs, unions, and enums when looking for a matching
4856      // tag declaration or definition. See the similar lookup tweak
4857      // in Sema::LookupName; is there a better way to deal with this?
4858      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
4859        SearchDC = SearchDC->getParent();
4860    }
4861  }
4862
4863  if (Previous.isSingleResult() &&
4864      Previous.getFoundDecl()->isTemplateParameter()) {
4865    // Maybe we will complain about the shadowed template parameter.
4866    DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
4867    // Just pretend that we didn't see the previous declaration.
4868    Previous.clear();
4869  }
4870
4871  if (getLangOptions().CPlusPlus && Name && DC && StdNamespace &&
4872      DC->Equals(StdNamespace) && Name->isStr("bad_alloc")) {
4873    // This is a declaration of or a reference to "std::bad_alloc".
4874    isStdBadAlloc = true;
4875
4876    if (Previous.empty() && StdBadAlloc) {
4877      // std::bad_alloc has been implicitly declared (but made invisible to
4878      // name lookup). Fill in this implicit declaration as the previous
4879      // declaration, so that the declarations get chained appropriately.
4880      Previous.addDecl(StdBadAlloc);
4881    }
4882  }
4883
4884  // If we didn't find a previous declaration, and this is a reference
4885  // (or friend reference), move to the correct scope.  In C++, we
4886  // also need to do a redeclaration lookup there, just in case
4887  // there's a shadow friend decl.
4888  if (Name && Previous.empty() &&
4889      (TUK == TUK_Reference || TUK == TUK_Friend)) {
4890    if (Invalid) goto CreateNewDecl;
4891    assert(SS.isEmpty());
4892
4893    if (TUK == TUK_Reference) {
4894      // C++ [basic.scope.pdecl]p5:
4895      //   -- for an elaborated-type-specifier of the form
4896      //
4897      //          class-key identifier
4898      //
4899      //      if the elaborated-type-specifier is used in the
4900      //      decl-specifier-seq or parameter-declaration-clause of a
4901      //      function defined in namespace scope, the identifier is
4902      //      declared as a class-name in the namespace that contains
4903      //      the declaration; otherwise, except as a friend
4904      //      declaration, the identifier is declared in the smallest
4905      //      non-class, non-function-prototype scope that contains the
4906      //      declaration.
4907      //
4908      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
4909      // C structs and unions.
4910      //
4911      // It is an error in C++ to declare (rather than define) an enum
4912      // type, including via an elaborated type specifier.  We'll
4913      // diagnose that later; for now, declare the enum in the same
4914      // scope as we would have picked for any other tag type.
4915      //
4916      // GNU C also supports this behavior as part of its incomplete
4917      // enum types extension, while GNU C++ does not.
4918      //
4919      // Find the context where we'll be declaring the tag.
4920      // FIXME: We would like to maintain the current DeclContext as the
4921      // lexical context,
4922      while (SearchDC->isRecord())
4923        SearchDC = SearchDC->getParent();
4924
4925      // Find the scope where we'll be declaring the tag.
4926      while (S->isClassScope() ||
4927             (getLangOptions().CPlusPlus &&
4928              S->isFunctionPrototypeScope()) ||
4929             ((S->getFlags() & Scope::DeclScope) == 0) ||
4930             (S->getEntity() &&
4931              ((DeclContext *)S->getEntity())->isTransparentContext()))
4932        S = S->getParent();
4933    } else {
4934      assert(TUK == TUK_Friend);
4935      // C++ [namespace.memdef]p3:
4936      //   If a friend declaration in a non-local class first declares a
4937      //   class or function, the friend class or function is a member of
4938      //   the innermost enclosing namespace.
4939      SearchDC = SearchDC->getEnclosingNamespaceContext();
4940    }
4941
4942    // In C++, look for a shadow friend decl.
4943    if (getLangOptions().CPlusPlus) {
4944      Previous.setRedeclarationKind(ForRedeclaration);
4945      LookupQualifiedName(Previous, SearchDC);
4946    }
4947  }
4948
4949  if (!Previous.empty()) {
4950    NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl();
4951    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
4952      // If this is a use of a previous tag, or if the tag is already declared
4953      // in the same scope (so that the definition/declaration completes or
4954      // rementions the tag), reuse the decl.
4955      if (TUK == TUK_Reference || TUK == TUK_Friend ||
4956          isDeclInScope(PrevDecl, SearchDC, S)) {
4957        // Make sure that this wasn't declared as an enum and now used as a
4958        // struct or something similar.
4959        if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, KWLoc, *Name)) {
4960          bool SafeToContinue
4961            = (PrevTagDecl->getTagKind() != TagDecl::TK_enum &&
4962               Kind != TagDecl::TK_enum);
4963          if (SafeToContinue)
4964            Diag(KWLoc, diag::err_use_with_wrong_tag)
4965              << Name
4966              << FixItHint::CreateReplacement(SourceRange(KWLoc),
4967                                              PrevTagDecl->getKindName());
4968          else
4969            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
4970          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
4971
4972          if (SafeToContinue)
4973            Kind = PrevTagDecl->getTagKind();
4974          else {
4975            // Recover by making this an anonymous redefinition.
4976            Name = 0;
4977            Previous.clear();
4978            Invalid = true;
4979          }
4980        }
4981
4982        if (!Invalid) {
4983          // If this is a use, just return the declaration we found.
4984
4985          // FIXME: In the future, return a variant or some other clue
4986          // for the consumer of this Decl to know it doesn't own it.
4987          // For our current ASTs this shouldn't be a problem, but will
4988          // need to be changed with DeclGroups.
4989          if (TUK == TUK_Reference || TUK == TUK_Friend)
4990            return DeclPtrTy::make(PrevTagDecl);
4991
4992          // Diagnose attempts to redefine a tag.
4993          if (TUK == TUK_Definition) {
4994            if (TagDecl *Def = PrevTagDecl->getDefinition()) {
4995              // If we're defining a specialization and the previous definition
4996              // is from an implicit instantiation, don't emit an error
4997              // here; we'll catch this in the general case below.
4998              if (!isExplicitSpecialization ||
4999                  !isa<CXXRecordDecl>(Def) ||
5000                  cast<CXXRecordDecl>(Def)->getTemplateSpecializationKind()
5001                                               == TSK_ExplicitSpecialization) {
5002                Diag(NameLoc, diag::err_redefinition) << Name;
5003                Diag(Def->getLocation(), diag::note_previous_definition);
5004                // If this is a redefinition, recover by making this
5005                // struct be anonymous, which will make any later
5006                // references get the previous definition.
5007                Name = 0;
5008                Previous.clear();
5009                Invalid = true;
5010              }
5011            } else {
5012              // If the type is currently being defined, complain
5013              // about a nested redefinition.
5014              TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
5015              if (Tag->isBeingDefined()) {
5016                Diag(NameLoc, diag::err_nested_redefinition) << Name;
5017                Diag(PrevTagDecl->getLocation(),
5018                     diag::note_previous_definition);
5019                Name = 0;
5020                Previous.clear();
5021                Invalid = true;
5022              }
5023            }
5024
5025            // Okay, this is definition of a previously declared or referenced
5026            // tag PrevDecl. We're going to create a new Decl for it.
5027          }
5028        }
5029        // If we get here we have (another) forward declaration or we
5030        // have a definition.  Just create a new decl.
5031
5032      } else {
5033        // If we get here, this is a definition of a new tag type in a nested
5034        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
5035        // new decl/type.  We set PrevDecl to NULL so that the entities
5036        // have distinct types.
5037        Previous.clear();
5038      }
5039      // If we get here, we're going to create a new Decl. If PrevDecl
5040      // is non-NULL, it's a definition of the tag declared by
5041      // PrevDecl. If it's NULL, we have a new definition.
5042    } else {
5043      // PrevDecl is a namespace, template, or anything else
5044      // that lives in the IDNS_Tag identifier namespace.
5045      if (TUK == TUK_Reference || TUK == TUK_Friend ||
5046          isDeclInScope(PrevDecl, SearchDC, S)) {
5047        // The tag name clashes with a namespace name, issue an error and
5048        // recover by making this tag be anonymous.
5049        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
5050        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5051        Name = 0;
5052        Previous.clear();
5053        Invalid = true;
5054      } else {
5055        // The existing declaration isn't relevant to us; we're in a
5056        // new scope, so clear out the previous declaration.
5057        Previous.clear();
5058      }
5059    }
5060  }
5061
5062CreateNewDecl:
5063
5064  TagDecl *PrevDecl = 0;
5065  if (Previous.isSingleResult())
5066    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
5067
5068  // If there is an identifier, use the location of the identifier as the
5069  // location of the decl, otherwise use the location of the struct/union
5070  // keyword.
5071  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
5072
5073  // Otherwise, create a new declaration. If there is a previous
5074  // declaration of the same entity, the two will be linked via
5075  // PrevDecl.
5076  TagDecl *New;
5077
5078  if (Kind == TagDecl::TK_enum) {
5079    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5080    // enum X { A, B, C } D;    D should chain to X.
5081    New = EnumDecl::Create(Context, SearchDC, Loc, Name, KWLoc,
5082                           cast_or_null<EnumDecl>(PrevDecl));
5083    // If this is an undefined enum, warn.
5084    if (TUK != TUK_Definition && !Invalid)  {
5085      unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
5086                                              : diag::ext_forward_ref_enum;
5087      Diag(Loc, DK);
5088    }
5089  } else {
5090    // struct/union/class
5091
5092    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
5093    // struct X { int A; } D;    D should chain to X.
5094    if (getLangOptions().CPlusPlus) {
5095      // FIXME: Look for a way to use RecordDecl for simple structs.
5096      New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5097                                  cast_or_null<CXXRecordDecl>(PrevDecl));
5098
5099      if (isStdBadAlloc && (!StdBadAlloc || StdBadAlloc->isImplicit()))
5100        StdBadAlloc = cast<CXXRecordDecl>(New);
5101    } else
5102      New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name, KWLoc,
5103                               cast_or_null<RecordDecl>(PrevDecl));
5104  }
5105
5106  // Maybe add qualifier info.
5107  if (SS.isNotEmpty()) {
5108    NestedNameSpecifier *NNS
5109      = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5110    New->setQualifierInfo(NNS, SS.getRange());
5111  }
5112
5113  if (Kind != TagDecl::TK_enum) {
5114    // Handle #pragma pack: if the #pragma pack stack has non-default
5115    // alignment, make up a packed attribute for this decl. These
5116    // attributes are checked when the ASTContext lays out the
5117    // structure.
5118    //
5119    // It is important for implementing the correct semantics that this
5120    // happen here (in act on tag decl). The #pragma pack stack is
5121    // maintained as a result of parser callbacks which can occur at
5122    // many points during the parsing of a struct declaration (because
5123    // the #pragma tokens are effectively skipped over during the
5124    // parsing of the struct).
5125    if (unsigned Alignment = getPragmaPackAlignment())
5126      New->addAttr(::new (Context) PragmaPackAttr(Alignment * 8));
5127  }
5128
5129  if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
5130    // C++ [dcl.typedef]p3:
5131    //   [...] Similarly, in a given scope, a class or enumeration
5132    //   shall not be declared with the same name as a typedef-name
5133    //   that is declared in that scope and refers to a type other
5134    //   than the class or enumeration itself.
5135    LookupResult Lookup(*this, Name, NameLoc, LookupOrdinaryName,
5136                        ForRedeclaration);
5137    LookupName(Lookup, S);
5138    TypedefDecl *PrevTypedef = Lookup.getAsSingle<TypedefDecl>();
5139    NamedDecl *PrevTypedefNamed = PrevTypedef;
5140    if (PrevTypedef && isDeclInScope(PrevTypedefNamed, SearchDC, S) &&
5141        Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
5142          Context.getCanonicalType(Context.getTypeDeclType(New))) {
5143      Diag(Loc, diag::err_tag_definition_of_typedef)
5144        << Context.getTypeDeclType(New)
5145        << PrevTypedef->getUnderlyingType();
5146      Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
5147      Invalid = true;
5148    }
5149  }
5150
5151  // If this is a specialization of a member class (of a class template),
5152  // check the specialization.
5153  if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
5154    Invalid = true;
5155
5156  if (Invalid)
5157    New->setInvalidDecl();
5158
5159  if (Attr)
5160    ProcessDeclAttributeList(S, New, Attr);
5161
5162  // If we're declaring or defining a tag in function prototype scope
5163  // in C, note that this type can only be used within the function.
5164  if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
5165    Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
5166
5167  // Set the lexical context. If the tag has a C++ scope specifier, the
5168  // lexical context will be different from the semantic context.
5169  New->setLexicalDeclContext(CurContext);
5170
5171  // Mark this as a friend decl if applicable.
5172  if (TUK == TUK_Friend)
5173    New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty());
5174
5175  // Set the access specifier.
5176  if (!Invalid && SearchDC->isRecord())
5177    SetMemberAccessSpecifier(New, PrevDecl, AS);
5178
5179  if (TUK == TUK_Definition)
5180    New->startDefinition();
5181
5182  // If this has an identifier, add it to the scope stack.
5183  if (TUK == TUK_Friend) {
5184    // We might be replacing an existing declaration in the lookup tables;
5185    // if so, borrow its access specifier.
5186    if (PrevDecl)
5187      New->setAccess(PrevDecl->getAccess());
5188
5189    DeclContext *DC = New->getDeclContext()->getLookupContext();
5190    DC->makeDeclVisibleInContext(New, /* Recoverable = */ false);
5191    if (Name) // can be null along some error paths
5192      if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
5193        PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
5194  } else if (Name) {
5195    S = getNonFieldDeclScope(S);
5196    PushOnScopeChains(New, S);
5197  } else {
5198    CurContext->addDecl(New);
5199  }
5200
5201  // If this is the C FILE type, notify the AST context.
5202  if (IdentifierInfo *II = New->getIdentifier())
5203    if (!New->isInvalidDecl() &&
5204        New->getDeclContext()->getLookupContext()->isTranslationUnit() &&
5205        II->isStr("FILE"))
5206      Context.setFILEDecl(New);
5207
5208  OwnedDecl = true;
5209  return DeclPtrTy::make(New);
5210}
5211
5212void Sema::ActOnTagStartDefinition(Scope *S, DeclPtrTy TagD) {
5213  AdjustDeclIfTemplate(TagD);
5214  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5215
5216  // Enter the tag context.
5217  PushDeclContext(S, Tag);
5218}
5219
5220void Sema::ActOnStartCXXMemberDeclarations(Scope *S, DeclPtrTy TagD,
5221                                           SourceLocation LBraceLoc) {
5222  AdjustDeclIfTemplate(TagD);
5223  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD.getAs<Decl>());
5224
5225  FieldCollector->StartClass();
5226
5227  if (!Record->getIdentifier())
5228    return;
5229
5230  // C++ [class]p2:
5231  //   [...] The class-name is also inserted into the scope of the
5232  //   class itself; this is known as the injected-class-name. For
5233  //   purposes of access checking, the injected-class-name is treated
5234  //   as if it were a public member name.
5235  CXXRecordDecl *InjectedClassName
5236    = CXXRecordDecl::Create(Context, Record->getTagKind(),
5237                            CurContext, Record->getLocation(),
5238                            Record->getIdentifier(),
5239                            Record->getTagKeywordLoc(),
5240                            Record);
5241  InjectedClassName->setImplicit();
5242  InjectedClassName->setAccess(AS_public);
5243  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
5244      InjectedClassName->setDescribedClassTemplate(Template);
5245  PushOnScopeChains(InjectedClassName, S);
5246  assert(InjectedClassName->isInjectedClassName() &&
5247         "Broken injected-class-name");
5248}
5249
5250// Traverses the class and any nested classes, making a note of any
5251// dynamic classes that have no key function so that we can mark all of
5252// their virtual member functions as "used" at the end of the translation
5253// unit. This ensures that all functions needed by the vtable will get
5254// instantiated/synthesized.
5255static void
5256RecordDynamicClassesWithNoKeyFunction(Sema &S, CXXRecordDecl *Record,
5257                                      SourceLocation Loc) {
5258  // We don't look at dependent or undefined classes.
5259  if (Record->isDependentContext() || !Record->isDefinition())
5260    return;
5261
5262  if (Record->isDynamicClass()) {
5263    const CXXMethodDecl *KeyFunction = S.Context.getKeyFunction(Record);
5264
5265    if (!KeyFunction)
5266      S.ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(Record,
5267                                                                   Loc));
5268
5269    if ((!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
5270        && Record->getLinkage() == ExternalLinkage)
5271      S.Diag(Record->getLocation(), diag::warn_weak_vtable) << Record;
5272  }
5273  for (DeclContext::decl_iterator D = Record->decls_begin(),
5274                               DEnd = Record->decls_end();
5275       D != DEnd; ++D) {
5276    if (CXXRecordDecl *Nested = dyn_cast<CXXRecordDecl>(*D))
5277      RecordDynamicClassesWithNoKeyFunction(S, Nested, Loc);
5278  }
5279}
5280
5281void Sema::ActOnTagFinishDefinition(Scope *S, DeclPtrTy TagD,
5282                                    SourceLocation RBraceLoc) {
5283  AdjustDeclIfTemplate(TagD);
5284  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5285  Tag->setRBraceLoc(RBraceLoc);
5286
5287  if (isa<CXXRecordDecl>(Tag))
5288    FieldCollector->FinishClass();
5289
5290  // Exit this scope of this tag's definition.
5291  PopDeclContext();
5292
5293  if (isa<CXXRecordDecl>(Tag) && !Tag->getLexicalDeclContext()->isRecord())
5294    RecordDynamicClassesWithNoKeyFunction(*this, cast<CXXRecordDecl>(Tag),
5295                                          RBraceLoc);
5296
5297  // Notify the consumer that we've defined a tag.
5298  Consumer.HandleTagDeclDefinition(Tag);
5299}
5300
5301void Sema::ActOnTagDefinitionError(Scope *S, DeclPtrTy TagD) {
5302  AdjustDeclIfTemplate(TagD);
5303  TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
5304  Tag->setInvalidDecl();
5305
5306  // We're undoing ActOnTagStartDefinition here, not
5307  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
5308  // the FieldCollector.
5309
5310  PopDeclContext();
5311}
5312
5313// Note that FieldName may be null for anonymous bitfields.
5314bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
5315                          QualType FieldTy, const Expr *BitWidth,
5316                          bool *ZeroWidth) {
5317  // Default to true; that shouldn't confuse checks for emptiness
5318  if (ZeroWidth)
5319    *ZeroWidth = true;
5320
5321  // C99 6.7.2.1p4 - verify the field type.
5322  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
5323  if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
5324    // Handle incomplete types with specific error.
5325    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
5326      return true;
5327    if (FieldName)
5328      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
5329        << FieldName << FieldTy << BitWidth->getSourceRange();
5330    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
5331      << FieldTy << BitWidth->getSourceRange();
5332  }
5333
5334  // If the bit-width is type- or value-dependent, don't try to check
5335  // it now.
5336  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
5337    return false;
5338
5339  llvm::APSInt Value;
5340  if (VerifyIntegerConstantExpression(BitWidth, &Value))
5341    return true;
5342
5343  if (Value != 0 && ZeroWidth)
5344    *ZeroWidth = false;
5345
5346  // Zero-width bitfield is ok for anonymous field.
5347  if (Value == 0 && FieldName)
5348    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
5349
5350  if (Value.isSigned() && Value.isNegative()) {
5351    if (FieldName)
5352      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
5353               << FieldName << Value.toString(10);
5354    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
5355      << Value.toString(10);
5356  }
5357
5358  if (!FieldTy->isDependentType()) {
5359    uint64_t TypeSize = Context.getTypeSize(FieldTy);
5360    if (Value.getZExtValue() > TypeSize) {
5361      if (FieldName)
5362        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
5363          << FieldName << (unsigned)TypeSize;
5364      return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size)
5365        << (unsigned)TypeSize;
5366    }
5367  }
5368
5369  return false;
5370}
5371
5372/// ActOnField - Each field of a struct/union/class is passed into this in order
5373/// to create a FieldDecl object for it.
5374Sema::DeclPtrTy Sema::ActOnField(Scope *S, DeclPtrTy TagD,
5375                                 SourceLocation DeclStart,
5376                                 Declarator &D, ExprTy *BitfieldWidth) {
5377  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD.getAs<Decl>()),
5378                               DeclStart, D, static_cast<Expr*>(BitfieldWidth),
5379                               AS_public);
5380  return DeclPtrTy::make(Res);
5381}
5382
5383/// HandleField - Analyze a field of a C struct or a C++ data member.
5384///
5385FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
5386                             SourceLocation DeclStart,
5387                             Declarator &D, Expr *BitWidth,
5388                             AccessSpecifier AS) {
5389  IdentifierInfo *II = D.getIdentifier();
5390  SourceLocation Loc = DeclStart;
5391  if (II) Loc = D.getIdentifierLoc();
5392
5393  TypeSourceInfo *TInfo = 0;
5394  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5395  if (getLangOptions().CPlusPlus)
5396    CheckExtraCXXDefaultArguments(D);
5397
5398  DiagnoseFunctionSpecifiers(D);
5399
5400  if (D.getDeclSpec().isThreadSpecified())
5401    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
5402
5403  NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5404                                         ForRedeclaration);
5405
5406  if (PrevDecl && PrevDecl->isTemplateParameter()) {
5407    // Maybe we will complain about the shadowed template parameter.
5408    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
5409    // Just pretend that we didn't see the previous declaration.
5410    PrevDecl = 0;
5411  }
5412
5413  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
5414    PrevDecl = 0;
5415
5416  bool Mutable
5417    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
5418  SourceLocation TSSL = D.getSourceRange().getBegin();
5419  FieldDecl *NewFD
5420    = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, TSSL,
5421                     AS, PrevDecl, &D);
5422
5423  if (NewFD->isInvalidDecl())
5424    Record->setInvalidDecl();
5425
5426  if (NewFD->isInvalidDecl() && PrevDecl) {
5427    // Don't introduce NewFD into scope; there's already something
5428    // with the same name in the same scope.
5429  } else if (II) {
5430    PushOnScopeChains(NewFD, S);
5431  } else
5432    Record->addDecl(NewFD);
5433
5434  return NewFD;
5435}
5436
5437/// \brief Build a new FieldDecl and check its well-formedness.
5438///
5439/// This routine builds a new FieldDecl given the fields name, type,
5440/// record, etc. \p PrevDecl should refer to any previous declaration
5441/// with the same name and in the same scope as the field to be
5442/// created.
5443///
5444/// \returns a new FieldDecl.
5445///
5446/// \todo The Declarator argument is a hack. It will be removed once
5447FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
5448                                TypeSourceInfo *TInfo,
5449                                RecordDecl *Record, SourceLocation Loc,
5450                                bool Mutable, Expr *BitWidth,
5451                                SourceLocation TSSL,
5452                                AccessSpecifier AS, NamedDecl *PrevDecl,
5453                                Declarator *D) {
5454  IdentifierInfo *II = Name.getAsIdentifierInfo();
5455  bool InvalidDecl = false;
5456  if (D) InvalidDecl = D->isInvalidType();
5457
5458  // If we receive a broken type, recover by assuming 'int' and
5459  // marking this declaration as invalid.
5460  if (T.isNull()) {
5461    InvalidDecl = true;
5462    T = Context.IntTy;
5463  }
5464
5465  QualType EltTy = Context.getBaseElementType(T);
5466  if (!EltTy->isDependentType() &&
5467      RequireCompleteType(Loc, EltTy, diag::err_field_incomplete))
5468    InvalidDecl = true;
5469
5470  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5471  // than a variably modified type.
5472  if (!InvalidDecl && T->isVariablyModifiedType()) {
5473    bool SizeIsNegative;
5474    QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
5475                                                           SizeIsNegative);
5476    if (!FixedTy.isNull()) {
5477      Diag(Loc, diag::warn_illegal_constant_array_size);
5478      T = FixedTy;
5479    } else {
5480      if (SizeIsNegative)
5481        Diag(Loc, diag::err_typecheck_negative_array_size);
5482      else
5483        Diag(Loc, diag::err_typecheck_field_variable_size);
5484      InvalidDecl = true;
5485    }
5486  }
5487
5488  // Fields can not have abstract class types
5489  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
5490                                             diag::err_abstract_type_in_decl,
5491                                             AbstractFieldType))
5492    InvalidDecl = true;
5493
5494  bool ZeroWidth = false;
5495  // If this is declared as a bit-field, check the bit-field.
5496  if (!InvalidDecl && BitWidth &&
5497      VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth)) {
5498    InvalidDecl = true;
5499    DeleteExpr(BitWidth);
5500    BitWidth = 0;
5501    ZeroWidth = false;
5502  }
5503
5504  FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, TInfo,
5505                                       BitWidth, Mutable);
5506  if (InvalidDecl)
5507    NewFD->setInvalidDecl();
5508
5509  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
5510    Diag(Loc, diag::err_duplicate_member) << II;
5511    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5512    NewFD->setInvalidDecl();
5513  }
5514
5515  if (!InvalidDecl && getLangOptions().CPlusPlus) {
5516    CXXRecordDecl* CXXRecord = cast<CXXRecordDecl>(Record);
5517
5518    if (!T->isPODType())
5519      CXXRecord->setPOD(false);
5520    if (!ZeroWidth)
5521      CXXRecord->setEmpty(false);
5522
5523    if (const RecordType *RT = EltTy->getAs<RecordType>()) {
5524      CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
5525
5526      if (!RDecl->hasTrivialConstructor())
5527        CXXRecord->setHasTrivialConstructor(false);
5528      if (!RDecl->hasTrivialCopyConstructor())
5529        CXXRecord->setHasTrivialCopyConstructor(false);
5530      if (!RDecl->hasTrivialCopyAssignment())
5531        CXXRecord->setHasTrivialCopyAssignment(false);
5532      if (!RDecl->hasTrivialDestructor())
5533        CXXRecord->setHasTrivialDestructor(false);
5534
5535      // C++ 9.5p1: An object of a class with a non-trivial
5536      // constructor, a non-trivial copy constructor, a non-trivial
5537      // destructor, or a non-trivial copy assignment operator
5538      // cannot be a member of a union, nor can an array of such
5539      // objects.
5540      // TODO: C++0x alters this restriction significantly.
5541      if (Record->isUnion()) {
5542        // We check for copy constructors before constructors
5543        // because otherwise we'll never get complaints about
5544        // copy constructors.
5545
5546        const CXXSpecialMember invalid = (CXXSpecialMember) -1;
5547
5548        CXXSpecialMember member;
5549        if (!RDecl->hasTrivialCopyConstructor())
5550          member = CXXCopyConstructor;
5551        else if (!RDecl->hasTrivialConstructor())
5552          member = CXXDefaultConstructor;
5553        else if (!RDecl->hasTrivialCopyAssignment())
5554          member = CXXCopyAssignment;
5555        else if (!RDecl->hasTrivialDestructor())
5556          member = CXXDestructor;
5557        else
5558          member = invalid;
5559
5560        if (member != invalid) {
5561          Diag(Loc, diag::err_illegal_union_member) << Name << member;
5562          DiagnoseNontrivial(RT, member);
5563          NewFD->setInvalidDecl();
5564        }
5565      }
5566    }
5567  }
5568
5569  // FIXME: We need to pass in the attributes given an AST
5570  // representation, not a parser representation.
5571  if (D)
5572    // FIXME: What to pass instead of TUScope?
5573    ProcessDeclAttributes(TUScope, NewFD, *D);
5574
5575  if (T.isObjCGCWeak())
5576    Diag(Loc, diag::warn_attribute_weak_on_field);
5577
5578  NewFD->setAccess(AS);
5579
5580  // C++ [dcl.init.aggr]p1:
5581  //   An aggregate is an array or a class (clause 9) with [...] no
5582  //   private or protected non-static data members (clause 11).
5583  // A POD must be an aggregate.
5584  if (getLangOptions().CPlusPlus &&
5585      (AS == AS_private || AS == AS_protected)) {
5586    CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
5587    CXXRecord->setAggregate(false);
5588    CXXRecord->setPOD(false);
5589  }
5590
5591  return NewFD;
5592}
5593
5594/// DiagnoseNontrivial - Given that a class has a non-trivial
5595/// special member, figure out why.
5596void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) {
5597  QualType QT(T, 0U);
5598  CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl());
5599
5600  // Check whether the member was user-declared.
5601  switch (member) {
5602  case CXXDefaultConstructor:
5603    if (RD->hasUserDeclaredConstructor()) {
5604      typedef CXXRecordDecl::ctor_iterator ctor_iter;
5605      for (ctor_iter ci = RD->ctor_begin(), ce = RD->ctor_end(); ci != ce;++ci){
5606        const FunctionDecl *body = 0;
5607        ci->getBody(body);
5608        if (!body ||
5609            !cast<CXXConstructorDecl>(body)->isImplicitlyDefined(Context)) {
5610          SourceLocation CtorLoc = ci->getLocation();
5611          Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5612          return;
5613        }
5614      }
5615
5616      assert(0 && "found no user-declared constructors");
5617      return;
5618    }
5619    break;
5620
5621  case CXXCopyConstructor:
5622    if (RD->hasUserDeclaredCopyConstructor()) {
5623      SourceLocation CtorLoc =
5624        RD->getCopyConstructor(Context, 0)->getLocation();
5625      Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5626      return;
5627    }
5628    break;
5629
5630  case CXXCopyAssignment:
5631    if (RD->hasUserDeclaredCopyAssignment()) {
5632      // FIXME: this should use the location of the copy
5633      // assignment, not the type.
5634      SourceLocation TyLoc = RD->getSourceRange().getBegin();
5635      Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member;
5636      return;
5637    }
5638    break;
5639
5640  case CXXDestructor:
5641    if (RD->hasUserDeclaredDestructor()) {
5642      SourceLocation DtorLoc = RD->getDestructor(Context)->getLocation();
5643      Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member;
5644      return;
5645    }
5646    break;
5647  }
5648
5649  typedef CXXRecordDecl::base_class_iterator base_iter;
5650
5651  // Virtual bases and members inhibit trivial copying/construction,
5652  // but not trivial destruction.
5653  if (member != CXXDestructor) {
5654    // Check for virtual bases.  vbases includes indirect virtual bases,
5655    // so we just iterate through the direct bases.
5656    for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi)
5657      if (bi->isVirtual()) {
5658        SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5659        Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1;
5660        return;
5661      }
5662
5663    // Check for virtual methods.
5664    typedef CXXRecordDecl::method_iterator meth_iter;
5665    for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me;
5666         ++mi) {
5667      if (mi->isVirtual()) {
5668        SourceLocation MLoc = mi->getSourceRange().getBegin();
5669        Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0;
5670        return;
5671      }
5672    }
5673  }
5674
5675  bool (CXXRecordDecl::*hasTrivial)() const;
5676  switch (member) {
5677  case CXXDefaultConstructor:
5678    hasTrivial = &CXXRecordDecl::hasTrivialConstructor; break;
5679  case CXXCopyConstructor:
5680    hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break;
5681  case CXXCopyAssignment:
5682    hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break;
5683  case CXXDestructor:
5684    hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break;
5685  default:
5686    assert(0 && "unexpected special member"); return;
5687  }
5688
5689  // Check for nontrivial bases (and recurse).
5690  for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) {
5691    const RecordType *BaseRT = bi->getType()->getAs<RecordType>();
5692    assert(BaseRT && "Don't know how to handle dependent bases");
5693    CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl());
5694    if (!(BaseRecTy->*hasTrivial)()) {
5695      SourceLocation BaseLoc = bi->getSourceRange().getBegin();
5696      Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member;
5697      DiagnoseNontrivial(BaseRT, member);
5698      return;
5699    }
5700  }
5701
5702  // Check for nontrivial members (and recurse).
5703  typedef RecordDecl::field_iterator field_iter;
5704  for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe;
5705       ++fi) {
5706    QualType EltTy = Context.getBaseElementType((*fi)->getType());
5707    if (const RecordType *EltRT = EltTy->getAs<RecordType>()) {
5708      CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl());
5709
5710      if (!(EltRD->*hasTrivial)()) {
5711        SourceLocation FLoc = (*fi)->getLocation();
5712        Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member;
5713        DiagnoseNontrivial(EltRT, member);
5714        return;
5715      }
5716    }
5717  }
5718
5719  assert(0 && "found no explanation for non-trivial member");
5720}
5721
5722/// TranslateIvarVisibility - Translate visibility from a token ID to an
5723///  AST enum value.
5724static ObjCIvarDecl::AccessControl
5725TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5726  switch (ivarVisibility) {
5727  default: assert(0 && "Unknown visitibility kind");
5728  case tok::objc_private: return ObjCIvarDecl::Private;
5729  case tok::objc_public: return ObjCIvarDecl::Public;
5730  case tok::objc_protected: return ObjCIvarDecl::Protected;
5731  case tok::objc_package: return ObjCIvarDecl::Package;
5732  }
5733}
5734
5735/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5736/// in order to create an IvarDecl object for it.
5737Sema::DeclPtrTy Sema::ActOnIvar(Scope *S,
5738                                SourceLocation DeclStart,
5739                                DeclPtrTy IntfDecl,
5740                                Declarator &D, ExprTy *BitfieldWidth,
5741                                tok::ObjCKeywordKind Visibility) {
5742
5743  IdentifierInfo *II = D.getIdentifier();
5744  Expr *BitWidth = (Expr*)BitfieldWidth;
5745  SourceLocation Loc = DeclStart;
5746  if (II) Loc = D.getIdentifierLoc();
5747
5748  // FIXME: Unnamed fields can be handled in various different ways, for
5749  // example, unnamed unions inject all members into the struct namespace!
5750
5751  TypeSourceInfo *TInfo = 0;
5752  QualType T = GetTypeForDeclarator(D, S, &TInfo);
5753
5754  if (BitWidth) {
5755    // 6.7.2.1p3, 6.7.2.1p4
5756    if (VerifyBitField(Loc, II, T, BitWidth)) {
5757      D.setInvalidType();
5758      DeleteExpr(BitWidth);
5759      BitWidth = 0;
5760    }
5761  } else {
5762    // Not a bitfield.
5763
5764    // validate II.
5765
5766  }
5767
5768  // C99 6.7.2.1p8: A member of a structure or union may have any type other
5769  // than a variably modified type.
5770  if (T->isVariablyModifiedType()) {
5771    Diag(Loc, diag::err_typecheck_ivar_variable_size);
5772    D.setInvalidType();
5773  }
5774
5775  // Get the visibility (access control) for this ivar.
5776  ObjCIvarDecl::AccessControl ac =
5777    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
5778                                        : ObjCIvarDecl::None;
5779  // Must set ivar's DeclContext to its enclosing interface.
5780  ObjCContainerDecl *EnclosingDecl = IntfDecl.getAs<ObjCContainerDecl>();
5781  ObjCContainerDecl *EnclosingContext;
5782  if (ObjCImplementationDecl *IMPDecl =
5783      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5784    // Case of ivar declared in an implementation. Context is that of its class.
5785    EnclosingContext = IMPDecl->getClassInterface();
5786    assert(EnclosingContext && "Implementation has no class interface!");
5787  } else {
5788    if (ObjCCategoryDecl *CDecl =
5789        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
5790      if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) {
5791        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
5792        return DeclPtrTy();
5793      }
5794    }
5795    EnclosingContext = EnclosingDecl;
5796  }
5797
5798  // Construct the decl.
5799  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context,
5800                                             EnclosingContext, Loc, II, T,
5801                                             TInfo, ac, (Expr *)BitfieldWidth);
5802
5803  if (II) {
5804    NamedDecl *PrevDecl = LookupSingleName(S, II, LookupMemberName,
5805                                           ForRedeclaration);
5806    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
5807        && !isa<TagDecl>(PrevDecl)) {
5808      Diag(Loc, diag::err_duplicate_member) << II;
5809      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5810      NewID->setInvalidDecl();
5811    }
5812  }
5813
5814  // Process attributes attached to the ivar.
5815  ProcessDeclAttributes(S, NewID, D);
5816
5817  if (D.isInvalidType())
5818    NewID->setInvalidDecl();
5819
5820  if (II) {
5821    // FIXME: When interfaces are DeclContexts, we'll need to add
5822    // these to the interface.
5823    S->AddDecl(DeclPtrTy::make(NewID));
5824    IdResolver.AddDecl(NewID);
5825  }
5826
5827  return DeclPtrTy::make(NewID);
5828}
5829
5830void Sema::ActOnFields(Scope* S,
5831                       SourceLocation RecLoc, DeclPtrTy RecDecl,
5832                       DeclPtrTy *Fields, unsigned NumFields,
5833                       SourceLocation LBrac, SourceLocation RBrac,
5834                       AttributeList *Attr) {
5835  Decl *EnclosingDecl = RecDecl.getAs<Decl>();
5836  assert(EnclosingDecl && "missing record or interface decl");
5837
5838  // If the decl this is being inserted into is invalid, then it may be a
5839  // redeclaration or some other bogus case.  Don't try to add fields to it.
5840  if (EnclosingDecl->isInvalidDecl()) {
5841    // FIXME: Deallocate fields?
5842    return;
5843  }
5844
5845
5846  // Verify that all the fields are okay.
5847  unsigned NumNamedMembers = 0;
5848  llvm::SmallVector<FieldDecl*, 32> RecFields;
5849
5850  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
5851  for (unsigned i = 0; i != NumFields; ++i) {
5852    FieldDecl *FD = cast<FieldDecl>(Fields[i].getAs<Decl>());
5853
5854    // Get the type for the field.
5855    Type *FDTy = FD->getType().getTypePtr();
5856
5857    if (!FD->isAnonymousStructOrUnion()) {
5858      // Remember all fields written by the user.
5859      RecFields.push_back(FD);
5860    }
5861
5862    // If the field is already invalid for some reason, don't emit more
5863    // diagnostics about it.
5864    if (FD->isInvalidDecl()) {
5865      EnclosingDecl->setInvalidDecl();
5866      continue;
5867    }
5868
5869    // C99 6.7.2.1p2:
5870    //   A structure or union shall not contain a member with
5871    //   incomplete or function type (hence, a structure shall not
5872    //   contain an instance of itself, but may contain a pointer to
5873    //   an instance of itself), except that the last member of a
5874    //   structure with more than one named member may have incomplete
5875    //   array type; such a structure (and any union containing,
5876    //   possibly recursively, a member that is such a structure)
5877    //   shall not be a member of a structure or an element of an
5878    //   array.
5879    if (FDTy->isFunctionType()) {
5880      // Field declared as a function.
5881      Diag(FD->getLocation(), diag::err_field_declared_as_function)
5882        << FD->getDeclName();
5883      FD->setInvalidDecl();
5884      EnclosingDecl->setInvalidDecl();
5885      continue;
5886    } else if (FDTy->isIncompleteArrayType() && i == NumFields - 1 &&
5887               Record && Record->isStruct()) {
5888      // Flexible array member.
5889      if (NumNamedMembers < 1) {
5890        Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
5891          << FD->getDeclName();
5892        FD->setInvalidDecl();
5893        EnclosingDecl->setInvalidDecl();
5894        continue;
5895      }
5896      // Okay, we have a legal flexible array member at the end of the struct.
5897      if (Record)
5898        Record->setHasFlexibleArrayMember(true);
5899    } else if (!FDTy->isDependentType() &&
5900               RequireCompleteType(FD->getLocation(), FD->getType(),
5901                                   diag::err_field_incomplete)) {
5902      // Incomplete type
5903      FD->setInvalidDecl();
5904      EnclosingDecl->setInvalidDecl();
5905      continue;
5906    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
5907      if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
5908        // If this is a member of a union, then entire union becomes "flexible".
5909        if (Record && Record->isUnion()) {
5910          Record->setHasFlexibleArrayMember(true);
5911        } else {
5912          // If this is a struct/class and this is not the last element, reject
5913          // it.  Note that GCC supports variable sized arrays in the middle of
5914          // structures.
5915          if (i != NumFields-1)
5916            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
5917              << FD->getDeclName() << FD->getType();
5918          else {
5919            // We support flexible arrays at the end of structs in
5920            // other structs as an extension.
5921            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
5922              << FD->getDeclName();
5923            if (Record)
5924              Record->setHasFlexibleArrayMember(true);
5925          }
5926        }
5927      }
5928      if (Record && FDTTy->getDecl()->hasObjectMember())
5929        Record->setHasObjectMember(true);
5930    } else if (FDTy->isObjCInterfaceType()) {
5931      /// A field cannot be an Objective-c object
5932      Diag(FD->getLocation(), diag::err_statically_allocated_object);
5933      FD->setInvalidDecl();
5934      EnclosingDecl->setInvalidDecl();
5935      continue;
5936    } else if (getLangOptions().ObjC1 &&
5937               getLangOptions().getGCMode() != LangOptions::NonGC &&
5938               Record &&
5939               (FD->getType()->isObjCObjectPointerType() ||
5940                FD->getType().isObjCGCStrong()))
5941      Record->setHasObjectMember(true);
5942    // Keep track of the number of named members.
5943    if (FD->getIdentifier())
5944      ++NumNamedMembers;
5945  }
5946
5947  // Okay, we successfully defined 'Record'.
5948  if (Record) {
5949    Record->completeDefinition();
5950  } else {
5951    ObjCIvarDecl **ClsFields =
5952      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
5953    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
5954      ID->setLocEnd(RBrac);
5955      // Add ivar's to class's DeclContext.
5956      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5957        ClsFields[i]->setLexicalDeclContext(ID);
5958        ID->addDecl(ClsFields[i]);
5959      }
5960      // Must enforce the rule that ivars in the base classes may not be
5961      // duplicates.
5962      if (ID->getSuperClass())
5963        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
5964    } else if (ObjCImplementationDecl *IMPDecl =
5965                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5966      assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
5967      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
5968        // Ivar declared in @implementation never belongs to the implementation.
5969        // Only it is in implementation's lexical context.
5970        ClsFields[I]->setLexicalDeclContext(IMPDecl);
5971      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
5972    } else if (ObjCCategoryDecl *CDecl =
5973                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
5974      // case of ivars in class extension; all other cases have been
5975      // reported as errors elsewhere.
5976      // FIXME. Class extension does not have a LocEnd field.
5977      // CDecl->setLocEnd(RBrac);
5978      // Add ivar's to class extension's DeclContext.
5979      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
5980        ClsFields[i]->setLexicalDeclContext(CDecl);
5981        CDecl->addDecl(ClsFields[i]);
5982      }
5983    }
5984  }
5985
5986  if (Attr)
5987    ProcessDeclAttributeList(S, Record, Attr);
5988}
5989
5990/// \brief Determine whether the given integral value is representable within
5991/// the given type T.
5992static bool isRepresentableIntegerValue(ASTContext &Context,
5993                                        llvm::APSInt &Value,
5994                                        QualType T) {
5995  assert(T->isIntegralType() && "Integral type required!");
5996  unsigned BitWidth = Context.getTypeSize(T);
5997
5998  if (Value.isUnsigned() || Value.isNonNegative())
5999    return Value.getActiveBits() < BitWidth;
6000
6001  return Value.getMinSignedBits() <= BitWidth;
6002}
6003
6004// \brief Given an integral type, return the next larger integral type
6005// (or a NULL type of no such type exists).
6006static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
6007  // FIXME: Int128/UInt128 support, which also needs to be introduced into
6008  // enum checking below.
6009  assert(T->isIntegralType() && "Integral type required!");
6010  const unsigned NumTypes = 4;
6011  QualType SignedIntegralTypes[NumTypes] = {
6012    Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
6013  };
6014  QualType UnsignedIntegralTypes[NumTypes] = {
6015    Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
6016    Context.UnsignedLongLongTy
6017  };
6018
6019  unsigned BitWidth = Context.getTypeSize(T);
6020  QualType *Types = T->isSignedIntegerType()? SignedIntegralTypes
6021                                            : UnsignedIntegralTypes;
6022  for (unsigned I = 0; I != NumTypes; ++I)
6023    if (Context.getTypeSize(Types[I]) > BitWidth)
6024      return Types[I];
6025
6026  return QualType();
6027}
6028
6029EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
6030                                          EnumConstantDecl *LastEnumConst,
6031                                          SourceLocation IdLoc,
6032                                          IdentifierInfo *Id,
6033                                          ExprArg val) {
6034  Expr *Val = (Expr *)val.get();
6035
6036  unsigned IntWidth = Context.Target.getIntWidth();
6037  llvm::APSInt EnumVal(IntWidth);
6038  QualType EltTy;
6039  if (Val) {
6040    if (Enum->isDependentType() || Val->isTypeDependent())
6041      EltTy = Context.DependentTy;
6042    else {
6043      // C99 6.7.2.2p2: Make sure we have an integer constant expression.
6044      SourceLocation ExpLoc;
6045      if (!Val->isValueDependent() &&
6046          VerifyIntegerConstantExpression(Val, &EnumVal)) {
6047        Val = 0;
6048      } else {
6049        if (!getLangOptions().CPlusPlus) {
6050          // C99 6.7.2.2p2:
6051          //   The expression that defines the value of an enumeration constant
6052          //   shall be an integer constant expression that has a value
6053          //   representable as an int.
6054
6055          // Complain if the value is not representable in an int.
6056          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
6057            Diag(IdLoc, diag::ext_enum_value_not_int)
6058              << EnumVal.toString(10) << Val->getSourceRange()
6059              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
6060          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
6061            // Force the type of the expression to 'int'.
6062            ImpCastExprToType(Val, Context.IntTy, CastExpr::CK_IntegralCast);
6063
6064            if (Val != val.get()) {
6065              val.release();
6066              val = Val;
6067            }
6068          }
6069        }
6070
6071        // C++0x [dcl.enum]p5:
6072        //   If the underlying type is not fixed, the type of each enumerator
6073        //   is the type of its initializing value:
6074        //     - If an initializer is specified for an enumerator, the
6075        //       initializing value has the same type as the expression.
6076        EltTy = Val->getType();
6077      }
6078    }
6079  }
6080
6081  if (!Val) {
6082    if (Enum->isDependentType())
6083      EltTy = Context.DependentTy;
6084    else if (!LastEnumConst) {
6085      // C++0x [dcl.enum]p5:
6086      //   If the underlying type is not fixed, the type of each enumerator
6087      //   is the type of its initializing value:
6088      //     - If no initializer is specified for the first enumerator, the
6089      //       initializing value has an unspecified integral type.
6090      //
6091      // GCC uses 'int' for its unspecified integral type, as does
6092      // C99 6.7.2.2p3.
6093      EltTy = Context.IntTy;
6094    } else {
6095      // Assign the last value + 1.
6096      EnumVal = LastEnumConst->getInitVal();
6097      ++EnumVal;
6098      EltTy = LastEnumConst->getType();
6099
6100      // Check for overflow on increment.
6101      if (EnumVal < LastEnumConst->getInitVal()) {
6102        // C++0x [dcl.enum]p5:
6103        //   If the underlying type is not fixed, the type of each enumerator
6104        //   is the type of its initializing value:
6105        //
6106        //     - Otherwise the type of the initializing value is the same as
6107        //       the type of the initializing value of the preceding enumerator
6108        //       unless the incremented value is not representable in that type,
6109        //       in which case the type is an unspecified integral type
6110        //       sufficient to contain the incremented value. If no such type
6111        //       exists, the program is ill-formed.
6112        QualType T = getNextLargerIntegralType(Context, EltTy);
6113        if (T.isNull()) {
6114          // There is no integral type larger enough to represent this
6115          // value. Complain, then allow the value to wrap around.
6116          EnumVal = LastEnumConst->getInitVal();
6117          EnumVal.zext(EnumVal.getBitWidth() * 2);
6118          Diag(IdLoc, diag::warn_enumerator_too_large)
6119            << EnumVal.toString(10);
6120        } else {
6121          EltTy = T;
6122        }
6123
6124        // Retrieve the last enumerator's value, extent that type to the
6125        // type that is supposed to be large enough to represent the incremented
6126        // value, then increment.
6127        EnumVal = LastEnumConst->getInitVal();
6128        EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6129        EnumVal.zextOrTrunc(Context.getTypeSize(EltTy));
6130        ++EnumVal;
6131
6132        // If we're not in C++, diagnose the overflow of enumerator values,
6133        // which in C99 means that the enumerator value is not representable in
6134        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
6135        // permits enumerator values that are representable in some larger
6136        // integral type.
6137        if (!getLangOptions().CPlusPlus && !T.isNull())
6138          Diag(IdLoc, diag::warn_enum_value_overflow);
6139      } else if (!getLangOptions().CPlusPlus &&
6140                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
6141        // Enforce C99 6.7.2.2p2 even when we compute the next value.
6142        Diag(IdLoc, diag::ext_enum_value_not_int)
6143          << EnumVal.toString(10) << 1;
6144      }
6145    }
6146  }
6147
6148  if (!EltTy->isDependentType()) {
6149    // Make the enumerator value match the signedness and size of the
6150    // enumerator's type.
6151    EnumVal.zextOrTrunc(Context.getTypeSize(EltTy));
6152    EnumVal.setIsSigned(EltTy->isSignedIntegerType());
6153  }
6154
6155  val.release();
6156  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
6157                                  Val, EnumVal);
6158}
6159
6160
6161Sema::DeclPtrTy Sema::ActOnEnumConstant(Scope *S, DeclPtrTy theEnumDecl,
6162                                        DeclPtrTy lastEnumConst,
6163                                        SourceLocation IdLoc,
6164                                        IdentifierInfo *Id,
6165                                        SourceLocation EqualLoc, ExprTy *val) {
6166  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl.getAs<Decl>());
6167  EnumConstantDecl *LastEnumConst =
6168    cast_or_null<EnumConstantDecl>(lastEnumConst.getAs<Decl>());
6169  Expr *Val = static_cast<Expr*>(val);
6170
6171  // The scope passed in may not be a decl scope.  Zip up the scope tree until
6172  // we find one that is.
6173  S = getNonFieldDeclScope(S);
6174
6175  // Verify that there isn't already something declared with this name in this
6176  // scope.
6177  NamedDecl *PrevDecl = LookupSingleName(S, Id, LookupOrdinaryName,
6178                                         ForRedeclaration);
6179  if (PrevDecl && PrevDecl->isTemplateParameter()) {
6180    // Maybe we will complain about the shadowed template parameter.
6181    DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
6182    // Just pretend that we didn't see the previous declaration.
6183    PrevDecl = 0;
6184  }
6185
6186  if (PrevDecl) {
6187    // When in C++, we may get a TagDecl with the same name; in this case the
6188    // enum constant will 'hide' the tag.
6189    assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
6190           "Received TagDecl when not in C++!");
6191    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
6192      if (isa<EnumConstantDecl>(PrevDecl))
6193        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
6194      else
6195        Diag(IdLoc, diag::err_redefinition) << Id;
6196      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
6197      if (Val) Val->Destroy(Context);
6198      return DeclPtrTy();
6199    }
6200  }
6201
6202  EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
6203                                            IdLoc, Id, Owned(Val));
6204
6205  // Register this decl in the current scope stack.
6206  if (New) {
6207    New->setAccess(TheEnumDecl->getAccess());
6208    PushOnScopeChains(New, S);
6209  }
6210
6211  return DeclPtrTy::make(New);
6212}
6213
6214void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
6215                         SourceLocation RBraceLoc, DeclPtrTy EnumDeclX,
6216                         DeclPtrTy *Elements, unsigned NumElements,
6217                         Scope *S, AttributeList *Attr) {
6218  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX.getAs<Decl>());
6219  QualType EnumType = Context.getTypeDeclType(Enum);
6220
6221  if (Attr)
6222    ProcessDeclAttributeList(S, Enum, Attr);
6223
6224  if (Enum->isDependentType()) {
6225    for (unsigned i = 0; i != NumElements; ++i) {
6226      EnumConstantDecl *ECD =
6227        cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6228      if (!ECD) continue;
6229
6230      ECD->setType(EnumType);
6231    }
6232
6233    Enum->completeDefinition(Context.DependentTy, Context.DependentTy);
6234    return;
6235  }
6236
6237  // TODO: If the result value doesn't fit in an int, it must be a long or long
6238  // long value.  ISO C does not support this, but GCC does as an extension,
6239  // emit a warning.
6240  unsigned IntWidth = Context.Target.getIntWidth();
6241  unsigned CharWidth = Context.Target.getCharWidth();
6242  unsigned ShortWidth = Context.Target.getShortWidth();
6243
6244  // Verify that all the values are okay, compute the size of the values, and
6245  // reverse the list.
6246  unsigned NumNegativeBits = 0;
6247  unsigned NumPositiveBits = 0;
6248
6249  // Keep track of whether all elements have type int.
6250  bool AllElementsInt = true;
6251
6252  for (unsigned i = 0; i != NumElements; ++i) {
6253    EnumConstantDecl *ECD =
6254      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6255    if (!ECD) continue;  // Already issued a diagnostic.
6256
6257    const llvm::APSInt &InitVal = ECD->getInitVal();
6258
6259    // Keep track of the size of positive and negative values.
6260    if (InitVal.isUnsigned() || InitVal.isNonNegative())
6261      NumPositiveBits = std::max(NumPositiveBits,
6262                                 (unsigned)InitVal.getActiveBits());
6263    else
6264      NumNegativeBits = std::max(NumNegativeBits,
6265                                 (unsigned)InitVal.getMinSignedBits());
6266
6267    // Keep track of whether every enum element has type int (very commmon).
6268    if (AllElementsInt)
6269      AllElementsInt = ECD->getType() == Context.IntTy;
6270  }
6271
6272  // Figure out the type that should be used for this enum.
6273  // FIXME: Support -fshort-enums.
6274  QualType BestType;
6275  unsigned BestWidth;
6276
6277  // C++0x N3000 [conv.prom]p3:
6278  //   An rvalue of an unscoped enumeration type whose underlying
6279  //   type is not fixed can be converted to an rvalue of the first
6280  //   of the following types that can represent all the values of
6281  //   the enumeration: int, unsigned int, long int, unsigned long
6282  //   int, long long int, or unsigned long long int.
6283  // C99 6.4.4.3p2:
6284  //   An identifier declared as an enumeration constant has type int.
6285  // The C99 rule is modified by a gcc extension
6286  QualType BestPromotionType;
6287
6288  bool Packed = Enum->getAttr<PackedAttr>() ? true : false;
6289
6290  if (NumNegativeBits) {
6291    // If there is a negative value, figure out the smallest integer type (of
6292    // int/long/longlong) that fits.
6293    // If it's packed, check also if it fits a char or a short.
6294    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
6295      BestType = Context.SignedCharTy;
6296      BestWidth = CharWidth;
6297    } else if (Packed && NumNegativeBits <= ShortWidth &&
6298               NumPositiveBits < ShortWidth) {
6299      BestType = Context.ShortTy;
6300      BestWidth = ShortWidth;
6301    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
6302      BestType = Context.IntTy;
6303      BestWidth = IntWidth;
6304    } else {
6305      BestWidth = Context.Target.getLongWidth();
6306
6307      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
6308        BestType = Context.LongTy;
6309      } else {
6310        BestWidth = Context.Target.getLongLongWidth();
6311
6312        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
6313          Diag(Enum->getLocation(), diag::warn_enum_too_large);
6314        BestType = Context.LongLongTy;
6315      }
6316    }
6317    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
6318  } else {
6319    // If there is no negative value, figure out the smallest type that fits
6320    // all of the enumerator values.
6321    // If it's packed, check also if it fits a char or a short.
6322    if (Packed && NumPositiveBits <= CharWidth) {
6323      BestType = Context.UnsignedCharTy;
6324      BestPromotionType = Context.IntTy;
6325      BestWidth = CharWidth;
6326    } else if (Packed && NumPositiveBits <= ShortWidth) {
6327      BestType = Context.UnsignedShortTy;
6328      BestPromotionType = Context.IntTy;
6329      BestWidth = ShortWidth;
6330    } else if (NumPositiveBits <= IntWidth) {
6331      BestType = Context.UnsignedIntTy;
6332      BestWidth = IntWidth;
6333      BestPromotionType
6334        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6335                           ? Context.UnsignedIntTy : Context.IntTy;
6336    } else if (NumPositiveBits <=
6337               (BestWidth = Context.Target.getLongWidth())) {
6338      BestType = Context.UnsignedLongTy;
6339      BestPromotionType
6340        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6341                           ? Context.UnsignedLongTy : Context.LongTy;
6342    } else {
6343      BestWidth = Context.Target.getLongLongWidth();
6344      assert(NumPositiveBits <= BestWidth &&
6345             "How could an initializer get larger than ULL?");
6346      BestType = Context.UnsignedLongLongTy;
6347      BestPromotionType
6348        = (NumPositiveBits == BestWidth || !getLangOptions().CPlusPlus)
6349                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
6350    }
6351  }
6352
6353  // Loop over all of the enumerator constants, changing their types to match
6354  // the type of the enum if needed.
6355  for (unsigned i = 0; i != NumElements; ++i) {
6356    EnumConstantDecl *ECD =
6357      cast_or_null<EnumConstantDecl>(Elements[i].getAs<Decl>());
6358    if (!ECD) continue;  // Already issued a diagnostic.
6359
6360    // Standard C says the enumerators have int type, but we allow, as an
6361    // extension, the enumerators to be larger than int size.  If each
6362    // enumerator value fits in an int, type it as an int, otherwise type it the
6363    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
6364    // that X has type 'int', not 'unsigned'.
6365
6366    // Determine whether the value fits into an int.
6367    llvm::APSInt InitVal = ECD->getInitVal();
6368
6369    // If it fits into an integer type, force it.  Otherwise force it to match
6370    // the enum decl type.
6371    QualType NewTy;
6372    unsigned NewWidth;
6373    bool NewSign;
6374    if (!getLangOptions().CPlusPlus &&
6375        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
6376      NewTy = Context.IntTy;
6377      NewWidth = IntWidth;
6378      NewSign = true;
6379    } else if (ECD->getType() == BestType) {
6380      // Already the right type!
6381      if (getLangOptions().CPlusPlus)
6382        // C++ [dcl.enum]p4: Following the closing brace of an
6383        // enum-specifier, each enumerator has the type of its
6384        // enumeration.
6385        ECD->setType(EnumType);
6386      continue;
6387    } else {
6388      NewTy = BestType;
6389      NewWidth = BestWidth;
6390      NewSign = BestType->isSignedIntegerType();
6391    }
6392
6393    // Adjust the APSInt value.
6394    InitVal.extOrTrunc(NewWidth);
6395    InitVal.setIsSigned(NewSign);
6396    ECD->setInitVal(InitVal);
6397
6398    // Adjust the Expr initializer and type.
6399    if (ECD->getInitExpr())
6400      ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy,
6401                                                      CastExpr::CK_IntegralCast,
6402                                                      ECD->getInitExpr(),
6403                                                      /*isLvalue=*/false));
6404    if (getLangOptions().CPlusPlus)
6405      // C++ [dcl.enum]p4: Following the closing brace of an
6406      // enum-specifier, each enumerator has the type of its
6407      // enumeration.
6408      ECD->setType(EnumType);
6409    else
6410      ECD->setType(NewTy);
6411  }
6412
6413  Enum->completeDefinition(BestType, BestPromotionType);
6414}
6415
6416Sema::DeclPtrTy Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
6417                                            ExprArg expr) {
6418  StringLiteral *AsmString = cast<StringLiteral>(expr.takeAs<Expr>());
6419
6420  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
6421                                                   Loc, AsmString);
6422  CurContext->addDecl(New);
6423  return DeclPtrTy::make(New);
6424}
6425
6426void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
6427                             SourceLocation PragmaLoc,
6428                             SourceLocation NameLoc) {
6429  Decl *PrevDecl = LookupSingleName(TUScope, Name, LookupOrdinaryName);
6430
6431  if (PrevDecl) {
6432    PrevDecl->addAttr(::new (Context) WeakAttr());
6433  } else {
6434    (void)WeakUndeclaredIdentifiers.insert(
6435      std::pair<IdentifierInfo*,WeakInfo>
6436        (Name, WeakInfo((IdentifierInfo*)0, NameLoc)));
6437  }
6438}
6439
6440void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
6441                                IdentifierInfo* AliasName,
6442                                SourceLocation PragmaLoc,
6443                                SourceLocation NameLoc,
6444                                SourceLocation AliasNameLoc) {
6445  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
6446  WeakInfo W = WeakInfo(Name, NameLoc);
6447
6448  if (PrevDecl) {
6449    if (!PrevDecl->hasAttr<AliasAttr>())
6450      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
6451        DeclApplyPragmaWeak(TUScope, ND, W);
6452  } else {
6453    (void)WeakUndeclaredIdentifiers.insert(
6454      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
6455  }
6456}
6457