SemaDeclCXX.cpp revision 58c428c96934a7873e70eadde8b496ff7f8d72ec
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ 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 C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/TypeOrdering.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Parse/DeclSpec.h"
22#include "llvm/Support/Compiler.h"
23#include <algorithm> // for std::equal
24#include <map>
25
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29// CheckDefaultArgumentVisitor
30//===----------------------------------------------------------------------===//
31
32namespace {
33  /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
34  /// the default argument of a parameter to determine whether it
35  /// contains any ill-formed subexpressions. For example, this will
36  /// diagnose the use of local variables or parameters within the
37  /// default argument expression.
38  class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
39    : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
40    Expr *DefaultArg;
41    Sema *S;
42
43  public:
44    CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
45      : DefaultArg(defarg), S(s) {}
46
47    bool VisitExpr(Expr *Node);
48    bool VisitDeclRefExpr(DeclRefExpr *DRE);
49    bool VisitPredefinedExpr(PredefinedExpr *PE);
50  };
51
52  /// VisitExpr - Visit all of the children of this expression.
53  bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
54    bool IsInvalid = false;
55    for (Stmt::child_iterator I = Node->child_begin(),
56         E = Node->child_end(); I != E; ++I)
57      IsInvalid |= Visit(*I);
58    return IsInvalid;
59  }
60
61  /// VisitDeclRefExpr - Visit a reference to a declaration, to
62  /// determine whether this declaration can be used in the default
63  /// argument expression.
64  bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
65    NamedDecl *Decl = DRE->getDecl();
66    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
67      // C++ [dcl.fct.default]p9
68      //   Default arguments are evaluated each time the function is
69      //   called. The order of evaluation of function arguments is
70      //   unspecified. Consequently, parameters of a function shall not
71      //   be used in default argument expressions, even if they are not
72      //   evaluated. Parameters of a function declared before a default
73      //   argument expression are in scope and can hide namespace and
74      //   class member names.
75      return S->Diag(DRE->getSourceRange().getBegin(),
76                     diag::err_param_default_argument_references_param,
77                     Param->getName(), DefaultArg->getSourceRange());
78    } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
79      // C++ [dcl.fct.default]p7
80      //   Local variables shall not be used in default argument
81      //   expressions.
82      if (VDecl->isBlockVarDecl())
83        return S->Diag(DRE->getSourceRange().getBegin(),
84                       diag::err_param_default_argument_references_local,
85                       VDecl->getName(), DefaultArg->getSourceRange());
86    }
87
88    return false;
89  }
90
91  /// VisitPredefinedExpr - Visit a predefined expression, which could
92  /// refer to "this".
93  bool CheckDefaultArgumentVisitor::VisitPredefinedExpr(PredefinedExpr *PE) {
94    if (PE->getIdentType() == PredefinedExpr::CXXThis) {
95      // C++ [dcl.fct.default]p8:
96      //   The keyword this shall not be used in a default argument of a
97      //   member function.
98      return S->Diag(PE->getSourceRange().getBegin(),
99                     diag::err_param_default_argument_references_this,
100                     PE->getSourceRange());
101    }
102    return false;
103  }
104}
105
106/// ActOnParamDefaultArgument - Check whether the default argument
107/// provided for a function parameter is well-formed. If so, attach it
108/// to the parameter declaration.
109void
110Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
111                                ExprTy *defarg) {
112  ParmVarDecl *Param = (ParmVarDecl *)param;
113  llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
114  QualType ParamType = Param->getType();
115
116  // Default arguments are only permitted in C++
117  if (!getLangOptions().CPlusPlus) {
118    Diag(EqualLoc, diag::err_param_default_argument,
119         DefaultArg->getSourceRange());
120    return;
121  }
122
123  // C++ [dcl.fct.default]p5
124  //   A default argument expression is implicitly converted (clause
125  //   4) to the parameter type. The default argument expression has
126  //   the same semantic constraints as the initializer expression in
127  //   a declaration of a variable of the parameter type, using the
128  //   copy-initialization semantics (8.5).
129  Expr *DefaultArgPtr = DefaultArg.get();
130  bool DefaultInitFailed = PerformCopyInitialization(DefaultArgPtr, ParamType,
131                                                     "in default argument");
132  if (DefaultArgPtr != DefaultArg.get()) {
133    DefaultArg.take();
134    DefaultArg.reset(DefaultArgPtr);
135  }
136  if (DefaultInitFailed) {
137    return;
138  }
139
140  // Check that the default argument is well-formed
141  CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
142  if (DefaultArgChecker.Visit(DefaultArg.get()))
143    return;
144
145  // Okay: add the default argument to the parameter
146  Param->setDefaultArg(DefaultArg.take());
147}
148
149/// CheckExtraCXXDefaultArguments - Check for any extra default
150/// arguments in the declarator, which is not a function declaration
151/// or definition and therefore is not permitted to have default
152/// arguments. This routine should be invoked for every declarator
153/// that is not a function declaration or definition.
154void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
155  // C++ [dcl.fct.default]p3
156  //   A default argument expression shall be specified only in the
157  //   parameter-declaration-clause of a function declaration or in a
158  //   template-parameter (14.1). It shall not be specified for a
159  //   parameter pack. If it is specified in a
160  //   parameter-declaration-clause, it shall not occur within a
161  //   declarator or abstract-declarator of a parameter-declaration.
162  for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
163    DeclaratorChunk &chunk = D.getTypeObject(i);
164    if (chunk.Kind == DeclaratorChunk::Function) {
165      for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
166        ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
167        if (Param->getDefaultArg()) {
168          Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
169               Param->getDefaultArg()->getSourceRange());
170          Param->setDefaultArg(0);
171        }
172      }
173    }
174  }
175}
176
177// MergeCXXFunctionDecl - Merge two declarations of the same C++
178// function, once we already know that they have the same
179// type. Subroutine of MergeFunctionDecl.
180FunctionDecl *
181Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
182  // C++ [dcl.fct.default]p4:
183  //
184  //   For non-template functions, default arguments can be added in
185  //   later declarations of a function in the same
186  //   scope. Declarations in different scopes have completely
187  //   distinct sets of default arguments. That is, declarations in
188  //   inner scopes do not acquire default arguments from
189  //   declarations in outer scopes, and vice versa. In a given
190  //   function declaration, all parameters subsequent to a
191  //   parameter with a default argument shall have default
192  //   arguments supplied in this or previous declarations. A
193  //   default argument shall not be redefined by a later
194  //   declaration (not even to the same value).
195  for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
196    ParmVarDecl *OldParam = Old->getParamDecl(p);
197    ParmVarDecl *NewParam = New->getParamDecl(p);
198
199    if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
200      Diag(NewParam->getLocation(),
201           diag::err_param_default_argument_redefinition,
202           NewParam->getDefaultArg()->getSourceRange());
203      Diag(OldParam->getLocation(), diag::err_previous_definition);
204    } else if (OldParam->getDefaultArg()) {
205      // Merge the old default argument into the new parameter
206      NewParam->setDefaultArg(OldParam->getDefaultArg());
207    }
208  }
209
210  return New;
211}
212
213/// CheckCXXDefaultArguments - Verify that the default arguments for a
214/// function declaration are well-formed according to C++
215/// [dcl.fct.default].
216void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
217  unsigned NumParams = FD->getNumParams();
218  unsigned p;
219
220  // Find first parameter with a default argument
221  for (p = 0; p < NumParams; ++p) {
222    ParmVarDecl *Param = FD->getParamDecl(p);
223    if (Param->getDefaultArg())
224      break;
225  }
226
227  // C++ [dcl.fct.default]p4:
228  //   In a given function declaration, all parameters
229  //   subsequent to a parameter with a default argument shall
230  //   have default arguments supplied in this or previous
231  //   declarations. A default argument shall not be redefined
232  //   by a later declaration (not even to the same value).
233  unsigned LastMissingDefaultArg = 0;
234  for(; p < NumParams; ++p) {
235    ParmVarDecl *Param = FD->getParamDecl(p);
236    if (!Param->getDefaultArg()) {
237      if (Param->getIdentifier())
238        Diag(Param->getLocation(),
239             diag::err_param_default_argument_missing_name,
240             Param->getIdentifier()->getName());
241      else
242        Diag(Param->getLocation(),
243             diag::err_param_default_argument_missing);
244
245      LastMissingDefaultArg = p;
246    }
247  }
248
249  if (LastMissingDefaultArg > 0) {
250    // Some default arguments were missing. Clear out all of the
251    // default arguments up to (and including) the last missing
252    // default argument, so that we leave the function parameters
253    // in a semantically valid state.
254    for (p = 0; p <= LastMissingDefaultArg; ++p) {
255      ParmVarDecl *Param = FD->getParamDecl(p);
256      if (Param->getDefaultArg()) {
257        delete Param->getDefaultArg();
258        Param->setDefaultArg(0);
259      }
260    }
261  }
262}
263
264/// isCurrentClassName - Determine whether the identifier II is the
265/// name of the class type currently being defined. In the case of
266/// nested classes, this will only return true if II is the name of
267/// the innermost class.
268bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) {
269  if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext))
270    return &II == CurDecl->getIdentifier();
271  else
272    return false;
273}
274
275/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
276/// one entry in the base class list of a class specifier, for
277/// example:
278///    class foo : public bar, virtual private baz {
279/// 'public bar' and 'virtual private baz' are each base-specifiers.
280Sema::BaseResult
281Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
282                         bool Virtual, AccessSpecifier Access,
283                         TypeTy *basetype, SourceLocation BaseLoc) {
284  RecordDecl *Decl = (RecordDecl*)classdecl;
285  QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
286
287  // Base specifiers must be record types.
288  if (!BaseType->isRecordType()) {
289    Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
290    return true;
291  }
292
293  // C++ [class.union]p1:
294  //   A union shall not be used as a base class.
295  if (BaseType->isUnionType()) {
296    Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
297    return true;
298  }
299
300  // C++ [class.union]p1:
301  //   A union shall not have base classes.
302  if (Decl->isUnion()) {
303    Diag(Decl->getLocation(), diag::err_base_clause_on_union,
304         SpecifierRange);
305    return true;
306  }
307
308  // C++ [class.derived]p2:
309  //   The class-name in a base-specifier shall not be an incompletely
310  //   defined class.
311  if (BaseType->isIncompleteType()) {
312    Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
313    return true;
314  }
315
316  // Create the base specifier.
317  return new CXXBaseSpecifier(SpecifierRange, Virtual,
318                              BaseType->isClassType(), Access, BaseType);
319}
320
321/// ActOnBaseSpecifiers - Attach the given base specifiers to the
322/// class, after checking whether there are any duplicate base
323/// classes.
324void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
325                               unsigned NumBases) {
326  if (NumBases == 0)
327    return;
328
329  // Used to keep track of which base types we have already seen, so
330  // that we can properly diagnose redundant direct base types. Note
331  // that the key is always the unqualified canonical type of the base
332  // class.
333  std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
334
335  // Copy non-redundant base specifiers into permanent storage.
336  CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
337  unsigned NumGoodBases = 0;
338  for (unsigned idx = 0; idx < NumBases; ++idx) {
339    QualType NewBaseType
340      = Context.getCanonicalType(BaseSpecs[idx]->getType());
341    NewBaseType = NewBaseType.getUnqualifiedType();
342
343    if (KnownBaseTypes[NewBaseType]) {
344      // C++ [class.mi]p3:
345      //   A class shall not be specified as a direct base class of a
346      //   derived class more than once.
347      Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
348           diag::err_duplicate_base_class,
349           KnownBaseTypes[NewBaseType]->getType().getAsString(),
350           BaseSpecs[idx]->getSourceRange());
351
352      // Delete the duplicate base class specifier; we're going to
353      // overwrite its pointer later.
354      delete BaseSpecs[idx];
355    } else {
356      // Okay, add this new base class.
357      KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
358      BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
359    }
360  }
361
362  // Attach the remaining base class specifiers to the derived class.
363  CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
364  Decl->setBases(BaseSpecs, NumGoodBases);
365
366  // Delete the remaining (good) base class specifiers, since their
367  // data has been copied into the CXXRecordDecl.
368  for (unsigned idx = 0; idx < NumGoodBases; ++idx)
369    delete BaseSpecs[idx];
370}
371
372//===----------------------------------------------------------------------===//
373// C++ class member Handling
374//===----------------------------------------------------------------------===//
375
376/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
377/// definition, when on C++.
378void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
379  CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
380  PushDeclContext(Dcl);
381  FieldCollector->StartClass();
382
383  if (Dcl->getIdentifier()) {
384    // C++ [class]p2:
385    //   [...] The class-name is also inserted into the scope of the
386    //   class itself; this is known as the injected-class-name. For
387    //   purposes of access checking, the injected-class-name is treated
388    //   as if it were a public member name.
389    TypedefDecl *InjectedClassName
390      = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
391                            Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
392    PushOnScopeChains(InjectedClassName, S);
393  }
394}
395
396/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
397/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
398/// bitfield width if there is one and 'InitExpr' specifies the initializer if
399/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
400/// declarators on it.
401///
402/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
403/// an instance field is declared, a new CXXFieldDecl is created but the method
404/// does *not* return it; it returns LastInGroup instead. The other C++ members
405/// (which are all ScopedDecls) are returned after appending them to
406/// LastInGroup.
407Sema::DeclTy *
408Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
409                               ExprTy *BW, ExprTy *InitExpr,
410                               DeclTy *LastInGroup) {
411  const DeclSpec &DS = D.getDeclSpec();
412  IdentifierInfo *II = D.getIdentifier();
413  Expr *BitWidth = static_cast<Expr*>(BW);
414  Expr *Init = static_cast<Expr*>(InitExpr);
415  SourceLocation Loc = D.getIdentifierLoc();
416
417  // C++ 9.2p6: A member shall not be declared to have automatic storage
418  // duration (auto, register) or with the extern storage-class-specifier.
419  switch (DS.getStorageClassSpec()) {
420    case DeclSpec::SCS_unspecified:
421    case DeclSpec::SCS_typedef:
422    case DeclSpec::SCS_static:
423      // FALL THROUGH.
424      break;
425    default:
426      if (DS.getStorageClassSpecLoc().isValid())
427        Diag(DS.getStorageClassSpecLoc(),
428             diag::err_storageclass_invalid_for_member);
429      else
430        Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
431      D.getMutableDeclSpec().ClearStorageClassSpecs();
432  }
433
434  bool isFunc = D.isFunctionDeclarator();
435  if (!isFunc &&
436      D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
437      D.getNumTypeObjects() == 0) {
438    // Check also for this case:
439    //
440    // typedef int f();
441    // f a;
442    //
443    Decl *TD = static_cast<Decl *>(DS.getTypeRep());
444    isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
445  }
446
447  bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
448                      !isFunc);
449
450  Decl *Member;
451  bool InvalidDecl = false;
452
453  if (isInstField)
454    Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
455  else
456    Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
457
458  if (!Member) return LastInGroup;
459
460  assert((II || isInstField) && "No identifier for non-field ?");
461
462  // set/getAccess is not part of Decl's interface to avoid bloating it with C++
463  // specific methods. Use a wrapper class that can be used with all C++ class
464  // member decls.
465  CXXClassMemberWrapper(Member).setAccess(AS);
466
467  if (BitWidth) {
468    // C++ 9.6p2: Only when declaring an unnamed bit-field may the
469    // constant-expression be a value equal to zero.
470    // FIXME: Check this.
471
472    if (D.isFunctionDeclarator()) {
473      // FIXME: Emit diagnostic about only constructors taking base initializers
474      // or something similar, when constructor support is in place.
475      Diag(Loc, diag::err_not_bitfield_type,
476           II->getName(), BitWidth->getSourceRange());
477      InvalidDecl = true;
478
479    } else if (isInstField) {
480      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
481      if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
482        Diag(Loc, diag::err_not_integral_type_bitfield,
483             II->getName(), BitWidth->getSourceRange());
484        InvalidDecl = true;
485      }
486
487    } else if (isa<FunctionDecl>(Member)) {
488      // A function typedef ("typedef int f(); f a;").
489      // C++ 9.6p3: A bit-field shall have integral or enumeration type.
490      Diag(Loc, diag::err_not_integral_type_bitfield,
491           II->getName(), BitWidth->getSourceRange());
492      InvalidDecl = true;
493
494    } else if (isa<TypedefDecl>(Member)) {
495      // "cannot declare 'A' to be a bit-field type"
496      Diag(Loc, diag::err_not_bitfield_type, II->getName(),
497           BitWidth->getSourceRange());
498      InvalidDecl = true;
499
500    } else {
501      assert(isa<CXXClassVarDecl>(Member) &&
502             "Didn't we cover all member kinds?");
503      // C++ 9.6p3: A bit-field shall not be a static member.
504      // "static member 'A' cannot be a bit-field"
505      Diag(Loc, diag::err_static_not_bitfield, II->getName(),
506           BitWidth->getSourceRange());
507      InvalidDecl = true;
508    }
509  }
510
511  if (Init) {
512    // C++ 9.2p4: A member-declarator can contain a constant-initializer only
513    // if it declares a static member of const integral or const enumeration
514    // type.
515    if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
516      // ...static member of...
517      CVD->setInit(Init);
518      // ...const integral or const enumeration type.
519      if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
520          CVD->getType()->isIntegralType()) {
521        // constant-initializer
522        if (CheckForConstantInitializer(Init, CVD->getType()))
523          InvalidDecl = true;
524
525      } else {
526        // not const integral.
527        Diag(Loc, diag::err_member_initialization,
528             II->getName(), Init->getSourceRange());
529        InvalidDecl = true;
530      }
531
532    } else {
533      // not static member.
534      Diag(Loc, diag::err_member_initialization,
535           II->getName(), Init->getSourceRange());
536      InvalidDecl = true;
537    }
538  }
539
540  if (InvalidDecl)
541    Member->setInvalidDecl();
542
543  if (isInstField) {
544    FieldCollector->Add(cast<CXXFieldDecl>(Member));
545    return LastInGroup;
546  }
547  return Member;
548}
549
550void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
551                                             DeclTy *TagDecl,
552                                             SourceLocation LBrac,
553                                             SourceLocation RBrac) {
554  ActOnFields(S, RLoc, TagDecl,
555              (DeclTy**)FieldCollector->getCurFields(),
556              FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
557}
558
559/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
560/// special functions, such as the default constructor, copy
561/// constructor, or destructor, to the given C++ class (C++
562/// [special]p1).  This routine can only be executed just before the
563/// definition of the class is complete.
564void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
565  if (!ClassDecl->hasUserDeclaredConstructor()) {
566    // C++ [class.ctor]p5:
567    //   A default constructor for a class X is a constructor of class X
568    //   that can be called without an argument. If there is no
569    //   user-declared constructor for class X, a default constructor is
570    //   implicitly declared. An implicitly-declared default constructor
571    //   is an inline public member of its class.
572    CXXConstructorDecl *DefaultCon =
573      CXXConstructorDecl::Create(Context, ClassDecl,
574                                 ClassDecl->getLocation(),
575                                 ClassDecl->getIdentifier(),
576                                 Context.getFunctionType(Context.VoidTy,
577                                                         0, 0, false, 0),
578                                 /*isExplicit=*/false,
579                                 /*isInline=*/true,
580                                 /*isImplicitlyDeclared=*/true);
581    DefaultCon->setAccess(AS_public);
582    ClassDecl->addConstructor(Context, DefaultCon);
583  }
584
585  if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
586    // C++ [class.copy]p4:
587    //   If the class definition does not explicitly declare a copy
588    //   constructor, one is declared implicitly.
589
590    // C++ [class.copy]p5:
591    //   The implicitly-declared copy constructor for a class X will
592    //   have the form
593    //
594    //       X::X(const X&)
595    //
596    //   if
597    bool HasConstCopyConstructor = true;
598
599    //     -- each direct or virtual base class B of X has a copy
600    //        constructor whose first parameter is of type const B& or
601    //        const volatile B&, and
602    for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
603         HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
604      const CXXRecordDecl *BaseClassDecl
605        = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
606      HasConstCopyConstructor
607        = BaseClassDecl->hasConstCopyConstructor(Context);
608    }
609
610    //     -- for all the nonstatic data members of X that are of a
611    //        class type M (or array thereof), each such class type
612    //        has a copy constructor whose first parameter is of type
613    //        const M& or const volatile M&.
614    for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
615         HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
616      QualType FieldType = (*Field)->getType();
617      if (const ArrayType *Array = Context.getAsArrayType(FieldType))
618        FieldType = Array->getElementType();
619      if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
620        const CXXRecordDecl *FieldClassDecl
621          = cast<CXXRecordDecl>(FieldClassType->getDecl());
622        HasConstCopyConstructor
623          = FieldClassDecl->hasConstCopyConstructor(Context);
624      }
625    }
626
627    //  Otherwise, the implicitly declared copy constructor will have
628    //  the form
629    //
630    //       X::X(X&)
631    QualType ArgType = Context.getTypeDeclType(ClassDecl);
632    if (HasConstCopyConstructor)
633      ArgType = ArgType.withConst();
634    ArgType = Context.getReferenceType(ArgType);
635
636    //  An implicitly-declared copy constructor is an inline public
637    //  member of its class.
638    CXXConstructorDecl *CopyConstructor
639      = CXXConstructorDecl::Create(Context, ClassDecl,
640                                   ClassDecl->getLocation(),
641                                   ClassDecl->getIdentifier(),
642                                   Context.getFunctionType(Context.VoidTy,
643                                                           &ArgType, 1,
644                                                           false, 0),
645                                   /*isExplicit=*/false,
646                                   /*isInline=*/true,
647                                   /*isImplicitlyDeclared=*/true);
648    CopyConstructor->setAccess(AS_public);
649
650    // Add the parameter to the constructor.
651    ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
652                                                 ClassDecl->getLocation(),
653                                                 /*IdentifierInfo=*/0,
654                                                 ArgType, VarDecl::None, 0, 0);
655    CopyConstructor->setParams(&FromParam, 1);
656
657    ClassDecl->addConstructor(Context, CopyConstructor);
658  }
659
660  // FIXME: Implicit destructor
661  // FIXME: Implicit copy assignment operator
662}
663
664void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
665  CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
666  FieldCollector->FinishClass();
667  AddImplicitlyDeclaredMembersToClass(Rec);
668  PopDeclContext();
669
670  // Everything, including inline method definitions, have been parsed.
671  // Let the consumer know of the new TagDecl definition.
672  Consumer.HandleTagDeclDefinition(Rec);
673}
674
675/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
676/// the declaration of the given C++ constructor ConDecl that was
677/// built from declarator D. This routine is responsible for checking
678/// that the newly-created constructor declaration is well-formed and
679/// for recording it in the C++ class. Example:
680///
681/// @code
682/// class X {
683///   X(); // X::X() will be the ConDecl.
684/// };
685/// @endcode
686Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
687  assert(ConDecl && "Expected to receive a constructor declaration");
688
689  // Check default arguments on the constructor
690  CheckCXXDefaultArguments(ConDecl);
691
692  CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
693  if (!ClassDecl) {
694    ConDecl->setInvalidDecl();
695    return ConDecl;
696  }
697
698  // Make sure this constructor is an overload of the existing
699  // constructors.
700  OverloadedFunctionDecl::function_iterator MatchedDecl;
701  if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
702    Diag(ConDecl->getLocation(),
703         diag::err_constructor_redeclared,
704         SourceRange(ConDecl->getLocation()));
705    Diag((*MatchedDecl)->getLocation(),
706         diag::err_previous_declaration,
707         SourceRange((*MatchedDecl)->getLocation()));
708    ConDecl->setInvalidDecl();
709    return ConDecl;
710  }
711
712
713  // C++ [class.copy]p3:
714  //   A declaration of a constructor for a class X is ill-formed if
715  //   its first parameter is of type (optionally cv-qualified) X and
716  //   either there are no other parameters or else all other
717  //   parameters have default arguments.
718  if ((ConDecl->getNumParams() == 1) ||
719      (ConDecl->getNumParams() > 1 &&
720       ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
721    QualType ParamType = ConDecl->getParamDecl(0)->getType();
722    QualType ClassTy = Context.getTagDeclType(
723                         const_cast<CXXRecordDecl*>(ConDecl->getParent()));
724    if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
725      Diag(ConDecl->getLocation(),
726           diag::err_constructor_byvalue_arg,
727           SourceRange(ConDecl->getParamDecl(0)->getLocation()));
728      ConDecl->setInvalidDecl();
729      return 0;
730    }
731  }
732
733  // Add this constructor to the set of constructors of the current
734  // class.
735  ClassDecl->addConstructor(Context, ConDecl);
736
737  return (DeclTy *)ConDecl;
738}
739
740//===----------------------------------------------------------------------===//
741// Namespace Handling
742//===----------------------------------------------------------------------===//
743
744/// ActOnStartNamespaceDef - This is called at the start of a namespace
745/// definition.
746Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
747                                           SourceLocation IdentLoc,
748                                           IdentifierInfo *II,
749                                           SourceLocation LBrace) {
750  NamespaceDecl *Namespc =
751      NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
752  Namespc->setLBracLoc(LBrace);
753
754  Scope *DeclRegionScope = NamespcScope->getParent();
755
756  if (II) {
757    // C++ [namespace.def]p2:
758    // The identifier in an original-namespace-definition shall not have been
759    // previously defined in the declarative region in which the
760    // original-namespace-definition appears. The identifier in an
761    // original-namespace-definition is the name of the namespace. Subsequently
762    // in that declarative region, it is treated as an original-namespace-name.
763
764    Decl *PrevDecl =
765        LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
766                   /*enableLazyBuiltinCreation=*/false);
767
768    if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
769      if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
770        // This is an extended namespace definition.
771        // Attach this namespace decl to the chain of extended namespace
772        // definitions.
773        NamespaceDecl *NextNS = OrigNS;
774        while (NextNS->getNextNamespace())
775          NextNS = NextNS->getNextNamespace();
776
777        NextNS->setNextNamespace(Namespc);
778        Namespc->setOriginalNamespace(OrigNS);
779
780        // We won't add this decl to the current scope. We want the namespace
781        // name to return the original namespace decl during a name lookup.
782      } else {
783        // This is an invalid name redefinition.
784        Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
785          Namespc->getName());
786        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
787        Namespc->setInvalidDecl();
788        // Continue on to push Namespc as current DeclContext and return it.
789      }
790    } else {
791      // This namespace name is declared for the first time.
792      PushOnScopeChains(Namespc, DeclRegionScope);
793    }
794  }
795  else {
796    // FIXME: Handle anonymous namespaces
797  }
798
799  // Although we could have an invalid decl (i.e. the namespace name is a
800  // redefinition), push it as current DeclContext and try to continue parsing.
801  PushDeclContext(Namespc->getOriginalNamespace());
802  return Namespc;
803}
804
805/// ActOnFinishNamespaceDef - This callback is called after a namespace is
806/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
807void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
808  Decl *Dcl = static_cast<Decl *>(D);
809  NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
810  assert(Namespc && "Invalid parameter, expected NamespaceDecl");
811  Namespc->setRBracLoc(RBrace);
812  PopDeclContext();
813}
814
815
816/// AddCXXDirectInitializerToDecl - This action is called immediately after
817/// ActOnDeclarator, when a C++ direct initializer is present.
818/// e.g: "int x(1);"
819void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
820                                         ExprTy **ExprTys, unsigned NumExprs,
821                                         SourceLocation *CommaLocs,
822                                         SourceLocation RParenLoc) {
823  assert(NumExprs != 0 && ExprTys && "missing expressions");
824  Decl *RealDecl = static_cast<Decl *>(Dcl);
825
826  // If there is no declaration, there was an error parsing it.  Just ignore
827  // the initializer.
828  if (RealDecl == 0) {
829    for (unsigned i = 0; i != NumExprs; ++i)
830      delete static_cast<Expr *>(ExprTys[i]);
831    return;
832  }
833
834  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
835  if (!VDecl) {
836    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
837    RealDecl->setInvalidDecl();
838    return;
839  }
840
841  // We will treat direct-initialization as a copy-initialization:
842  //    int x(1);  -as-> int x = 1;
843  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
844  //
845  // Clients that want to distinguish between the two forms, can check for
846  // direct initializer using VarDecl::hasCXXDirectInitializer().
847  // A major benefit is that clients that don't particularly care about which
848  // exactly form was it (like the CodeGen) can handle both cases without
849  // special case code.
850
851  // C++ 8.5p11:
852  // The form of initialization (using parentheses or '=') is generally
853  // insignificant, but does matter when the entity being initialized has a
854  // class type.
855  QualType DeclInitType = VDecl->getType();
856  if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
857    DeclInitType = Array->getElementType();
858
859  if (VDecl->getType()->isRecordType()) {
860    CXXConstructorDecl *Constructor
861      = PerformDirectInitForClassType(DeclInitType, (Expr **)ExprTys, NumExprs,
862                                      VDecl->getLocation(),
863                                      SourceRange(VDecl->getLocation(),
864                                                  RParenLoc),
865                                      VDecl->getName(),
866                                      /*HasInitializer=*/true);
867    if (!Constructor) {
868      RealDecl->setInvalidDecl();
869    }
870    return;
871  }
872
873  if (NumExprs > 1) {
874    Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
875         SourceRange(VDecl->getLocation(), RParenLoc));
876    RealDecl->setInvalidDecl();
877    return;
878  }
879
880  // Let clients know that initialization was done with a direct initializer.
881  VDecl->setCXXDirectInitializer(true);
882
883  assert(NumExprs == 1 && "Expected 1 expression");
884  // Set the init expression, handles conversions.
885  AddInitializerToDecl(Dcl, ExprTys[0]);
886}
887
888/// PerformDirectInitForClassType - Perform direct-initialization (C++
889/// [dcl.init]) for a value of the given class type with the given set
890/// of arguments (@p Args). @p Loc is the location in the source code
891/// where the initializer occurs (e.g., a declaration, member
892/// initializer, functional cast, etc.) while @p Range covers the
893/// whole initialization. @p HasInitializer is true if the initializer
894/// was actually written in the source code. When successful, returns
895/// the constructor that will be used to perform the initialization;
896/// when the initialization fails, emits a diagnostic and returns null.
897CXXConstructorDecl *
898Sema::PerformDirectInitForClassType(QualType ClassType,
899                                    Expr **Args, unsigned NumArgs,
900                                    SourceLocation Loc, SourceRange Range,
901                                    std::string InitEntity,
902                                    bool HasInitializer) {
903  const RecordType *ClassRec = ClassType->getAsRecordType();
904  assert(ClassRec && "Can only initialize a class type here");
905
906  // C++ [dcl.init]p14:
907  //
908  //   If the initialization is direct-initialization, or if it is
909  //   copy-initialization where the cv-unqualified version of the
910  //   source type is the same class as, or a derived class of, the
911  //   class of the destination, constructors are considered. The
912  //   applicable constructors are enumerated (13.3.1.3), and the
913  //   best one is chosen through overload resolution (13.3). The
914  //   constructor so selected is called to initialize the object,
915  //   with the initializer expression(s) as its argument(s). If no
916  //   constructor applies, or the overload resolution is ambiguous,
917  //   the initialization is ill-formed.
918  //
919  // FIXME: We don't check cv-qualifiers on the class type, because we
920  // don't yet keep track of whether a class type is a POD class type
921  // (or a "trivial" class type, as is used in C++0x).
922  const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
923  OverloadCandidateSet CandidateSet;
924  OverloadCandidateSet::iterator Best;
925  AddOverloadCandidates(ClassDecl->getConstructors(), Args, NumArgs,
926                        CandidateSet);
927  switch (BestViableFunction(CandidateSet, Best)) {
928  case OR_Success:
929    // We found a constructor. Return it.
930    return cast<CXXConstructorDecl>(Best->Function);
931
932  case OR_No_Viable_Function:
933    if (CandidateSet.empty())
934      Diag(Loc, diag::err_ovl_no_viable_function_in_init,
935           InitEntity, Range);
936    else {
937      Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
938           InitEntity, Range);
939      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
940    }
941    return 0;
942
943  case OR_Ambiguous:
944    Diag(Loc, diag::err_ovl_ambiguous_init,
945         InitEntity, Range);
946    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
947    return 0;
948  }
949
950  return 0;
951}
952
953/// CompareReferenceRelationship - Compare the two types T1 and T2 to
954/// determine whether they are reference-related,
955/// reference-compatible, reference-compatible with added
956/// qualification, or incompatible, for use in C++ initialization by
957/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
958/// type, and the first type (T1) is the pointee type of the reference
959/// type being initialized.
960Sema::ReferenceCompareResult
961Sema::CompareReferenceRelationship(QualType T1, QualType T2,
962                                   bool& DerivedToBase) {
963  assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
964  assert(!T2->isReferenceType() && "T2 cannot be a reference type");
965
966  T1 = Context.getCanonicalType(T1);
967  T2 = Context.getCanonicalType(T2);
968  QualType UnqualT1 = T1.getUnqualifiedType();
969  QualType UnqualT2 = T2.getUnqualifiedType();
970
971  // C++ [dcl.init.ref]p4:
972  //   Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
973  //   reference-related to “cv2 T2” if T1 is the same type as T2, or
974  //   T1 is a base class of T2.
975  if (UnqualT1 == UnqualT2)
976    DerivedToBase = false;
977  else if (IsDerivedFrom(UnqualT2, UnqualT1))
978    DerivedToBase = true;
979  else
980    return Ref_Incompatible;
981
982  // At this point, we know that T1 and T2 are reference-related (at
983  // least).
984
985  // C++ [dcl.init.ref]p4:
986  //   "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
987  //   reference-related to T2 and cv1 is the same cv-qualification
988  //   as, or greater cv-qualification than, cv2. For purposes of
989  //   overload resolution, cases for which cv1 is greater
990  //   cv-qualification than cv2 are identified as
991  //   reference-compatible with added qualification (see 13.3.3.2).
992  if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
993    return Ref_Compatible;
994  else if (T1.isMoreQualifiedThan(T2))
995    return Ref_Compatible_With_Added_Qualification;
996  else
997    return Ref_Related;
998}
999
1000/// CheckReferenceInit - Check the initialization of a reference
1001/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1002/// the initializer (either a simple initializer or an initializer
1003/// list), and DeclType is the type of the declaration. When ICS is
1004/// non-null, this routine will compute the implicit conversion
1005/// sequence according to C++ [over.ics.ref] and will not produce any
1006/// diagnostics; when ICS is null, it will emit diagnostics when any
1007/// errors are found. Either way, a return value of true indicates
1008/// that there was a failure, a return value of false indicates that
1009/// the reference initialization succeeded.
1010///
1011/// When @p SuppressUserConversions, user-defined conversions are
1012/// suppressed.
1013bool
1014Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
1015                         ImplicitConversionSequence *ICS,
1016                         bool SuppressUserConversions) {
1017  assert(DeclType->isReferenceType() && "Reference init needs a reference");
1018
1019  QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1020  QualType T2 = Init->getType();
1021
1022  // Compute some basic properties of the types and the initializer.
1023  bool DerivedToBase = false;
1024  Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
1025  ReferenceCompareResult RefRelationship
1026    = CompareReferenceRelationship(T1, T2, DerivedToBase);
1027
1028  // Most paths end in a failed conversion.
1029  if (ICS)
1030    ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
1031
1032  // C++ [dcl.init.ref]p5:
1033  //   A reference to type “cv1 T1” is initialized by an expression
1034  //   of type “cv2 T2” as follows:
1035
1036  //     -- If the initializer expression
1037
1038  bool BindsDirectly = false;
1039  //       -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1040  //          reference-compatible with “cv2 T2,” or
1041  //
1042  // Note that the bit-field check is skipped if we are just computing
1043  // the implicit conversion sequence (C++ [over.best.ics]p2).
1044  if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1045      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1046    BindsDirectly = true;
1047
1048    if (ICS) {
1049      // C++ [over.ics.ref]p1:
1050      //   When a parameter of reference type binds directly (8.5.3)
1051      //   to an argument expression, the implicit conversion sequence
1052      //   is the identity conversion, unless the argument expression
1053      //   has a type that is a derived class of the parameter type,
1054      //   in which case the implicit conversion sequence is a
1055      //   derived-to-base Conversion (13.3.3.1).
1056      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1057      ICS->Standard.First = ICK_Identity;
1058      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1059      ICS->Standard.Third = ICK_Identity;
1060      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1061      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1062      ICS->Standard.ReferenceBinding = true;
1063      ICS->Standard.DirectBinding = true;
1064
1065      // Nothing more to do: the inaccessibility/ambiguity check for
1066      // derived-to-base conversions is suppressed when we're
1067      // computing the implicit conversion sequence (C++
1068      // [over.best.ics]p2).
1069      return false;
1070    } else {
1071      // Perform the conversion.
1072      // FIXME: Binding to a subobject of the lvalue is going to require
1073      // more AST annotation than this.
1074      ImpCastExprToType(Init, T1);
1075    }
1076  }
1077
1078  //       -- has a class type (i.e., T2 is a class type) and can be
1079  //          implicitly converted to an lvalue of type “cv3 T3,”
1080  //          where “cv1 T1” is reference-compatible with “cv3 T3”
1081  //          92) (this conversion is selected by enumerating the
1082  //          applicable conversion functions (13.3.1.6) and choosing
1083  //          the best one through overload resolution (13.3)),
1084  // FIXME: Implement this second bullet, once we have conversion
1085  //        functions. Also remember C++ [over.ics.ref]p1, second part.
1086
1087  if (BindsDirectly) {
1088    // C++ [dcl.init.ref]p4:
1089    //   [...] In all cases where the reference-related or
1090    //   reference-compatible relationship of two types is used to
1091    //   establish the validity of a reference binding, and T1 is a
1092    //   base class of T2, a program that necessitates such a binding
1093    //   is ill-formed if T1 is an inaccessible (clause 11) or
1094    //   ambiguous (10.2) base class of T2.
1095    //
1096    // Note that we only check this condition when we're allowed to
1097    // complain about errors, because we should not be checking for
1098    // ambiguity (or inaccessibility) unless the reference binding
1099    // actually happens.
1100    if (DerivedToBase)
1101      return CheckDerivedToBaseConversion(T2, T1,
1102                                          Init->getSourceRange().getBegin(),
1103                                          Init->getSourceRange());
1104    else
1105      return false;
1106  }
1107
1108  //     -- Otherwise, the reference shall be to a non-volatile const
1109  //        type (i.e., cv1 shall be const).
1110  if (T1.getCVRQualifiers() != QualType::Const) {
1111    if (!ICS)
1112      Diag(Init->getSourceRange().getBegin(),
1113           diag::err_not_reference_to_const_init,
1114           T1.getAsString(),
1115           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1116           T2.getAsString(), Init->getSourceRange());
1117    return true;
1118  }
1119
1120  //       -- If the initializer expression is an rvalue, with T2 a
1121  //          class type, and “cv1 T1” is reference-compatible with
1122  //          “cv2 T2,” the reference is bound in one of the
1123  //          following ways (the choice is implementation-defined):
1124  //
1125  //          -- The reference is bound to the object represented by
1126  //             the rvalue (see 3.10) or to a sub-object within that
1127  //             object.
1128  //
1129  //          -- A temporary of type “cv1 T2” [sic] is created, and
1130  //             a constructor is called to copy the entire rvalue
1131  //             object into the temporary. The reference is bound to
1132  //             the temporary or to a sub-object within the
1133  //             temporary.
1134  //
1135  //
1136  //          The constructor that would be used to make the copy
1137  //          shall be callable whether or not the copy is actually
1138  //          done.
1139  //
1140  // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1141  // freedom, so we will always take the first option and never build
1142  // a temporary in this case. FIXME: We will, however, have to check
1143  // for the presence of a copy constructor in C++98/03 mode.
1144  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
1145      RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1146    if (ICS) {
1147      ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1148      ICS->Standard.First = ICK_Identity;
1149      ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1150      ICS->Standard.Third = ICK_Identity;
1151      ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1152      ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
1153      ICS->Standard.ReferenceBinding = true;
1154      ICS->Standard.DirectBinding = false;
1155    } else {
1156      // FIXME: Binding to a subobject of the rvalue is going to require
1157      // more AST annotation than this.
1158      ImpCastExprToType(Init, T1);
1159    }
1160    return false;
1161  }
1162
1163  //       -- Otherwise, a temporary of type “cv1 T1” is created and
1164  //          initialized from the initializer expression using the
1165  //          rules for a non-reference copy initialization (8.5). The
1166  //          reference is then bound to the temporary. If T1 is
1167  //          reference-related to T2, cv1 must be the same
1168  //          cv-qualification as, or greater cv-qualification than,
1169  //          cv2; otherwise, the program is ill-formed.
1170  if (RefRelationship == Ref_Related) {
1171    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1172    // we would be reference-compatible or reference-compatible with
1173    // added qualification. But that wasn't the case, so the reference
1174    // initialization fails.
1175    if (!ICS)
1176      Diag(Init->getSourceRange().getBegin(),
1177           diag::err_reference_init_drops_quals,
1178           T1.getAsString(),
1179           InitLvalue != Expr::LV_Valid? "temporary" : "value",
1180           T2.getAsString(), Init->getSourceRange());
1181    return true;
1182  }
1183
1184  // Actually try to convert the initializer to T1.
1185  if (ICS) {
1186    /// C++ [over.ics.ref]p2:
1187    ///
1188    ///   When a parameter of reference type is not bound directly to
1189    ///   an argument expression, the conversion sequence is the one
1190    ///   required to convert the argument expression to the
1191    ///   underlying type of the reference according to
1192    ///   13.3.3.1. Conceptually, this conversion sequence corresponds
1193    ///   to copy-initializing a temporary of the underlying type with
1194    ///   the argument expression. Any difference in top-level
1195    ///   cv-qualification is subsumed by the initialization itself
1196    ///   and does not constitute a conversion.
1197    *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
1198    return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1199  } else {
1200    return PerformImplicitConversion(Init, T1);
1201  }
1202}
1203