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