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