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