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