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