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