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