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