SemaInit.cpp revision e5eee5a52d98021de862b7965c88577598d52ccb
1//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
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 initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
14// This file also implements Sema::CheckInitializerTypes.
15//
16//===----------------------------------------------------------------------===//
17
18#include "SemaInit.h"
19#include "Lookup.h"
20#include "Sema.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Parse/Designator.h"
23#include "clang/AST/ASTContext.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "llvm/Support/ErrorHandling.h"
28#include <map>
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
35static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
36  const ArrayType *AT = Context.getAsArrayType(DeclType);
37  if (!AT) return 0;
38
39  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
40    return 0;
41
42  // See if this is a string literal or @encode.
43  Init = Init->IgnoreParens();
44
45  // Handle @encode, which is a narrow string.
46  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
47    return Init;
48
49  // Otherwise we can only handle string literals.
50  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
51  if (SL == 0) return 0;
52
53  QualType ElemTy = Context.getCanonicalType(AT->getElementType());
54  // char array can be initialized with a narrow string.
55  // Only allow char x[] = "foo";  not char x[] = L"foo";
56  if (!SL->isWide())
57    return ElemTy->isCharType() ? Init : 0;
58
59  // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
60  // correction from DR343): "An array with element type compatible with a
61  // qualified or unqualified version of wchar_t may be initialized by a wide
62  // string literal, optionally enclosed in braces."
63  if (Context.typesAreCompatible(Context.getWCharType(),
64                                 ElemTy.getUnqualifiedType()))
65    return Init;
66
67  return 0;
68}
69
70static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
71  // Get the length of the string as parsed.
72  uint64_t StrLength =
73    cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
74
75
76  const ArrayType *AT = S.Context.getAsArrayType(DeclT);
77  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
78    // C99 6.7.8p14. We have an array of character type with unknown size
79    // being initialized to a string literal.
80    llvm::APSInt ConstVal(32);
81    ConstVal = StrLength;
82    // Return a new array type (C99 6.7.8p22).
83    DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
84                                           ConstVal,
85                                           ArrayType::Normal, 0);
86    return;
87  }
88
89  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
90
91  // C99 6.7.8p14. We have an array of character type with known size.  However,
92  // the size may be smaller or larger than the string we are initializing.
93  // FIXME: Avoid truncation for 64-bit length strings.
94  if (StrLength-1 > CAT->getSize().getZExtValue())
95    S.Diag(Str->getSourceRange().getBegin(),
96           diag::warn_initializer_string_for_char_array_too_long)
97      << Str->getSourceRange();
98
99  // Set the type to the actual size that we are initializing.  If we have
100  // something like:
101  //   char x[1] = "foo";
102  // then this will set the string literal's type to char[1].
103  Str->setType(DeclT);
104}
105
106//===----------------------------------------------------------------------===//
107// Semantic checking for initializer lists.
108//===----------------------------------------------------------------------===//
109
110/// @brief Semantic checking for initializer lists.
111///
112/// The InitListChecker class contains a set of routines that each
113/// handle the initialization of a certain kind of entity, e.g.,
114/// arrays, vectors, struct/union types, scalars, etc. The
115/// InitListChecker itself performs a recursive walk of the subobject
116/// structure of the type to be initialized, while stepping through
117/// the initializer list one element at a time. The IList and Index
118/// parameters to each of the Check* routines contain the active
119/// (syntactic) initializer list and the index into that initializer
120/// list that represents the current initializer. Each routine is
121/// responsible for moving that Index forward as it consumes elements.
122///
123/// Each Check* routine also has a StructuredList/StructuredIndex
124/// arguments, which contains the current the "structured" (semantic)
125/// initializer list and the index into that initializer list where we
126/// are copying initializers as we map them over to the semantic
127/// list. Once we have completed our recursive walk of the subobject
128/// structure, we will have constructed a full semantic initializer
129/// list.
130///
131/// C99 designators cause changes in the initializer list traversal,
132/// because they make the initialization "jump" into a specific
133/// subobject and then continue the initialization from that
134/// point. CheckDesignatedInitializer() recursively steps into the
135/// designated subobject and manages backing out the recursion to
136/// initialize the subobjects after the one designated.
137namespace {
138class InitListChecker {
139  Sema &SemaRef;
140  bool hadError;
141  std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
142  InitListExpr *FullyStructuredList;
143
144  void CheckImplicitInitList(const InitializedEntity &Entity,
145                             InitListExpr *ParentIList, QualType T,
146                             unsigned &Index, InitListExpr *StructuredList,
147                             unsigned &StructuredIndex,
148                             bool TopLevelObject = false);
149  void CheckExplicitInitList(const InitializedEntity &Entity,
150                             InitListExpr *IList, QualType &T,
151                             unsigned &Index, InitListExpr *StructuredList,
152                             unsigned &StructuredIndex,
153                             bool TopLevelObject = false);
154  void CheckListElementTypes(const InitializedEntity &Entity,
155                             InitListExpr *IList, QualType &DeclType,
156                             bool SubobjectIsDesignatorContext,
157                             unsigned &Index,
158                             InitListExpr *StructuredList,
159                             unsigned &StructuredIndex,
160                             bool TopLevelObject = false);
161  void CheckSubElementType(const InitializedEntity &Entity,
162                           InitListExpr *IList, QualType ElemType,
163                           unsigned &Index,
164                           InitListExpr *StructuredList,
165                           unsigned &StructuredIndex);
166  void CheckScalarType(const InitializedEntity &Entity,
167                       InitListExpr *IList, QualType DeclType,
168                       unsigned &Index,
169                       InitListExpr *StructuredList,
170                       unsigned &StructuredIndex);
171  void CheckReferenceType(const InitializedEntity &Entity,
172                          InitListExpr *IList, QualType DeclType,
173                          unsigned &Index,
174                          InitListExpr *StructuredList,
175                          unsigned &StructuredIndex);
176  void CheckVectorType(const InitializedEntity &Entity,
177                       InitListExpr *IList, QualType DeclType, unsigned &Index,
178                       InitListExpr *StructuredList,
179                       unsigned &StructuredIndex);
180  void CheckStructUnionTypes(const InitializedEntity &Entity,
181                             InitListExpr *IList, QualType DeclType,
182                             RecordDecl::field_iterator Field,
183                             bool SubobjectIsDesignatorContext, unsigned &Index,
184                             InitListExpr *StructuredList,
185                             unsigned &StructuredIndex,
186                             bool TopLevelObject = false);
187  void CheckArrayType(const InitializedEntity &Entity,
188                      InitListExpr *IList, QualType &DeclType,
189                      llvm::APSInt elementIndex,
190                      bool SubobjectIsDesignatorContext, unsigned &Index,
191                      InitListExpr *StructuredList,
192                      unsigned &StructuredIndex);
193  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
194                                  InitListExpr *IList, DesignatedInitExpr *DIE,
195                                  unsigned DesigIdx,
196                                  QualType &CurrentObjectType,
197                                  RecordDecl::field_iterator *NextField,
198                                  llvm::APSInt *NextElementIndex,
199                                  unsigned &Index,
200                                  InitListExpr *StructuredList,
201                                  unsigned &StructuredIndex,
202                                  bool FinishSubobjectInit,
203                                  bool TopLevelObject);
204  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
205                                           QualType CurrentObjectType,
206                                           InitListExpr *StructuredList,
207                                           unsigned StructuredIndex,
208                                           SourceRange InitRange);
209  void UpdateStructuredListElement(InitListExpr *StructuredList,
210                                   unsigned &StructuredIndex,
211                                   Expr *expr);
212  int numArrayElements(QualType DeclType);
213  int numStructUnionElements(QualType DeclType);
214
215  void FillInValueInitForField(unsigned Init, FieldDecl *Field,
216                               const InitializedEntity &ParentEntity,
217                               InitListExpr *ILE, bool &RequiresSecondPass);
218  void FillInValueInitializations(const InitializedEntity &Entity,
219                                  InitListExpr *ILE, bool &RequiresSecondPass);
220public:
221  InitListChecker(Sema &S, const InitializedEntity &Entity,
222                  InitListExpr *IL, QualType &T);
223  bool HadError() { return hadError; }
224
225  // @brief Retrieves the fully-structured initializer list used for
226  // semantic analysis and code generation.
227  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
228};
229} // end anonymous namespace
230
231void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
232                                        const InitializedEntity &ParentEntity,
233                                              InitListExpr *ILE,
234                                              bool &RequiresSecondPass) {
235  SourceLocation Loc = ILE->getSourceRange().getBegin();
236  unsigned NumInits = ILE->getNumInits();
237  InitializedEntity MemberEntity
238    = InitializedEntity::InitializeMember(Field, &ParentEntity);
239  if (Init >= NumInits || !ILE->getInit(Init)) {
240    // FIXME: We probably don't need to handle references
241    // specially here, since value-initialization of references is
242    // handled in InitializationSequence.
243    if (Field->getType()->isReferenceType()) {
244      // C++ [dcl.init.aggr]p9:
245      //   If an incomplete or empty initializer-list leaves a
246      //   member of reference type uninitialized, the program is
247      //   ill-formed.
248      SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
249        << Field->getType()
250        << ILE->getSyntacticForm()->getSourceRange();
251      SemaRef.Diag(Field->getLocation(),
252                   diag::note_uninit_reference_member);
253      hadError = true;
254      return;
255    }
256
257    InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
258                                                              true);
259    InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
260    if (!InitSeq) {
261      InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
262      hadError = true;
263      return;
264    }
265
266    Sema::OwningExprResult MemberInit
267      = InitSeq.Perform(SemaRef, MemberEntity, Kind,
268                        Sema::MultiExprArg(SemaRef, 0, 0));
269    if (MemberInit.isInvalid()) {
270      hadError = true;
271      return;
272    }
273
274    if (hadError) {
275      // Do nothing
276    } else if (Init < NumInits) {
277      ILE->setInit(Init, MemberInit.takeAs<Expr>());
278    } else if (InitSeq.getKind()
279                 == InitializationSequence::ConstructorInitialization) {
280      // Value-initialization requires a constructor call, so
281      // extend the initializer list to include the constructor
282      // call and make a note that we'll need to take another pass
283      // through the initializer list.
284      ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
285      RequiresSecondPass = true;
286    }
287  } else if (InitListExpr *InnerILE
288               = dyn_cast<InitListExpr>(ILE->getInit(Init)))
289    FillInValueInitializations(MemberEntity, InnerILE,
290                               RequiresSecondPass);
291}
292
293/// Recursively replaces NULL values within the given initializer list
294/// with expressions that perform value-initialization of the
295/// appropriate type.
296void
297InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
298                                            InitListExpr *ILE,
299                                            bool &RequiresSecondPass) {
300  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
301         "Should not have void type");
302  SourceLocation Loc = ILE->getSourceRange().getBegin();
303  if (ILE->getSyntacticForm())
304    Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
305
306  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
307    if (RType->getDecl()->isUnion() &&
308        ILE->getInitializedFieldInUnion())
309      FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
310                              Entity, ILE, RequiresSecondPass);
311    else {
312      unsigned Init = 0;
313      for (RecordDecl::field_iterator
314             Field = RType->getDecl()->field_begin(),
315             FieldEnd = RType->getDecl()->field_end();
316           Field != FieldEnd; ++Field) {
317        if (Field->isUnnamedBitfield())
318          continue;
319
320        if (hadError)
321          return;
322
323        FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
324        if (hadError)
325          return;
326
327        ++Init;
328
329        // Only look at the first initialization of a union.
330        if (RType->getDecl()->isUnion())
331          break;
332      }
333    }
334
335    return;
336  }
337
338  QualType ElementType;
339
340  InitializedEntity ElementEntity = Entity;
341  unsigned NumInits = ILE->getNumInits();
342  unsigned NumElements = NumInits;
343  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
344    ElementType = AType->getElementType();
345    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
346      NumElements = CAType->getSize().getZExtValue();
347    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
348                                                         0, Entity);
349  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
350    ElementType = VType->getElementType();
351    NumElements = VType->getNumElements();
352    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
353                                                         0, Entity);
354  } else
355    ElementType = ILE->getType();
356
357
358  for (unsigned Init = 0; Init != NumElements; ++Init) {
359    if (hadError)
360      return;
361
362    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
363        ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
364      ElementEntity.setElementIndex(Init);
365
366    if (Init >= NumInits || !ILE->getInit(Init)) {
367      InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
368                                                                true);
369      InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
370      if (!InitSeq) {
371        InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
372        hadError = true;
373        return;
374      }
375
376      Sema::OwningExprResult ElementInit
377        = InitSeq.Perform(SemaRef, ElementEntity, Kind,
378                          Sema::MultiExprArg(SemaRef, 0, 0));
379      if (ElementInit.isInvalid()) {
380        hadError = true;
381        return;
382      }
383
384      if (hadError) {
385        // Do nothing
386      } else if (Init < NumInits) {
387        ILE->setInit(Init, ElementInit.takeAs<Expr>());
388      } else if (InitSeq.getKind()
389                   == InitializationSequence::ConstructorInitialization) {
390        // Value-initialization requires a constructor call, so
391        // extend the initializer list to include the constructor
392        // call and make a note that we'll need to take another pass
393        // through the initializer list.
394        ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
395        RequiresSecondPass = true;
396      }
397    } else if (InitListExpr *InnerILE
398                 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
399      FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
400  }
401}
402
403
404InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
405                                 InitListExpr *IL, QualType &T)
406  : SemaRef(S) {
407  hadError = false;
408
409  unsigned newIndex = 0;
410  unsigned newStructuredIndex = 0;
411  FullyStructuredList
412    = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
413  CheckExplicitInitList(Entity, IL, T, newIndex,
414                        FullyStructuredList, newStructuredIndex,
415                        /*TopLevelObject=*/true);
416
417  if (!hadError) {
418    bool RequiresSecondPass = false;
419    FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
420    if (RequiresSecondPass && !hadError)
421      FillInValueInitializations(Entity, FullyStructuredList,
422                                 RequiresSecondPass);
423  }
424}
425
426int InitListChecker::numArrayElements(QualType DeclType) {
427  // FIXME: use a proper constant
428  int maxElements = 0x7FFFFFFF;
429  if (const ConstantArrayType *CAT =
430        SemaRef.Context.getAsConstantArrayType(DeclType)) {
431    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
432  }
433  return maxElements;
434}
435
436int InitListChecker::numStructUnionElements(QualType DeclType) {
437  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
438  int InitializableMembers = 0;
439  for (RecordDecl::field_iterator
440         Field = structDecl->field_begin(),
441         FieldEnd = structDecl->field_end();
442       Field != FieldEnd; ++Field) {
443    if ((*Field)->getIdentifier() || !(*Field)->isBitField())
444      ++InitializableMembers;
445  }
446  if (structDecl->isUnion())
447    return std::min(InitializableMembers, 1);
448  return InitializableMembers - structDecl->hasFlexibleArrayMember();
449}
450
451void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
452                                            InitListExpr *ParentIList,
453                                            QualType T, unsigned &Index,
454                                            InitListExpr *StructuredList,
455                                            unsigned &StructuredIndex,
456                                            bool TopLevelObject) {
457  int maxElements = 0;
458
459  if (T->isArrayType())
460    maxElements = numArrayElements(T);
461  else if (T->isRecordType())
462    maxElements = numStructUnionElements(T);
463  else if (T->isVectorType())
464    maxElements = T->getAs<VectorType>()->getNumElements();
465  else
466    assert(0 && "CheckImplicitInitList(): Illegal type");
467
468  if (maxElements == 0) {
469    SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
470                  diag::err_implicit_empty_initializer);
471    ++Index;
472    hadError = true;
473    return;
474  }
475
476  // Build a structured initializer list corresponding to this subobject.
477  InitListExpr *StructuredSubobjectInitList
478    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
479                                 StructuredIndex,
480          SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
481                      ParentIList->getSourceRange().getEnd()));
482  unsigned StructuredSubobjectInitIndex = 0;
483
484  // Check the element types and build the structural subobject.
485  unsigned StartIndex = Index;
486  CheckListElementTypes(Entity, ParentIList, T,
487                        /*SubobjectIsDesignatorContext=*/false, Index,
488                        StructuredSubobjectInitList,
489                        StructuredSubobjectInitIndex,
490                        TopLevelObject);
491  unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
492  StructuredSubobjectInitList->setType(T);
493
494  // Update the structured sub-object initializer so that it's ending
495  // range corresponds with the end of the last initializer it used.
496  if (EndIndex < ParentIList->getNumInits()) {
497    SourceLocation EndLoc
498      = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
499    StructuredSubobjectInitList->setRBraceLoc(EndLoc);
500  }
501
502  // Warn about missing braces.
503  if (T->isArrayType() || T->isRecordType()) {
504    SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
505                 diag::warn_missing_braces)
506    << StructuredSubobjectInitList->getSourceRange()
507    << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
508                                  "{")
509    << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
510                                      StructuredSubobjectInitList->getLocEnd()),
511                                  "}");
512  }
513}
514
515void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
516                                            InitListExpr *IList, QualType &T,
517                                            unsigned &Index,
518                                            InitListExpr *StructuredList,
519                                            unsigned &StructuredIndex,
520                                            bool TopLevelObject) {
521  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
522  SyntacticToSemantic[IList] = StructuredList;
523  StructuredList->setSyntacticForm(IList);
524  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
525                        Index, StructuredList, StructuredIndex, TopLevelObject);
526  IList->setType(T.getNonReferenceType());
527  StructuredList->setType(T.getNonReferenceType());
528  if (hadError)
529    return;
530
531  if (Index < IList->getNumInits()) {
532    // We have leftover initializers
533    if (StructuredIndex == 1 &&
534        IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
535      unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
536      if (SemaRef.getLangOptions().CPlusPlus) {
537        DK = diag::err_excess_initializers_in_char_array_initializer;
538        hadError = true;
539      }
540      // Special-case
541      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
542        << IList->getInit(Index)->getSourceRange();
543    } else if (!T->isIncompleteType()) {
544      // Don't complain for incomplete types, since we'll get an error
545      // elsewhere
546      QualType CurrentObjectType = StructuredList->getType();
547      int initKind =
548        CurrentObjectType->isArrayType()? 0 :
549        CurrentObjectType->isVectorType()? 1 :
550        CurrentObjectType->isScalarType()? 2 :
551        CurrentObjectType->isUnionType()? 3 :
552        4;
553
554      unsigned DK = diag::warn_excess_initializers;
555      if (SemaRef.getLangOptions().CPlusPlus) {
556        DK = diag::err_excess_initializers;
557        hadError = true;
558      }
559      if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
560        DK = diag::err_excess_initializers;
561        hadError = true;
562      }
563
564      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
565        << initKind << IList->getInit(Index)->getSourceRange();
566    }
567  }
568
569  if (T->isScalarType() && !TopLevelObject)
570    SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
571      << IList->getSourceRange()
572      << FixItHint::CreateRemoval(IList->getLocStart())
573      << FixItHint::CreateRemoval(IList->getLocEnd());
574}
575
576void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
577                                            InitListExpr *IList,
578                                            QualType &DeclType,
579                                            bool SubobjectIsDesignatorContext,
580                                            unsigned &Index,
581                                            InitListExpr *StructuredList,
582                                            unsigned &StructuredIndex,
583                                            bool TopLevelObject) {
584  if (DeclType->isScalarType()) {
585    CheckScalarType(Entity, IList, DeclType, Index,
586                    StructuredList, StructuredIndex);
587  } else if (DeclType->isVectorType()) {
588    CheckVectorType(Entity, IList, DeclType, Index,
589                    StructuredList, StructuredIndex);
590  } else if (DeclType->isAggregateType()) {
591    if (DeclType->isRecordType()) {
592      RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
593      CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
594                            SubobjectIsDesignatorContext, Index,
595                            StructuredList, StructuredIndex,
596                            TopLevelObject);
597    } else if (DeclType->isArrayType()) {
598      llvm::APSInt Zero(
599                      SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
600                      false);
601      CheckArrayType(Entity, IList, DeclType, Zero,
602                     SubobjectIsDesignatorContext, Index,
603                     StructuredList, StructuredIndex);
604    } else
605      assert(0 && "Aggregate that isn't a structure or array?!");
606  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
607    // This type is invalid, issue a diagnostic.
608    ++Index;
609    SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
610      << DeclType;
611    hadError = true;
612  } else if (DeclType->isRecordType()) {
613    // C++ [dcl.init]p14:
614    //   [...] If the class is an aggregate (8.5.1), and the initializer
615    //   is a brace-enclosed list, see 8.5.1.
616    //
617    // Note: 8.5.1 is handled below; here, we diagnose the case where
618    // we have an initializer list and a destination type that is not
619    // an aggregate.
620    // FIXME: In C++0x, this is yet another form of initialization.
621    SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
622      << DeclType << IList->getSourceRange();
623    hadError = true;
624  } else if (DeclType->isReferenceType()) {
625    CheckReferenceType(Entity, IList, DeclType, Index,
626                       StructuredList, StructuredIndex);
627  } else if (DeclType->isObjCObjectType()) {
628    SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
629      << DeclType;
630    hadError = true;
631  } else {
632    SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
633      << DeclType;
634    hadError = true;
635  }
636}
637
638void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
639                                          InitListExpr *IList,
640                                          QualType ElemType,
641                                          unsigned &Index,
642                                          InitListExpr *StructuredList,
643                                          unsigned &StructuredIndex) {
644  Expr *expr = IList->getInit(Index);
645  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
646    unsigned newIndex = 0;
647    unsigned newStructuredIndex = 0;
648    InitListExpr *newStructuredList
649      = getStructuredSubobjectInit(IList, Index, ElemType,
650                                   StructuredList, StructuredIndex,
651                                   SubInitList->getSourceRange());
652    CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
653                          newStructuredList, newStructuredIndex);
654    ++StructuredIndex;
655    ++Index;
656  } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
657    CheckStringInit(Str, ElemType, SemaRef);
658    UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
659    ++Index;
660  } else if (ElemType->isScalarType()) {
661    CheckScalarType(Entity, IList, ElemType, Index,
662                    StructuredList, StructuredIndex);
663  } else if (ElemType->isReferenceType()) {
664    CheckReferenceType(Entity, IList, ElemType, Index,
665                       StructuredList, StructuredIndex);
666  } else {
667    if (SemaRef.getLangOptions().CPlusPlus) {
668      // C++ [dcl.init.aggr]p12:
669      //   All implicit type conversions (clause 4) are considered when
670      //   initializing the aggregate member with an ini- tializer from
671      //   an initializer-list. If the initializer can initialize a
672      //   member, the member is initialized. [...]
673
674      // FIXME: Better EqualLoc?
675      InitializationKind Kind =
676        InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
677      InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
678
679      if (Seq) {
680        Sema::OwningExprResult Result =
681          Seq.Perform(SemaRef, Entity, Kind,
682                      Sema::MultiExprArg(SemaRef, (void **)&expr, 1));
683        if (Result.isInvalid())
684          hadError = true;
685
686        UpdateStructuredListElement(StructuredList, StructuredIndex,
687                                    Result.takeAs<Expr>());
688        ++Index;
689        return;
690      }
691
692      // Fall through for subaggregate initialization
693    } else {
694      // C99 6.7.8p13:
695      //
696      //   The initializer for a structure or union object that has
697      //   automatic storage duration shall be either an initializer
698      //   list as described below, or a single expression that has
699      //   compatible structure or union type. In the latter case, the
700      //   initial value of the object, including unnamed members, is
701      //   that of the expression.
702      if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
703          SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
704        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
705        ++Index;
706        return;
707      }
708
709      // Fall through for subaggregate initialization
710    }
711
712    // C++ [dcl.init.aggr]p12:
713    //
714    //   [...] Otherwise, if the member is itself a non-empty
715    //   subaggregate, brace elision is assumed and the initializer is
716    //   considered for the initialization of the first member of
717    //   the subaggregate.
718    if (ElemType->isAggregateType() || ElemType->isVectorType()) {
719      CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
720                            StructuredIndex);
721      ++StructuredIndex;
722    } else {
723      // We cannot initialize this element, so let
724      // PerformCopyInitialization produce the appropriate diagnostic.
725      SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
726                                        SemaRef.Owned(expr));
727      IList->setInit(Index, 0);
728      hadError = true;
729      ++Index;
730      ++StructuredIndex;
731    }
732  }
733}
734
735void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
736                                      InitListExpr *IList, QualType DeclType,
737                                      unsigned &Index,
738                                      InitListExpr *StructuredList,
739                                      unsigned &StructuredIndex) {
740  if (Index < IList->getNumInits()) {
741    Expr *expr = IList->getInit(Index);
742    if (isa<InitListExpr>(expr)) {
743      SemaRef.Diag(IList->getLocStart(),
744                    diag::err_many_braces_around_scalar_init)
745        << IList->getSourceRange();
746      hadError = true;
747      ++Index;
748      ++StructuredIndex;
749      return;
750    } else if (isa<DesignatedInitExpr>(expr)) {
751      SemaRef.Diag(expr->getSourceRange().getBegin(),
752                    diag::err_designator_for_scalar_init)
753        << DeclType << expr->getSourceRange();
754      hadError = true;
755      ++Index;
756      ++StructuredIndex;
757      return;
758    }
759
760    Sema::OwningExprResult Result =
761      SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
762                                        SemaRef.Owned(expr));
763
764    Expr *ResultExpr = 0;
765
766    if (Result.isInvalid())
767      hadError = true; // types weren't compatible.
768    else {
769      ResultExpr = Result.takeAs<Expr>();
770
771      if (ResultExpr != expr) {
772        // The type was promoted, update initializer list.
773        IList->setInit(Index, ResultExpr);
774      }
775    }
776    if (hadError)
777      ++StructuredIndex;
778    else
779      UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
780    ++Index;
781  } else {
782    SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
783      << IList->getSourceRange();
784    hadError = true;
785    ++Index;
786    ++StructuredIndex;
787    return;
788  }
789}
790
791void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
792                                         InitListExpr *IList, QualType DeclType,
793                                         unsigned &Index,
794                                         InitListExpr *StructuredList,
795                                         unsigned &StructuredIndex) {
796  if (Index < IList->getNumInits()) {
797    Expr *expr = IList->getInit(Index);
798    if (isa<InitListExpr>(expr)) {
799      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
800        << DeclType << IList->getSourceRange();
801      hadError = true;
802      ++Index;
803      ++StructuredIndex;
804      return;
805    }
806
807    Sema::OwningExprResult Result =
808      SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
809                                        SemaRef.Owned(expr));
810
811    if (Result.isInvalid())
812      hadError = true;
813
814    expr = Result.takeAs<Expr>();
815    IList->setInit(Index, expr);
816
817    if (hadError)
818      ++StructuredIndex;
819    else
820      UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
821    ++Index;
822  } else {
823    // FIXME: It would be wonderful if we could point at the actual member. In
824    // general, it would be useful to pass location information down the stack,
825    // so that we know the location (or decl) of the "current object" being
826    // initialized.
827    SemaRef.Diag(IList->getLocStart(),
828                  diag::err_init_reference_member_uninitialized)
829      << DeclType
830      << IList->getSourceRange();
831    hadError = true;
832    ++Index;
833    ++StructuredIndex;
834    return;
835  }
836}
837
838void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
839                                      InitListExpr *IList, QualType DeclType,
840                                      unsigned &Index,
841                                      InitListExpr *StructuredList,
842                                      unsigned &StructuredIndex) {
843  if (Index < IList->getNumInits()) {
844    const VectorType *VT = DeclType->getAs<VectorType>();
845    unsigned maxElements = VT->getNumElements();
846    unsigned numEltsInit = 0;
847    QualType elementType = VT->getElementType();
848
849    if (!SemaRef.getLangOptions().OpenCL) {
850      InitializedEntity ElementEntity =
851        InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
852
853      for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
854        // Don't attempt to go past the end of the init list
855        if (Index >= IList->getNumInits())
856          break;
857
858        ElementEntity.setElementIndex(Index);
859        CheckSubElementType(ElementEntity, IList, elementType, Index,
860                            StructuredList, StructuredIndex);
861      }
862    } else {
863      InitializedEntity ElementEntity =
864        InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
865
866      // OpenCL initializers allows vectors to be constructed from vectors.
867      for (unsigned i = 0; i < maxElements; ++i) {
868        // Don't attempt to go past the end of the init list
869        if (Index >= IList->getNumInits())
870          break;
871
872        ElementEntity.setElementIndex(Index);
873
874        QualType IType = IList->getInit(Index)->getType();
875        if (!IType->isVectorType()) {
876          CheckSubElementType(ElementEntity, IList, elementType, Index,
877                              StructuredList, StructuredIndex);
878          ++numEltsInit;
879        } else {
880          const VectorType *IVT = IType->getAs<VectorType>();
881          unsigned numIElts = IVT->getNumElements();
882          QualType VecType = SemaRef.Context.getExtVectorType(elementType,
883                                                              numIElts);
884          CheckSubElementType(ElementEntity, IList, VecType, Index,
885                              StructuredList, StructuredIndex);
886          numEltsInit += numIElts;
887        }
888      }
889    }
890
891    // OpenCL requires all elements to be initialized.
892    if (numEltsInit != maxElements)
893      if (SemaRef.getLangOptions().OpenCL)
894        SemaRef.Diag(IList->getSourceRange().getBegin(),
895                     diag::err_vector_incorrect_num_initializers)
896          << (numEltsInit < maxElements) << maxElements << numEltsInit;
897  }
898}
899
900void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
901                                     InitListExpr *IList, QualType &DeclType,
902                                     llvm::APSInt elementIndex,
903                                     bool SubobjectIsDesignatorContext,
904                                     unsigned &Index,
905                                     InitListExpr *StructuredList,
906                                     unsigned &StructuredIndex) {
907  // Check for the special-case of initializing an array with a string.
908  if (Index < IList->getNumInits()) {
909    if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
910                                 SemaRef.Context)) {
911      CheckStringInit(Str, DeclType, SemaRef);
912      // We place the string literal directly into the resulting
913      // initializer list. This is the only place where the structure
914      // of the structured initializer list doesn't match exactly,
915      // because doing so would involve allocating one character
916      // constant for each string.
917      UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
918      StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
919      ++Index;
920      return;
921    }
922  }
923  if (const VariableArrayType *VAT =
924        SemaRef.Context.getAsVariableArrayType(DeclType)) {
925    // Check for VLAs; in standard C it would be possible to check this
926    // earlier, but I don't know where clang accepts VLAs (gcc accepts
927    // them in all sorts of strange places).
928    SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
929                  diag::err_variable_object_no_init)
930      << VAT->getSizeExpr()->getSourceRange();
931    hadError = true;
932    ++Index;
933    ++StructuredIndex;
934    return;
935  }
936
937  // We might know the maximum number of elements in advance.
938  llvm::APSInt maxElements(elementIndex.getBitWidth(),
939                           elementIndex.isUnsigned());
940  bool maxElementsKnown = false;
941  if (const ConstantArrayType *CAT =
942        SemaRef.Context.getAsConstantArrayType(DeclType)) {
943    maxElements = CAT->getSize();
944    elementIndex.extOrTrunc(maxElements.getBitWidth());
945    elementIndex.setIsUnsigned(maxElements.isUnsigned());
946    maxElementsKnown = true;
947  }
948
949  QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
950                             ->getElementType();
951  while (Index < IList->getNumInits()) {
952    Expr *Init = IList->getInit(Index);
953    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
954      // If we're not the subobject that matches up with the '{' for
955      // the designator, we shouldn't be handling the
956      // designator. Return immediately.
957      if (!SubobjectIsDesignatorContext)
958        return;
959
960      // Handle this designated initializer. elementIndex will be
961      // updated to be the next array element we'll initialize.
962      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
963                                     DeclType, 0, &elementIndex, Index,
964                                     StructuredList, StructuredIndex, true,
965                                     false)) {
966        hadError = true;
967        continue;
968      }
969
970      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
971        maxElements.extend(elementIndex.getBitWidth());
972      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
973        elementIndex.extend(maxElements.getBitWidth());
974      elementIndex.setIsUnsigned(maxElements.isUnsigned());
975
976      // If the array is of incomplete type, keep track of the number of
977      // elements in the initializer.
978      if (!maxElementsKnown && elementIndex > maxElements)
979        maxElements = elementIndex;
980
981      continue;
982    }
983
984    // If we know the maximum number of elements, and we've already
985    // hit it, stop consuming elements in the initializer list.
986    if (maxElementsKnown && elementIndex == maxElements)
987      break;
988
989    InitializedEntity ElementEntity =
990      InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
991                                           Entity);
992    // Check this element.
993    CheckSubElementType(ElementEntity, IList, elementType, Index,
994                        StructuredList, StructuredIndex);
995    ++elementIndex;
996
997    // If the array is of incomplete type, keep track of the number of
998    // elements in the initializer.
999    if (!maxElementsKnown && elementIndex > maxElements)
1000      maxElements = elementIndex;
1001  }
1002  if (!hadError && DeclType->isIncompleteArrayType()) {
1003    // If this is an incomplete array type, the actual type needs to
1004    // be calculated here.
1005    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1006    if (maxElements == Zero) {
1007      // Sizing an array implicitly to zero is not allowed by ISO C,
1008      // but is supported by GNU.
1009      SemaRef.Diag(IList->getLocStart(),
1010                    diag::ext_typecheck_zero_array_size);
1011    }
1012
1013    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1014                                                     ArrayType::Normal, 0);
1015  }
1016}
1017
1018void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1019                                            InitListExpr *IList,
1020                                            QualType DeclType,
1021                                            RecordDecl::field_iterator Field,
1022                                            bool SubobjectIsDesignatorContext,
1023                                            unsigned &Index,
1024                                            InitListExpr *StructuredList,
1025                                            unsigned &StructuredIndex,
1026                                            bool TopLevelObject) {
1027  RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1028
1029  // If the record is invalid, some of it's members are invalid. To avoid
1030  // confusion, we forgo checking the intializer for the entire record.
1031  if (structDecl->isInvalidDecl()) {
1032    hadError = true;
1033    return;
1034  }
1035
1036  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1037    // Value-initialize the first named member of the union.
1038    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1039    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1040         Field != FieldEnd; ++Field) {
1041      if (Field->getDeclName()) {
1042        StructuredList->setInitializedFieldInUnion(*Field);
1043        break;
1044      }
1045    }
1046    return;
1047  }
1048
1049  // If structDecl is a forward declaration, this loop won't do
1050  // anything except look at designated initializers; That's okay,
1051  // because an error should get printed out elsewhere. It might be
1052  // worthwhile to skip over the rest of the initializer, though.
1053  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1054  RecordDecl::field_iterator FieldEnd = RD->field_end();
1055  bool InitializedSomething = false;
1056  bool CheckForMissingFields = true;
1057  while (Index < IList->getNumInits()) {
1058    Expr *Init = IList->getInit(Index);
1059
1060    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1061      // If we're not the subobject that matches up with the '{' for
1062      // the designator, we shouldn't be handling the
1063      // designator. Return immediately.
1064      if (!SubobjectIsDesignatorContext)
1065        return;
1066
1067      // Handle this designated initializer. Field will be updated to
1068      // the next field that we'll be initializing.
1069      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1070                                     DeclType, &Field, 0, Index,
1071                                     StructuredList, StructuredIndex,
1072                                     true, TopLevelObject))
1073        hadError = true;
1074
1075      InitializedSomething = true;
1076
1077      // Disable check for missing fields when designators are used.
1078      // This matches gcc behaviour.
1079      CheckForMissingFields = false;
1080      continue;
1081    }
1082
1083    if (Field == FieldEnd) {
1084      // We've run out of fields. We're done.
1085      break;
1086    }
1087
1088    // We've already initialized a member of a union. We're done.
1089    if (InitializedSomething && DeclType->isUnionType())
1090      break;
1091
1092    // If we've hit the flexible array member at the end, we're done.
1093    if (Field->getType()->isIncompleteArrayType())
1094      break;
1095
1096    if (Field->isUnnamedBitfield()) {
1097      // Don't initialize unnamed bitfields, e.g. "int : 20;"
1098      ++Field;
1099      continue;
1100    }
1101
1102    InitializedEntity MemberEntity =
1103      InitializedEntity::InitializeMember(*Field, &Entity);
1104    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1105                        StructuredList, StructuredIndex);
1106    InitializedSomething = true;
1107
1108    if (DeclType->isUnionType()) {
1109      // Initialize the first field within the union.
1110      StructuredList->setInitializedFieldInUnion(*Field);
1111    }
1112
1113    ++Field;
1114  }
1115
1116  // Emit warnings for missing struct field initializers.
1117  if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
1118      !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1119    // It is possible we have one or more unnamed bitfields remaining.
1120    // Find first (if any) named field and emit warning.
1121    for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1122         it != end; ++it) {
1123      if (!it->isUnnamedBitfield()) {
1124        SemaRef.Diag(IList->getSourceRange().getEnd(),
1125                     diag::warn_missing_field_initializers) << it->getName();
1126        break;
1127      }
1128    }
1129  }
1130
1131  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1132      Index >= IList->getNumInits())
1133    return;
1134
1135  // Handle GNU flexible array initializers.
1136  if (!TopLevelObject &&
1137      (!isa<InitListExpr>(IList->getInit(Index)) ||
1138       cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
1139    SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1140                  diag::err_flexible_array_init_nonempty)
1141      << IList->getInit(Index)->getSourceRange().getBegin();
1142    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1143      << *Field;
1144    hadError = true;
1145    ++Index;
1146    return;
1147  } else {
1148    SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
1149                 diag::ext_flexible_array_init)
1150      << IList->getInit(Index)->getSourceRange().getBegin();
1151    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1152      << *Field;
1153  }
1154
1155  InitializedEntity MemberEntity =
1156    InitializedEntity::InitializeMember(*Field, &Entity);
1157
1158  if (isa<InitListExpr>(IList->getInit(Index)))
1159    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1160                        StructuredList, StructuredIndex);
1161  else
1162    CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1163                          StructuredList, StructuredIndex);
1164}
1165
1166/// \brief Expand a field designator that refers to a member of an
1167/// anonymous struct or union into a series of field designators that
1168/// refers to the field within the appropriate subobject.
1169///
1170/// Field/FieldIndex will be updated to point to the (new)
1171/// currently-designated field.
1172static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1173                                           DesignatedInitExpr *DIE,
1174                                           unsigned DesigIdx,
1175                                           FieldDecl *Field,
1176                                        RecordDecl::field_iterator &FieldIter,
1177                                           unsigned &FieldIndex) {
1178  typedef DesignatedInitExpr::Designator Designator;
1179
1180  // Build the path from the current object to the member of the
1181  // anonymous struct/union (backwards).
1182  llvm::SmallVector<FieldDecl *, 4> Path;
1183  SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
1184
1185  // Build the replacement designators.
1186  llvm::SmallVector<Designator, 4> Replacements;
1187  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1188         FI = Path.rbegin(), FIEnd = Path.rend();
1189       FI != FIEnd; ++FI) {
1190    if (FI + 1 == FIEnd)
1191      Replacements.push_back(Designator((IdentifierInfo *)0,
1192                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
1193                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
1194    else
1195      Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1196                                        SourceLocation()));
1197    Replacements.back().setField(*FI);
1198  }
1199
1200  // Expand the current designator into the set of replacement
1201  // designators, so we have a full subobject path down to where the
1202  // member of the anonymous struct/union is actually stored.
1203  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1204                        &Replacements[0] + Replacements.size());
1205
1206  // Update FieldIter/FieldIndex;
1207  RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
1208  FieldIter = Record->field_begin();
1209  FieldIndex = 0;
1210  for (RecordDecl::field_iterator FEnd = Record->field_end();
1211       FieldIter != FEnd; ++FieldIter) {
1212    if (FieldIter->isUnnamedBitfield())
1213        continue;
1214
1215    if (*FieldIter == Path.back())
1216      return;
1217
1218    ++FieldIndex;
1219  }
1220
1221  assert(false && "Unable to find anonymous struct/union field");
1222}
1223
1224/// @brief Check the well-formedness of a C99 designated initializer.
1225///
1226/// Determines whether the designated initializer @p DIE, which
1227/// resides at the given @p Index within the initializer list @p
1228/// IList, is well-formed for a current object of type @p DeclType
1229/// (C99 6.7.8). The actual subobject that this designator refers to
1230/// within the current subobject is returned in either
1231/// @p NextField or @p NextElementIndex (whichever is appropriate).
1232///
1233/// @param IList  The initializer list in which this designated
1234/// initializer occurs.
1235///
1236/// @param DIE The designated initializer expression.
1237///
1238/// @param DesigIdx  The index of the current designator.
1239///
1240/// @param DeclType  The type of the "current object" (C99 6.7.8p17),
1241/// into which the designation in @p DIE should refer.
1242///
1243/// @param NextField  If non-NULL and the first designator in @p DIE is
1244/// a field, this will be set to the field declaration corresponding
1245/// to the field named by the designator.
1246///
1247/// @param NextElementIndex  If non-NULL and the first designator in @p
1248/// DIE is an array designator or GNU array-range designator, this
1249/// will be set to the last index initialized by this designator.
1250///
1251/// @param Index  Index into @p IList where the designated initializer
1252/// @p DIE occurs.
1253///
1254/// @param StructuredList  The initializer list expression that
1255/// describes all of the subobject initializers in the order they'll
1256/// actually be initialized.
1257///
1258/// @returns true if there was an error, false otherwise.
1259bool
1260InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1261                                            InitListExpr *IList,
1262                                      DesignatedInitExpr *DIE,
1263                                      unsigned DesigIdx,
1264                                      QualType &CurrentObjectType,
1265                                      RecordDecl::field_iterator *NextField,
1266                                      llvm::APSInt *NextElementIndex,
1267                                      unsigned &Index,
1268                                      InitListExpr *StructuredList,
1269                                      unsigned &StructuredIndex,
1270                                            bool FinishSubobjectInit,
1271                                            bool TopLevelObject) {
1272  if (DesigIdx == DIE->size()) {
1273    // Check the actual initialization for the designated object type.
1274    bool prevHadError = hadError;
1275
1276    // Temporarily remove the designator expression from the
1277    // initializer list that the child calls see, so that we don't try
1278    // to re-process the designator.
1279    unsigned OldIndex = Index;
1280    IList->setInit(OldIndex, DIE->getInit());
1281
1282    CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1283                        StructuredList, StructuredIndex);
1284
1285    // Restore the designated initializer expression in the syntactic
1286    // form of the initializer list.
1287    if (IList->getInit(OldIndex) != DIE->getInit())
1288      DIE->setInit(IList->getInit(OldIndex));
1289    IList->setInit(OldIndex, DIE);
1290
1291    return hadError && !prevHadError;
1292  }
1293
1294  bool IsFirstDesignator = (DesigIdx == 0);
1295  assert((IsFirstDesignator || StructuredList) &&
1296         "Need a non-designated initializer list to start from");
1297
1298  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1299  // Determine the structural initializer list that corresponds to the
1300  // current subobject.
1301  StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1302    : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1303                                 StructuredList, StructuredIndex,
1304                                 SourceRange(D->getStartLocation(),
1305                                             DIE->getSourceRange().getEnd()));
1306  assert(StructuredList && "Expected a structured initializer list");
1307
1308  if (D->isFieldDesignator()) {
1309    // C99 6.7.8p7:
1310    //
1311    //   If a designator has the form
1312    //
1313    //      . identifier
1314    //
1315    //   then the current object (defined below) shall have
1316    //   structure or union type and the identifier shall be the
1317    //   name of a member of that type.
1318    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1319    if (!RT) {
1320      SourceLocation Loc = D->getDotLoc();
1321      if (Loc.isInvalid())
1322        Loc = D->getFieldLoc();
1323      SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1324        << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
1325      ++Index;
1326      return true;
1327    }
1328
1329    // Note: we perform a linear search of the fields here, despite
1330    // the fact that we have a faster lookup method, because we always
1331    // need to compute the field's index.
1332    FieldDecl *KnownField = D->getField();
1333    IdentifierInfo *FieldName = D->getFieldName();
1334    unsigned FieldIndex = 0;
1335    RecordDecl::field_iterator
1336      Field = RT->getDecl()->field_begin(),
1337      FieldEnd = RT->getDecl()->field_end();
1338    for (; Field != FieldEnd; ++Field) {
1339      if (Field->isUnnamedBitfield())
1340        continue;
1341
1342      if (KnownField == *Field || Field->getIdentifier() == FieldName)
1343        break;
1344
1345      ++FieldIndex;
1346    }
1347
1348    if (Field == FieldEnd) {
1349      // There was no normal field in the struct with the designated
1350      // name. Perform another lookup for this name, which may find
1351      // something that we can't designate (e.g., a member function),
1352      // may find nothing, or may find a member of an anonymous
1353      // struct/union.
1354      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1355      FieldDecl *ReplacementField = 0;
1356      if (Lookup.first == Lookup.second) {
1357        // Name lookup didn't find anything. Determine whether this
1358        // was a typo for another field name.
1359        LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1360                       Sema::LookupMemberName);
1361        if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl(), false,
1362                                Sema::CTC_NoKeywords) &&
1363            (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1364            ReplacementField->getDeclContext()->getLookupContext()
1365                                                      ->Equals(RT->getDecl())) {
1366          SemaRef.Diag(D->getFieldLoc(),
1367                       diag::err_field_designator_unknown_suggest)
1368            << FieldName << CurrentObjectType << R.getLookupName()
1369            << FixItHint::CreateReplacement(D->getFieldLoc(),
1370                                            R.getLookupName().getAsString());
1371          SemaRef.Diag(ReplacementField->getLocation(),
1372                       diag::note_previous_decl)
1373            << ReplacementField->getDeclName();
1374        } else {
1375          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1376            << FieldName << CurrentObjectType;
1377          ++Index;
1378          return true;
1379        }
1380      } else if (!KnownField) {
1381        // Determine whether we found a field at all.
1382        ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1383      }
1384
1385      if (!ReplacementField) {
1386        // Name lookup found something, but it wasn't a field.
1387        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1388          << FieldName;
1389        SemaRef.Diag((*Lookup.first)->getLocation(),
1390                      diag::note_field_designator_found);
1391        ++Index;
1392        return true;
1393      }
1394
1395      if (!KnownField &&
1396          cast<RecordDecl>((ReplacementField)->getDeclContext())
1397                                                 ->isAnonymousStructOrUnion()) {
1398        // Handle an field designator that refers to a member of an
1399        // anonymous struct or union.
1400        ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1401                                       ReplacementField,
1402                                       Field, FieldIndex);
1403        D = DIE->getDesignator(DesigIdx);
1404      } else if (!KnownField) {
1405        // The replacement field comes from typo correction; find it
1406        // in the list of fields.
1407        FieldIndex = 0;
1408        Field = RT->getDecl()->field_begin();
1409        for (; Field != FieldEnd; ++Field) {
1410          if (Field->isUnnamedBitfield())
1411            continue;
1412
1413          if (ReplacementField == *Field ||
1414              Field->getIdentifier() == ReplacementField->getIdentifier())
1415            break;
1416
1417          ++FieldIndex;
1418        }
1419      }
1420    } else if (!KnownField &&
1421               cast<RecordDecl>((*Field)->getDeclContext())
1422                 ->isAnonymousStructOrUnion()) {
1423      ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1424                                     Field, FieldIndex);
1425      D = DIE->getDesignator(DesigIdx);
1426    }
1427
1428    // All of the fields of a union are located at the same place in
1429    // the initializer list.
1430    if (RT->getDecl()->isUnion()) {
1431      FieldIndex = 0;
1432      StructuredList->setInitializedFieldInUnion(*Field);
1433    }
1434
1435    // Update the designator with the field declaration.
1436    D->setField(*Field);
1437
1438    // Make sure that our non-designated initializer list has space
1439    // for a subobject corresponding to this field.
1440    if (FieldIndex >= StructuredList->getNumInits())
1441      StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1442
1443    // This designator names a flexible array member.
1444    if (Field->getType()->isIncompleteArrayType()) {
1445      bool Invalid = false;
1446      if ((DesigIdx + 1) != DIE->size()) {
1447        // We can't designate an object within the flexible array
1448        // member (because GCC doesn't allow it).
1449        DesignatedInitExpr::Designator *NextD
1450          = DIE->getDesignator(DesigIdx + 1);
1451        SemaRef.Diag(NextD->getStartLocation(),
1452                      diag::err_designator_into_flexible_array_member)
1453          << SourceRange(NextD->getStartLocation(),
1454                         DIE->getSourceRange().getEnd());
1455        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1456          << *Field;
1457        Invalid = true;
1458      }
1459
1460      if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1461        // The initializer is not an initializer list.
1462        SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1463                      diag::err_flexible_array_init_needs_braces)
1464          << DIE->getInit()->getSourceRange();
1465        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1466          << *Field;
1467        Invalid = true;
1468      }
1469
1470      // Handle GNU flexible array initializers.
1471      if (!Invalid && !TopLevelObject &&
1472          cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
1473        SemaRef.Diag(DIE->getSourceRange().getBegin(),
1474                      diag::err_flexible_array_init_nonempty)
1475          << DIE->getSourceRange().getBegin();
1476        SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1477          << *Field;
1478        Invalid = true;
1479      }
1480
1481      if (Invalid) {
1482        ++Index;
1483        return true;
1484      }
1485
1486      // Initialize the array.
1487      bool prevHadError = hadError;
1488      unsigned newStructuredIndex = FieldIndex;
1489      unsigned OldIndex = Index;
1490      IList->setInit(Index, DIE->getInit());
1491
1492      InitializedEntity MemberEntity =
1493        InitializedEntity::InitializeMember(*Field, &Entity);
1494      CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1495                          StructuredList, newStructuredIndex);
1496
1497      IList->setInit(OldIndex, DIE);
1498      if (hadError && !prevHadError) {
1499        ++Field;
1500        ++FieldIndex;
1501        if (NextField)
1502          *NextField = Field;
1503        StructuredIndex = FieldIndex;
1504        return true;
1505      }
1506    } else {
1507      // Recurse to check later designated subobjects.
1508      QualType FieldType = (*Field)->getType();
1509      unsigned newStructuredIndex = FieldIndex;
1510
1511      InitializedEntity MemberEntity =
1512        InitializedEntity::InitializeMember(*Field, &Entity);
1513      if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1514                                     FieldType, 0, 0, Index,
1515                                     StructuredList, newStructuredIndex,
1516                                     true, false))
1517        return true;
1518    }
1519
1520    // Find the position of the next field to be initialized in this
1521    // subobject.
1522    ++Field;
1523    ++FieldIndex;
1524
1525    // If this the first designator, our caller will continue checking
1526    // the rest of this struct/class/union subobject.
1527    if (IsFirstDesignator) {
1528      if (NextField)
1529        *NextField = Field;
1530      StructuredIndex = FieldIndex;
1531      return false;
1532    }
1533
1534    if (!FinishSubobjectInit)
1535      return false;
1536
1537    // We've already initialized something in the union; we're done.
1538    if (RT->getDecl()->isUnion())
1539      return hadError;
1540
1541    // Check the remaining fields within this class/struct/union subobject.
1542    bool prevHadError = hadError;
1543
1544    CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1545                          StructuredList, FieldIndex);
1546    return hadError && !prevHadError;
1547  }
1548
1549  // C99 6.7.8p6:
1550  //
1551  //   If a designator has the form
1552  //
1553  //      [ constant-expression ]
1554  //
1555  //   then the current object (defined below) shall have array
1556  //   type and the expression shall be an integer constant
1557  //   expression. If the array is of unknown size, any
1558  //   nonnegative value is valid.
1559  //
1560  // Additionally, cope with the GNU extension that permits
1561  // designators of the form
1562  //
1563  //      [ constant-expression ... constant-expression ]
1564  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
1565  if (!AT) {
1566    SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1567      << CurrentObjectType;
1568    ++Index;
1569    return true;
1570  }
1571
1572  Expr *IndexExpr = 0;
1573  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1574  if (D->isArrayDesignator()) {
1575    IndexExpr = DIE->getArrayIndex(*D);
1576    DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
1577    DesignatedEndIndex = DesignatedStartIndex;
1578  } else {
1579    assert(D->isArrayRangeDesignator() && "Need array-range designator");
1580
1581
1582    DesignatedStartIndex =
1583      DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
1584    DesignatedEndIndex =
1585      DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
1586    IndexExpr = DIE->getArrayRangeEnd(*D);
1587
1588    if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
1589      FullyStructuredList->sawArrayRangeDesignator();
1590  }
1591
1592  if (isa<ConstantArrayType>(AT)) {
1593    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
1594    DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1595    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1596    DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1597    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1598    if (DesignatedEndIndex >= MaxElements) {
1599      SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1600                    diag::err_array_designator_too_large)
1601        << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1602        << IndexExpr->getSourceRange();
1603      ++Index;
1604      return true;
1605    }
1606  } else {
1607    // Make sure the bit-widths and signedness match.
1608    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1609      DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
1610    else if (DesignatedStartIndex.getBitWidth() <
1611             DesignatedEndIndex.getBitWidth())
1612      DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1613    DesignatedStartIndex.setIsUnsigned(true);
1614    DesignatedEndIndex.setIsUnsigned(true);
1615  }
1616
1617  // Make sure that our non-designated initializer list has space
1618  // for a subobject corresponding to this array element.
1619  if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
1620    StructuredList->resizeInits(SemaRef.Context,
1621                                DesignatedEndIndex.getZExtValue() + 1);
1622
1623  // Repeatedly perform subobject initializations in the range
1624  // [DesignatedStartIndex, DesignatedEndIndex].
1625
1626  // Move to the next designator
1627  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1628  unsigned OldIndex = Index;
1629
1630  InitializedEntity ElementEntity =
1631    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1632
1633  while (DesignatedStartIndex <= DesignatedEndIndex) {
1634    // Recurse to check later designated subobjects.
1635    QualType ElementType = AT->getElementType();
1636    Index = OldIndex;
1637
1638    ElementEntity.setElementIndex(ElementIndex);
1639    if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1640                                   ElementType, 0, 0, Index,
1641                                   StructuredList, ElementIndex,
1642                                   (DesignatedStartIndex == DesignatedEndIndex),
1643                                   false))
1644      return true;
1645
1646    // Move to the next index in the array that we'll be initializing.
1647    ++DesignatedStartIndex;
1648    ElementIndex = DesignatedStartIndex.getZExtValue();
1649  }
1650
1651  // If this the first designator, our caller will continue checking
1652  // the rest of this array subobject.
1653  if (IsFirstDesignator) {
1654    if (NextElementIndex)
1655      *NextElementIndex = DesignatedStartIndex;
1656    StructuredIndex = ElementIndex;
1657    return false;
1658  }
1659
1660  if (!FinishSubobjectInit)
1661    return false;
1662
1663  // Check the remaining elements within this array subobject.
1664  bool prevHadError = hadError;
1665  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
1666                 /*SubobjectIsDesignatorContext=*/false, Index,
1667                 StructuredList, ElementIndex);
1668  return hadError && !prevHadError;
1669}
1670
1671// Get the structured initializer list for a subobject of type
1672// @p CurrentObjectType.
1673InitListExpr *
1674InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1675                                            QualType CurrentObjectType,
1676                                            InitListExpr *StructuredList,
1677                                            unsigned StructuredIndex,
1678                                            SourceRange InitRange) {
1679  Expr *ExistingInit = 0;
1680  if (!StructuredList)
1681    ExistingInit = SyntacticToSemantic[IList];
1682  else if (StructuredIndex < StructuredList->getNumInits())
1683    ExistingInit = StructuredList->getInit(StructuredIndex);
1684
1685  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1686    return Result;
1687
1688  if (ExistingInit) {
1689    // We are creating an initializer list that initializes the
1690    // subobjects of the current object, but there was already an
1691    // initialization that completely initialized the current
1692    // subobject, e.g., by a compound literal:
1693    //
1694    // struct X { int a, b; };
1695    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
1696    //
1697    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1698    // designated initializer re-initializes the whole
1699    // subobject [0], overwriting previous initializers.
1700    SemaRef.Diag(InitRange.getBegin(),
1701                 diag::warn_subobject_initializer_overrides)
1702      << InitRange;
1703    SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
1704                  diag::note_previous_initializer)
1705      << /*FIXME:has side effects=*/0
1706      << ExistingInit->getSourceRange();
1707  }
1708
1709  InitListExpr *Result
1710    = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1711                                         InitRange.getBegin(), 0, 0,
1712                                         InitRange.getEnd());
1713
1714  Result->setType(CurrentObjectType.getNonReferenceType());
1715
1716  // Pre-allocate storage for the structured initializer list.
1717  unsigned NumElements = 0;
1718  unsigned NumInits = 0;
1719  if (!StructuredList)
1720    NumInits = IList->getNumInits();
1721  else if (Index < IList->getNumInits()) {
1722    if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1723      NumInits = SubList->getNumInits();
1724  }
1725
1726  if (const ArrayType *AType
1727      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1728    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1729      NumElements = CAType->getSize().getZExtValue();
1730      // Simple heuristic so that we don't allocate a very large
1731      // initializer with many empty entries at the end.
1732      if (NumInits && NumElements > NumInits)
1733        NumElements = 0;
1734    }
1735  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
1736    NumElements = VType->getNumElements();
1737  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
1738    RecordDecl *RDecl = RType->getDecl();
1739    if (RDecl->isUnion())
1740      NumElements = 1;
1741    else
1742      NumElements = std::distance(RDecl->field_begin(),
1743                                  RDecl->field_end());
1744  }
1745
1746  if (NumElements < NumInits)
1747    NumElements = IList->getNumInits();
1748
1749  Result->reserveInits(SemaRef.Context, NumElements);
1750
1751  // Link this new initializer list into the structured initializer
1752  // lists.
1753  if (StructuredList)
1754    StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
1755  else {
1756    Result->setSyntacticForm(IList);
1757    SyntacticToSemantic[IList] = Result;
1758  }
1759
1760  return Result;
1761}
1762
1763/// Update the initializer at index @p StructuredIndex within the
1764/// structured initializer list to the value @p expr.
1765void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1766                                                  unsigned &StructuredIndex,
1767                                                  Expr *expr) {
1768  // No structured initializer list to update
1769  if (!StructuredList)
1770    return;
1771
1772  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1773                                                  StructuredIndex, expr)) {
1774    // This initializer overwrites a previous initializer. Warn.
1775    SemaRef.Diag(expr->getSourceRange().getBegin(),
1776                  diag::warn_initializer_overrides)
1777      << expr->getSourceRange();
1778    SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
1779                  diag::note_previous_initializer)
1780      << /*FIXME:has side effects=*/0
1781      << PrevInit->getSourceRange();
1782  }
1783
1784  ++StructuredIndex;
1785}
1786
1787/// Check that the given Index expression is a valid array designator
1788/// value. This is essentailly just a wrapper around
1789/// VerifyIntegerConstantExpression that also checks for negative values
1790/// and produces a reasonable diagnostic if there is a
1791/// failure. Returns true if there was an error, false otherwise.  If
1792/// everything went okay, Value will receive the value of the constant
1793/// expression.
1794static bool
1795CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
1796  SourceLocation Loc = Index->getSourceRange().getBegin();
1797
1798  // Make sure this is an integer constant expression.
1799  if (S.VerifyIntegerConstantExpression(Index, &Value))
1800    return true;
1801
1802  if (Value.isSigned() && Value.isNegative())
1803    return S.Diag(Loc, diag::err_array_designator_negative)
1804      << Value.toString(10) << Index->getSourceRange();
1805
1806  Value.setIsUnsigned(true);
1807  return false;
1808}
1809
1810Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1811                                                        SourceLocation Loc,
1812                                                        bool GNUSyntax,
1813                                                        OwningExprResult Init) {
1814  typedef DesignatedInitExpr::Designator ASTDesignator;
1815
1816  bool Invalid = false;
1817  llvm::SmallVector<ASTDesignator, 32> Designators;
1818  llvm::SmallVector<Expr *, 32> InitExpressions;
1819
1820  // Build designators and check array designator expressions.
1821  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1822    const Designator &D = Desig.getDesignator(Idx);
1823    switch (D.getKind()) {
1824    case Designator::FieldDesignator:
1825      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
1826                                          D.getFieldLoc()));
1827      break;
1828
1829    case Designator::ArrayDesignator: {
1830      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1831      llvm::APSInt IndexValue;
1832      if (!Index->isTypeDependent() &&
1833          !Index->isValueDependent() &&
1834          CheckArrayDesignatorExpr(*this, Index, IndexValue))
1835        Invalid = true;
1836      else {
1837        Designators.push_back(ASTDesignator(InitExpressions.size(),
1838                                            D.getLBracketLoc(),
1839                                            D.getRBracketLoc()));
1840        InitExpressions.push_back(Index);
1841      }
1842      break;
1843    }
1844
1845    case Designator::ArrayRangeDesignator: {
1846      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1847      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1848      llvm::APSInt StartValue;
1849      llvm::APSInt EndValue;
1850      bool StartDependent = StartIndex->isTypeDependent() ||
1851                            StartIndex->isValueDependent();
1852      bool EndDependent = EndIndex->isTypeDependent() ||
1853                          EndIndex->isValueDependent();
1854      if ((!StartDependent &&
1855           CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1856          (!EndDependent &&
1857           CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
1858        Invalid = true;
1859      else {
1860        // Make sure we're comparing values with the same bit width.
1861        if (StartDependent || EndDependent) {
1862          // Nothing to compute.
1863        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
1864          EndValue.extend(StartValue.getBitWidth());
1865        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1866          StartValue.extend(EndValue.getBitWidth());
1867
1868        if (!StartDependent && !EndDependent && EndValue < StartValue) {
1869          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
1870            << StartValue.toString(10) << EndValue.toString(10)
1871            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1872          Invalid = true;
1873        } else {
1874          Designators.push_back(ASTDesignator(InitExpressions.size(),
1875                                              D.getLBracketLoc(),
1876                                              D.getEllipsisLoc(),
1877                                              D.getRBracketLoc()));
1878          InitExpressions.push_back(StartIndex);
1879          InitExpressions.push_back(EndIndex);
1880        }
1881      }
1882      break;
1883    }
1884    }
1885  }
1886
1887  if (Invalid || Init.isInvalid())
1888    return ExprError();
1889
1890  // Clear out the expressions within the designation.
1891  Desig.ClearExprs(*this);
1892
1893  DesignatedInitExpr *DIE
1894    = DesignatedInitExpr::Create(Context,
1895                                 Designators.data(), Designators.size(),
1896                                 InitExpressions.data(), InitExpressions.size(),
1897                                 Loc, GNUSyntax, Init.takeAs<Expr>());
1898  return Owned(DIE);
1899}
1900
1901bool Sema::CheckInitList(const InitializedEntity &Entity,
1902                         InitListExpr *&InitList, QualType &DeclType) {
1903  InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
1904  if (!CheckInitList.HadError())
1905    InitList = CheckInitList.getFullyStructuredList();
1906
1907  return CheckInitList.HadError();
1908}
1909
1910//===----------------------------------------------------------------------===//
1911// Initialization entity
1912//===----------------------------------------------------------------------===//
1913
1914InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1915                                     const InitializedEntity &Parent)
1916  : Parent(&Parent), Index(Index)
1917{
1918  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1919    Kind = EK_ArrayElement;
1920    Type = AT->getElementType();
1921  } else {
1922    Kind = EK_VectorElement;
1923    Type = Parent.getType()->getAs<VectorType>()->getElementType();
1924  }
1925}
1926
1927InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1928                                                    CXXBaseSpecifier *Base,
1929                                                    bool IsInheritedVirtualBase)
1930{
1931  InitializedEntity Result;
1932  Result.Kind = EK_Base;
1933  Result.Base = reinterpret_cast<uintptr_t>(Base);
1934  if (IsInheritedVirtualBase)
1935    Result.Base |= 0x01;
1936
1937  Result.Type = Base->getType();
1938  return Result;
1939}
1940
1941DeclarationName InitializedEntity::getName() const {
1942  switch (getKind()) {
1943  case EK_Parameter:
1944    if (!VariableOrMember)
1945      return DeclarationName();
1946    // Fall through
1947
1948  case EK_Variable:
1949  case EK_Member:
1950    return VariableOrMember->getDeclName();
1951
1952  case EK_Result:
1953  case EK_Exception:
1954  case EK_New:
1955  case EK_Temporary:
1956  case EK_Base:
1957  case EK_ArrayElement:
1958  case EK_VectorElement:
1959  case EK_BlockElement:
1960    return DeclarationName();
1961  }
1962
1963  // Silence GCC warning
1964  return DeclarationName();
1965}
1966
1967DeclaratorDecl *InitializedEntity::getDecl() const {
1968  switch (getKind()) {
1969  case EK_Variable:
1970  case EK_Parameter:
1971  case EK_Member:
1972    return VariableOrMember;
1973
1974  case EK_Result:
1975  case EK_Exception:
1976  case EK_New:
1977  case EK_Temporary:
1978  case EK_Base:
1979  case EK_ArrayElement:
1980  case EK_VectorElement:
1981  case EK_BlockElement:
1982    return 0;
1983  }
1984
1985  // Silence GCC warning
1986  return 0;
1987}
1988
1989bool InitializedEntity::allowsNRVO() const {
1990  switch (getKind()) {
1991  case EK_Result:
1992  case EK_Exception:
1993    return LocAndNRVO.NRVO;
1994
1995  case EK_Variable:
1996  case EK_Parameter:
1997  case EK_Member:
1998  case EK_New:
1999  case EK_Temporary:
2000  case EK_Base:
2001  case EK_ArrayElement:
2002  case EK_VectorElement:
2003  case EK_BlockElement:
2004    break;
2005  }
2006
2007  return false;
2008}
2009
2010//===----------------------------------------------------------------------===//
2011// Initialization sequence
2012//===----------------------------------------------------------------------===//
2013
2014void InitializationSequence::Step::Destroy() {
2015  switch (Kind) {
2016  case SK_ResolveAddressOfOverloadedFunction:
2017  case SK_CastDerivedToBaseRValue:
2018  case SK_CastDerivedToBaseLValue:
2019  case SK_BindReference:
2020  case SK_BindReferenceToTemporary:
2021  case SK_ExtraneousCopyToTemporary:
2022  case SK_UserConversion:
2023  case SK_QualificationConversionRValue:
2024  case SK_QualificationConversionLValue:
2025  case SK_ListInitialization:
2026  case SK_ConstructorInitialization:
2027  case SK_ZeroInitialization:
2028  case SK_CAssignment:
2029  case SK_StringInit:
2030    break;
2031
2032  case SK_ConversionSequence:
2033    delete ICS;
2034  }
2035}
2036
2037bool InitializationSequence::isDirectReferenceBinding() const {
2038  return getKind() == ReferenceBinding && Steps.back().Kind == SK_BindReference;
2039}
2040
2041bool InitializationSequence::isAmbiguous() const {
2042  if (getKind() != FailedSequence)
2043    return false;
2044
2045  switch (getFailureKind()) {
2046  case FK_TooManyInitsForReference:
2047  case FK_ArrayNeedsInitList:
2048  case FK_ArrayNeedsInitListOrStringLiteral:
2049  case FK_AddressOfOverloadFailed: // FIXME: Could do better
2050  case FK_NonConstLValueReferenceBindingToTemporary:
2051  case FK_NonConstLValueReferenceBindingToUnrelated:
2052  case FK_RValueReferenceBindingToLValue:
2053  case FK_ReferenceInitDropsQualifiers:
2054  case FK_ReferenceInitFailed:
2055  case FK_ConversionFailed:
2056  case FK_TooManyInitsForScalar:
2057  case FK_ReferenceBindingToInitList:
2058  case FK_InitListBadDestinationType:
2059  case FK_DefaultInitOfConst:
2060  case FK_Incomplete:
2061    return false;
2062
2063  case FK_ReferenceInitOverloadFailed:
2064  case FK_UserConversionOverloadFailed:
2065  case FK_ConstructorOverloadFailed:
2066    return FailedOverloadResult == OR_Ambiguous;
2067  }
2068
2069  return false;
2070}
2071
2072bool InitializationSequence::isConstructorInitialization() const {
2073  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2074}
2075
2076void InitializationSequence::AddAddressOverloadResolutionStep(
2077                                                      FunctionDecl *Function,
2078                                                      DeclAccessPair Found) {
2079  Step S;
2080  S.Kind = SK_ResolveAddressOfOverloadedFunction;
2081  S.Type = Function->getType();
2082  S.Function.Function = Function;
2083  S.Function.FoundDecl = Found;
2084  Steps.push_back(S);
2085}
2086
2087void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2088                                                      bool IsLValue) {
2089  Step S;
2090  S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2091  S.Type = BaseType;
2092  Steps.push_back(S);
2093}
2094
2095void InitializationSequence::AddReferenceBindingStep(QualType T,
2096                                                     bool BindingTemporary) {
2097  Step S;
2098  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2099  S.Type = T;
2100  Steps.push_back(S);
2101}
2102
2103void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2104  Step S;
2105  S.Kind = SK_ExtraneousCopyToTemporary;
2106  S.Type = T;
2107  Steps.push_back(S);
2108}
2109
2110void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2111                                                   DeclAccessPair FoundDecl,
2112                                                   QualType T) {
2113  Step S;
2114  S.Kind = SK_UserConversion;
2115  S.Type = T;
2116  S.Function.Function = Function;
2117  S.Function.FoundDecl = FoundDecl;
2118  Steps.push_back(S);
2119}
2120
2121void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2122                                                            bool IsLValue) {
2123  Step S;
2124  S.Kind = IsLValue? SK_QualificationConversionLValue
2125                   : SK_QualificationConversionRValue;
2126  S.Type = Ty;
2127  Steps.push_back(S);
2128}
2129
2130void InitializationSequence::AddConversionSequenceStep(
2131                                       const ImplicitConversionSequence &ICS,
2132                                                       QualType T) {
2133  Step S;
2134  S.Kind = SK_ConversionSequence;
2135  S.Type = T;
2136  S.ICS = new ImplicitConversionSequence(ICS);
2137  Steps.push_back(S);
2138}
2139
2140void InitializationSequence::AddListInitializationStep(QualType T) {
2141  Step S;
2142  S.Kind = SK_ListInitialization;
2143  S.Type = T;
2144  Steps.push_back(S);
2145}
2146
2147void
2148InitializationSequence::AddConstructorInitializationStep(
2149                                              CXXConstructorDecl *Constructor,
2150                                                       AccessSpecifier Access,
2151                                                         QualType T) {
2152  Step S;
2153  S.Kind = SK_ConstructorInitialization;
2154  S.Type = T;
2155  S.Function.Function = Constructor;
2156  S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2157  Steps.push_back(S);
2158}
2159
2160void InitializationSequence::AddZeroInitializationStep(QualType T) {
2161  Step S;
2162  S.Kind = SK_ZeroInitialization;
2163  S.Type = T;
2164  Steps.push_back(S);
2165}
2166
2167void InitializationSequence::AddCAssignmentStep(QualType T) {
2168  Step S;
2169  S.Kind = SK_CAssignment;
2170  S.Type = T;
2171  Steps.push_back(S);
2172}
2173
2174void InitializationSequence::AddStringInitStep(QualType T) {
2175  Step S;
2176  S.Kind = SK_StringInit;
2177  S.Type = T;
2178  Steps.push_back(S);
2179}
2180
2181void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2182                                                OverloadingResult Result) {
2183  SequenceKind = FailedSequence;
2184  this->Failure = Failure;
2185  this->FailedOverloadResult = Result;
2186}
2187
2188//===----------------------------------------------------------------------===//
2189// Attempt initialization
2190//===----------------------------------------------------------------------===//
2191
2192/// \brief Attempt list initialization (C++0x [dcl.init.list])
2193static void TryListInitialization(Sema &S,
2194                                  const InitializedEntity &Entity,
2195                                  const InitializationKind &Kind,
2196                                  InitListExpr *InitList,
2197                                  InitializationSequence &Sequence) {
2198  // FIXME: We only perform rudimentary checking of list
2199  // initializations at this point, then assume that any list
2200  // initialization of an array, aggregate, or scalar will be
2201  // well-formed. When we actually "perform" list initialization, we'll
2202  // do all of the necessary checking.  C++0x initializer lists will
2203  // force us to perform more checking here.
2204  Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2205
2206  QualType DestType = Entity.getType();
2207
2208  // C++ [dcl.init]p13:
2209  //   If T is a scalar type, then a declaration of the form
2210  //
2211  //     T x = { a };
2212  //
2213  //   is equivalent to
2214  //
2215  //     T x = a;
2216  if (DestType->isScalarType()) {
2217    if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2218      Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2219      return;
2220    }
2221
2222    // Assume scalar initialization from a single value works.
2223  } else if (DestType->isAggregateType()) {
2224    // Assume aggregate initialization works.
2225  } else if (DestType->isVectorType()) {
2226    // Assume vector initialization works.
2227  } else if (DestType->isReferenceType()) {
2228    // FIXME: C++0x defines behavior for this.
2229    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2230    return;
2231  } else if (DestType->isRecordType()) {
2232    // FIXME: C++0x defines behavior for this
2233    Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2234  }
2235
2236  // Add a general "list initialization" step.
2237  Sequence.AddListInitializationStep(DestType);
2238}
2239
2240/// \brief Try a reference initialization that involves calling a conversion
2241/// function.
2242static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2243                                             const InitializedEntity &Entity,
2244                                             const InitializationKind &Kind,
2245                                                          Expr *Initializer,
2246                                                          bool AllowRValues,
2247                                             InitializationSequence &Sequence) {
2248  QualType DestType = Entity.getType();
2249  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2250  QualType T1 = cv1T1.getUnqualifiedType();
2251  QualType cv2T2 = Initializer->getType();
2252  QualType T2 = cv2T2.getUnqualifiedType();
2253
2254  bool DerivedToBase;
2255  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2256                                         T1, T2, DerivedToBase) &&
2257         "Must have incompatible references when binding via conversion");
2258  (void)DerivedToBase;
2259
2260  // Build the candidate set directly in the initialization sequence
2261  // structure, so that it will persist if we fail.
2262  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2263  CandidateSet.clear();
2264
2265  // Determine whether we are allowed to call explicit constructors or
2266  // explicit conversion operators.
2267  bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2268
2269  const RecordType *T1RecordType = 0;
2270  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2271      !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
2272    // The type we're converting to is a class type. Enumerate its constructors
2273    // to see if there is a suitable conversion.
2274    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2275    DeclContext::lookup_iterator Con, ConEnd;
2276    for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
2277         Con != ConEnd; ++Con) {
2278      NamedDecl *D = *Con;
2279      DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2280
2281      // Find the constructor (which may be a template).
2282      CXXConstructorDecl *Constructor = 0;
2283      FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2284      if (ConstructorTmpl)
2285        Constructor = cast<CXXConstructorDecl>(
2286                                         ConstructorTmpl->getTemplatedDecl());
2287      else
2288        Constructor = cast<CXXConstructorDecl>(D);
2289
2290      if (!Constructor->isInvalidDecl() &&
2291          Constructor->isConvertingConstructor(AllowExplicit)) {
2292        if (ConstructorTmpl)
2293          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2294                                         /*ExplicitArgs*/ 0,
2295                                         &Initializer, 1, CandidateSet);
2296        else
2297          S.AddOverloadCandidate(Constructor, FoundDecl,
2298                                 &Initializer, 1, CandidateSet);
2299      }
2300    }
2301  }
2302
2303  const RecordType *T2RecordType = 0;
2304  if ((T2RecordType = T2->getAs<RecordType>()) &&
2305      !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
2306    // The type we're converting from is a class type, enumerate its conversion
2307    // functions.
2308    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2309
2310    // Determine the type we are converting to. If we are allowed to
2311    // convert to an rvalue, take the type that the destination type
2312    // refers to.
2313    QualType ToType = AllowRValues? cv1T1 : DestType;
2314
2315    const UnresolvedSetImpl *Conversions
2316      = T2RecordDecl->getVisibleConversionFunctions();
2317    for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2318           E = Conversions->end(); I != E; ++I) {
2319      NamedDecl *D = *I;
2320      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2321      if (isa<UsingShadowDecl>(D))
2322        D = cast<UsingShadowDecl>(D)->getTargetDecl();
2323
2324      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2325      CXXConversionDecl *Conv;
2326      if (ConvTemplate)
2327        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2328      else
2329        Conv = cast<CXXConversionDecl>(D);
2330
2331      // If the conversion function doesn't return a reference type,
2332      // it can't be considered for this conversion unless we're allowed to
2333      // consider rvalues.
2334      // FIXME: Do we need to make sure that we only consider conversion
2335      // candidates with reference-compatible results? That might be needed to
2336      // break recursion.
2337      if ((AllowExplicit || !Conv->isExplicit()) &&
2338          (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2339        if (ConvTemplate)
2340          S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
2341                                           ActingDC, Initializer,
2342                                           ToType, CandidateSet);
2343        else
2344          S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
2345                                   Initializer, ToType, CandidateSet);
2346      }
2347    }
2348  }
2349
2350  SourceLocation DeclLoc = Initializer->getLocStart();
2351
2352  // Perform overload resolution. If it fails, return the failed result.
2353  OverloadCandidateSet::iterator Best;
2354  if (OverloadingResult Result
2355        = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2356    return Result;
2357
2358  FunctionDecl *Function = Best->Function;
2359
2360  // Compute the returned type of the conversion.
2361  if (isa<CXXConversionDecl>(Function))
2362    T2 = Function->getResultType();
2363  else
2364    T2 = cv1T1;
2365
2366  // Add the user-defined conversion step.
2367  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
2368                                 T2.getNonReferenceType());
2369
2370  // Determine whether we need to perform derived-to-base or
2371  // cv-qualification adjustments.
2372  bool NewDerivedToBase = false;
2373  Sema::ReferenceCompareResult NewRefRelationship
2374    = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2375                                     NewDerivedToBase);
2376  if (NewRefRelationship == Sema::Ref_Incompatible) {
2377    // If the type we've converted to is not reference-related to the
2378    // type we're looking for, then there is another conversion step
2379    // we need to perform to produce a temporary of the right type
2380    // that we'll be binding to.
2381    ImplicitConversionSequence ICS;
2382    ICS.setStandard();
2383    ICS.Standard = Best->FinalConversion;
2384    T2 = ICS.Standard.getToType(2);
2385    Sequence.AddConversionSequenceStep(ICS, T2);
2386  } else if (NewDerivedToBase)
2387    Sequence.AddDerivedToBaseCastStep(
2388                                S.Context.getQualifiedType(T1,
2389                                  T2.getNonReferenceType().getQualifiers()),
2390                                  /*isLValue=*/true);
2391
2392  if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2393    Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2394
2395  Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2396  return OR_Success;
2397}
2398
2399/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2400static void TryReferenceInitialization(Sema &S,
2401                                       const InitializedEntity &Entity,
2402                                       const InitializationKind &Kind,
2403                                       Expr *Initializer,
2404                                       InitializationSequence &Sequence) {
2405  Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2406
2407  QualType DestType = Entity.getType();
2408  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2409  Qualifiers T1Quals;
2410  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
2411  QualType cv2T2 = Initializer->getType();
2412  Qualifiers T2Quals;
2413  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
2414  SourceLocation DeclLoc = Initializer->getLocStart();
2415
2416  // If the initializer is the address of an overloaded function, try
2417  // to resolve the overloaded function. If all goes well, T2 is the
2418  // type of the resulting function.
2419  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2420    DeclAccessPair Found;
2421    FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2422                                                            T1,
2423                                                            false,
2424                                                            Found);
2425    if (!Fn) {
2426      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2427      return;
2428    }
2429
2430    Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2431    cv2T2 = Fn->getType();
2432    T2 = cv2T2.getUnqualifiedType();
2433  }
2434
2435  // Compute some basic properties of the types and the initializer.
2436  bool isLValueRef = DestType->isLValueReferenceType();
2437  bool isRValueRef = !isLValueRef;
2438  bool DerivedToBase = false;
2439  Expr::Classification InitCategory = Initializer->Classify(S.Context);
2440  Sema::ReferenceCompareResult RefRelationship
2441    = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2442
2443  // C++0x [dcl.init.ref]p5:
2444  //   A reference to type "cv1 T1" is initialized by an expression of type
2445  //   "cv2 T2" as follows:
2446  //
2447  //     - If the reference is an lvalue reference and the initializer
2448  //       expression
2449  // Note the analogous bullet points for rvlaue refs to functions. Because
2450  // there are no function rvalues in C++, rvalue refs to functions are treated
2451  // like lvalue refs.
2452  OverloadingResult ConvOvlResult = OR_Success;
2453  bool T1Function = T1->isFunctionType();
2454  if (isLValueRef || T1Function) {
2455    if (InitCategory.isLValue() &&
2456        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2457      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
2458      //     reference-compatible with "cv2 T2," or
2459      //
2460      // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
2461      // bit-field when we're determining whether the reference initialization
2462      // can occur. However, we do pay attention to whether it is a bit-field
2463      // to decide whether we're actually binding to a temporary created from
2464      // the bit-field.
2465      if (DerivedToBase)
2466        Sequence.AddDerivedToBaseCastStep(
2467                         S.Context.getQualifiedType(T1, T2Quals),
2468                         /*isLValue=*/true);
2469      if (T1Quals != T2Quals)
2470        Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2471      bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
2472        (Initializer->getBitField() || Initializer->refersToVectorElement());
2473      Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
2474      return;
2475    }
2476
2477    //     - has a class type (i.e., T2 is a class type), where T1 is not
2478    //       reference-related to T2, and can be implicitly converted to an
2479    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2480    //       with "cv3 T3" (this conversion is selected by enumerating the
2481    //       applicable conversion functions (13.3.1.6) and choosing the best
2482    //       one through overload resolution (13.3)),
2483    // If we have an rvalue ref to function type here, the rhs must be
2484    // an rvalue.
2485    if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2486        (isLValueRef || InitCategory.isRValue())) {
2487      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2488                                                       Initializer,
2489                                                   /*AllowRValues=*/isRValueRef,
2490                                                       Sequence);
2491      if (ConvOvlResult == OR_Success)
2492        return;
2493      if (ConvOvlResult != OR_No_Viable_Function) {
2494        Sequence.SetOverloadFailure(
2495                      InitializationSequence::FK_ReferenceInitOverloadFailed,
2496                                    ConvOvlResult);
2497      }
2498    }
2499  }
2500
2501  //     - Otherwise, the reference shall be an lvalue reference to a
2502  //       non-volatile const type (i.e., cv1 shall be const), or the reference
2503  //       shall be an rvalue reference and the initializer expression shall
2504  //       be an rvalue or have a function type.
2505  // We handled the function type stuff above.
2506  if (!((isLValueRef && T1Quals.hasConst() && !T1Quals.hasVolatile()) ||
2507        (isRValueRef && InitCategory.isRValue()))) {
2508    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2509      Sequence.SetOverloadFailure(
2510                        InitializationSequence::FK_ReferenceInitOverloadFailed,
2511                                  ConvOvlResult);
2512    else if (isLValueRef)
2513      Sequence.SetFailed(InitCategory.isLValue()
2514        ? (RefRelationship == Sema::Ref_Related
2515             ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2516             : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2517        : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2518    else
2519      Sequence.SetFailed(
2520                    InitializationSequence::FK_RValueReferenceBindingToLValue);
2521
2522    return;
2523  }
2524
2525  //       - [If T1 is not a function type], if T2 is a class type and
2526  if (!T1Function && T2->isRecordType()) {
2527    //       - the initializer expression is an rvalue and "cv1 T1" is
2528    //         reference-compatible with "cv2 T2", or
2529    if (InitCategory.isRValue() &&
2530        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2531      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2532      // compiler the freedom to perform a copy here or bind to the
2533      // object, while C++0x requires that we bind directly to the
2534      // object. Hence, we always bind to the object without making an
2535      // extra copy. However, in C++03 requires that we check for the
2536      // presence of a suitable copy constructor:
2537      //
2538      //   The constructor that would be used to make the copy shall
2539      //   be callable whether or not the copy is actually done.
2540      if (!S.getLangOptions().CPlusPlus0x)
2541        Sequence.AddExtraneousCopyToTemporary(cv2T2);
2542
2543      if (DerivedToBase)
2544        Sequence.AddDerivedToBaseCastStep(
2545                         S.Context.getQualifiedType(T1, T2Quals),
2546                         /*isLValue=*/false);
2547      if (T1Quals != T2Quals)
2548        Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2549      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2550      return;
2551    }
2552
2553    //       - T1 is not reference-related to T2 and the initializer expression
2554    //         can be implicitly converted to an rvalue of type "cv3 T3" (this
2555    //         conversion is selected by enumerating the applicable conversion
2556    //         functions (13.3.1.6) and choosing the best one through overload
2557    //         resolution (13.3)),
2558    if (RefRelationship == Sema::Ref_Incompatible) {
2559      ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2560                                                       Kind, Initializer,
2561                                                       /*AllowRValues=*/true,
2562                                                       Sequence);
2563      if (ConvOvlResult)
2564        Sequence.SetOverloadFailure(
2565                      InitializationSequence::FK_ReferenceInitOverloadFailed,
2566                                    ConvOvlResult);
2567
2568      return;
2569    }
2570
2571    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2572    return;
2573  }
2574
2575  //      - If the initializer expression is an rvalue, with T2 an array type,
2576  //        and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2577  //        is bound to the object represented by the rvalue (see 3.10).
2578  // FIXME: How can an array type be reference-compatible with anything?
2579  // Don't we mean the element types of T1 and T2?
2580
2581  //      - Otherwise, a temporary of type “cv1 T1” is created and initialized
2582  //        from the initializer expression using the rules for a non-reference
2583  //        copy initialization (8.5). The reference is then bound to the
2584  //        temporary. [...]
2585
2586  // Determine whether we are allowed to call explicit constructors or
2587  // explicit conversion operators.
2588  bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2589
2590  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
2591
2592  if (S.TryImplicitConversion(Sequence, TempEntity, Initializer,
2593                              /*SuppressUserConversions*/ false,
2594                              AllowExplicit,
2595                              /*FIXME:InOverloadResolution=*/false)) {
2596    // FIXME: Use the conversion function set stored in ICS to turn
2597    // this into an overloading ambiguity diagnostic. However, we need
2598    // to keep that set as an OverloadCandidateSet rather than as some
2599    // other kind of set.
2600    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2601      Sequence.SetOverloadFailure(
2602                        InitializationSequence::FK_ReferenceInitOverloadFailed,
2603                                  ConvOvlResult);
2604    else
2605      Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
2606    return;
2607  }
2608
2609  //        [...] If T1 is reference-related to T2, cv1 must be the
2610  //        same cv-qualification as, or greater cv-qualification
2611  //        than, cv2; otherwise, the program is ill-formed.
2612  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2613  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
2614  if (RefRelationship == Sema::Ref_Related &&
2615      (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
2616    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2617    return;
2618  }
2619
2620  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2621  return;
2622}
2623
2624/// \brief Attempt character array initialization from a string literal
2625/// (C++ [dcl.init.string], C99 6.7.8).
2626static void TryStringLiteralInitialization(Sema &S,
2627                                           const InitializedEntity &Entity,
2628                                           const InitializationKind &Kind,
2629                                           Expr *Initializer,
2630                                       InitializationSequence &Sequence) {
2631  Sequence.setSequenceKind(InitializationSequence::StringInit);
2632  Sequence.AddStringInitStep(Entity.getType());
2633}
2634
2635/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2636/// enumerates the constructors of the initialized entity and performs overload
2637/// resolution to select the best.
2638static void TryConstructorInitialization(Sema &S,
2639                                         const InitializedEntity &Entity,
2640                                         const InitializationKind &Kind,
2641                                         Expr **Args, unsigned NumArgs,
2642                                         QualType DestType,
2643                                         InitializationSequence &Sequence) {
2644  Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
2645
2646  // Build the candidate set directly in the initialization sequence
2647  // structure, so that it will persist if we fail.
2648  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2649  CandidateSet.clear();
2650
2651  // Determine whether we are allowed to call explicit constructors or
2652  // explicit conversion operators.
2653  bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2654                        Kind.getKind() == InitializationKind::IK_Value ||
2655                        Kind.getKind() == InitializationKind::IK_Default);
2656
2657  // The type we're constructing needs to be complete.
2658  if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2659    Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2660    return;
2661  }
2662
2663  // The type we're converting to is a class type. Enumerate its constructors
2664  // to see if one is suitable.
2665  const RecordType *DestRecordType = DestType->getAs<RecordType>();
2666  assert(DestRecordType && "Constructor initialization requires record type");
2667  CXXRecordDecl *DestRecordDecl
2668    = cast<CXXRecordDecl>(DestRecordType->getDecl());
2669
2670  DeclContext::lookup_iterator Con, ConEnd;
2671  for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2672       Con != ConEnd; ++Con) {
2673    NamedDecl *D = *Con;
2674    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2675    bool SuppressUserConversions = false;
2676
2677    // Find the constructor (which may be a template).
2678    CXXConstructorDecl *Constructor = 0;
2679    FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2680    if (ConstructorTmpl)
2681      Constructor = cast<CXXConstructorDecl>(
2682                                           ConstructorTmpl->getTemplatedDecl());
2683    else {
2684      Constructor = cast<CXXConstructorDecl>(D);
2685
2686      // If we're performing copy initialization using a copy constructor, we
2687      // suppress user-defined conversions on the arguments.
2688      // FIXME: Move constructors?
2689      if (Kind.getKind() == InitializationKind::IK_Copy &&
2690          Constructor->isCopyConstructor())
2691        SuppressUserConversions = true;
2692    }
2693
2694    if (!Constructor->isInvalidDecl() &&
2695        (AllowExplicit || !Constructor->isExplicit())) {
2696      if (ConstructorTmpl)
2697        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2698                                       /*ExplicitArgs*/ 0,
2699                                       Args, NumArgs, CandidateSet,
2700                                       SuppressUserConversions);
2701      else
2702        S.AddOverloadCandidate(Constructor, FoundDecl,
2703                               Args, NumArgs, CandidateSet,
2704                               SuppressUserConversions);
2705    }
2706  }
2707
2708  SourceLocation DeclLoc = Kind.getLocation();
2709
2710  // Perform overload resolution. If it fails, return the failed result.
2711  OverloadCandidateSet::iterator Best;
2712  if (OverloadingResult Result
2713        = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2714    Sequence.SetOverloadFailure(
2715                          InitializationSequence::FK_ConstructorOverloadFailed,
2716                                Result);
2717    return;
2718  }
2719
2720  // C++0x [dcl.init]p6:
2721  //   If a program calls for the default initialization of an object
2722  //   of a const-qualified type T, T shall be a class type with a
2723  //   user-provided default constructor.
2724  if (Kind.getKind() == InitializationKind::IK_Default &&
2725      Entity.getType().isConstQualified() &&
2726      cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
2727    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2728    return;
2729  }
2730
2731  // Add the constructor initialization step. Any cv-qualification conversion is
2732  // subsumed by the initialization.
2733  Sequence.AddConstructorInitializationStep(
2734                                      cast<CXXConstructorDecl>(Best->Function),
2735                                      Best->FoundDecl.getAccess(),
2736                                      DestType);
2737}
2738
2739/// \brief Attempt value initialization (C++ [dcl.init]p7).
2740static void TryValueInitialization(Sema &S,
2741                                   const InitializedEntity &Entity,
2742                                   const InitializationKind &Kind,
2743                                   InitializationSequence &Sequence) {
2744  // C++ [dcl.init]p5:
2745  //
2746  //   To value-initialize an object of type T means:
2747  QualType T = Entity.getType();
2748
2749  //     -- if T is an array type, then each element is value-initialized;
2750  while (const ArrayType *AT = S.Context.getAsArrayType(T))
2751    T = AT->getElementType();
2752
2753  if (const RecordType *RT = T->getAs<RecordType>()) {
2754    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2755      // -- if T is a class type (clause 9) with a user-declared
2756      //    constructor (12.1), then the default constructor for T is
2757      //    called (and the initialization is ill-formed if T has no
2758      //    accessible default constructor);
2759      //
2760      // FIXME: we really want to refer to a single subobject of the array,
2761      // but Entity doesn't have a way to capture that (yet).
2762      if (ClassDecl->hasUserDeclaredConstructor())
2763        return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2764
2765      // -- if T is a (possibly cv-qualified) non-union class type
2766      //    without a user-provided constructor, then the object is
2767      //    zero-initialized and, if T’s implicitly-declared default
2768      //    constructor is non-trivial, that constructor is called.
2769      if ((ClassDecl->getTagKind() == TTK_Class ||
2770           ClassDecl->getTagKind() == TTK_Struct) &&
2771          !ClassDecl->hasTrivialConstructor()) {
2772        Sequence.AddZeroInitializationStep(Entity.getType());
2773        return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2774      }
2775    }
2776  }
2777
2778  Sequence.AddZeroInitializationStep(Entity.getType());
2779  Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2780}
2781
2782/// \brief Attempt default initialization (C++ [dcl.init]p6).
2783static void TryDefaultInitialization(Sema &S,
2784                                     const InitializedEntity &Entity,
2785                                     const InitializationKind &Kind,
2786                                     InitializationSequence &Sequence) {
2787  assert(Kind.getKind() == InitializationKind::IK_Default);
2788
2789  // C++ [dcl.init]p6:
2790  //   To default-initialize an object of type T means:
2791  //     - if T is an array type, each element is default-initialized;
2792  QualType DestType = Entity.getType();
2793  while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2794    DestType = Array->getElementType();
2795
2796  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
2797  //       constructor for T is called (and the initialization is ill-formed if
2798  //       T has no accessible default constructor);
2799  if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
2800    return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2801                                        Sequence);
2802  }
2803
2804  //     - otherwise, no initialization is performed.
2805  Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2806
2807  //   If a program calls for the default initialization of an object of
2808  //   a const-qualified type T, T shall be a class type with a user-provided
2809  //   default constructor.
2810  if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus)
2811    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2812}
2813
2814/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2815/// which enumerates all conversion functions and performs overload resolution
2816/// to select the best.
2817static void TryUserDefinedConversion(Sema &S,
2818                                     const InitializedEntity &Entity,
2819                                     const InitializationKind &Kind,
2820                                     Expr *Initializer,
2821                                     InitializationSequence &Sequence) {
2822  Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2823
2824  QualType DestType = Entity.getType();
2825  assert(!DestType->isReferenceType() && "References are handled elsewhere");
2826  QualType SourceType = Initializer->getType();
2827  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2828         "Must have a class type to perform a user-defined conversion");
2829
2830  // Build the candidate set directly in the initialization sequence
2831  // structure, so that it will persist if we fail.
2832  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2833  CandidateSet.clear();
2834
2835  // Determine whether we are allowed to call explicit constructors or
2836  // explicit conversion operators.
2837  bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2838
2839  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2840    // The type we're converting to is a class type. Enumerate its constructors
2841    // to see if there is a suitable conversion.
2842    CXXRecordDecl *DestRecordDecl
2843      = cast<CXXRecordDecl>(DestRecordType->getDecl());
2844
2845    // Try to complete the type we're converting to.
2846    if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2847      DeclContext::lookup_iterator Con, ConEnd;
2848      for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2849           Con != ConEnd; ++Con) {
2850        NamedDecl *D = *Con;
2851        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2852
2853        // Find the constructor (which may be a template).
2854        CXXConstructorDecl *Constructor = 0;
2855        FunctionTemplateDecl *ConstructorTmpl
2856          = dyn_cast<FunctionTemplateDecl>(D);
2857        if (ConstructorTmpl)
2858          Constructor = cast<CXXConstructorDecl>(
2859                                           ConstructorTmpl->getTemplatedDecl());
2860        else
2861          Constructor = cast<CXXConstructorDecl>(D);
2862
2863        if (!Constructor->isInvalidDecl() &&
2864            Constructor->isConvertingConstructor(AllowExplicit)) {
2865          if (ConstructorTmpl)
2866            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2867                                           /*ExplicitArgs*/ 0,
2868                                           &Initializer, 1, CandidateSet,
2869                                           /*SuppressUserConversions=*/true);
2870          else
2871            S.AddOverloadCandidate(Constructor, FoundDecl,
2872                                   &Initializer, 1, CandidateSet,
2873                                   /*SuppressUserConversions=*/true);
2874        }
2875      }
2876    }
2877  }
2878
2879  SourceLocation DeclLoc = Initializer->getLocStart();
2880
2881  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2882    // The type we're converting from is a class type, enumerate its conversion
2883    // functions.
2884
2885    // We can only enumerate the conversion functions for a complete type; if
2886    // the type isn't complete, simply skip this step.
2887    if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2888      CXXRecordDecl *SourceRecordDecl
2889        = cast<CXXRecordDecl>(SourceRecordType->getDecl());
2890
2891      const UnresolvedSetImpl *Conversions
2892        = SourceRecordDecl->getVisibleConversionFunctions();
2893      for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2894           E = Conversions->end();
2895           I != E; ++I) {
2896        NamedDecl *D = *I;
2897        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2898        if (isa<UsingShadowDecl>(D))
2899          D = cast<UsingShadowDecl>(D)->getTargetDecl();
2900
2901        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2902        CXXConversionDecl *Conv;
2903        if (ConvTemplate)
2904          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2905        else
2906          Conv = cast<CXXConversionDecl>(D);
2907
2908        if (AllowExplicit || !Conv->isExplicit()) {
2909          if (ConvTemplate)
2910            S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
2911                                             ActingDC, Initializer, DestType,
2912                                             CandidateSet);
2913          else
2914            S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
2915                                     Initializer, DestType, CandidateSet);
2916        }
2917      }
2918    }
2919  }
2920
2921  // Perform overload resolution. If it fails, return the failed result.
2922  OverloadCandidateSet::iterator Best;
2923  if (OverloadingResult Result
2924        = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2925    Sequence.SetOverloadFailure(
2926                        InitializationSequence::FK_UserConversionOverloadFailed,
2927                                Result);
2928    return;
2929  }
2930
2931  FunctionDecl *Function = Best->Function;
2932
2933  if (isa<CXXConstructorDecl>(Function)) {
2934    // Add the user-defined conversion step. Any cv-qualification conversion is
2935    // subsumed by the initialization.
2936    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
2937    return;
2938  }
2939
2940  // Add the user-defined conversion step that calls the conversion function.
2941  QualType ConvType = Function->getResultType().getNonReferenceType();
2942  if (ConvType->getAs<RecordType>()) {
2943    // If we're converting to a class type, there may be an copy if
2944    // the resulting temporary object (possible to create an object of
2945    // a base class type). That copy is not a separate conversion, so
2946    // we just make a note of the actual destination type (possibly a
2947    // base class of the type returned by the conversion function) and
2948    // let the user-defined conversion step handle the conversion.
2949    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
2950    return;
2951  }
2952
2953  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
2954
2955  // If the conversion following the call to the conversion function
2956  // is interesting, add it as a separate step.
2957  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2958      Best->FinalConversion.Third) {
2959    ImplicitConversionSequence ICS;
2960    ICS.setStandard();
2961    ICS.Standard = Best->FinalConversion;
2962    Sequence.AddConversionSequenceStep(ICS, DestType);
2963  }
2964}
2965
2966bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
2967                                 const InitializedEntity &Entity,
2968                                 Expr *Initializer,
2969                                 bool SuppressUserConversions,
2970                                 bool AllowExplicitConversions,
2971                                 bool InOverloadResolution) {
2972  ImplicitConversionSequence ICS
2973    = TryImplicitConversion(Initializer, Entity.getType(),
2974                            SuppressUserConversions,
2975                            AllowExplicitConversions,
2976                            InOverloadResolution);
2977  if (ICS.isBad()) return true;
2978
2979  // Perform the actual conversion.
2980  Sequence.AddConversionSequenceStep(ICS, Entity.getType());
2981  return false;
2982}
2983
2984InitializationSequence::InitializationSequence(Sema &S,
2985                                               const InitializedEntity &Entity,
2986                                               const InitializationKind &Kind,
2987                                               Expr **Args,
2988                                               unsigned NumArgs)
2989    : FailedCandidateSet(Kind.getLocation()) {
2990  ASTContext &Context = S.Context;
2991
2992  // C++0x [dcl.init]p16:
2993  //   The semantics of initializers are as follows. The destination type is
2994  //   the type of the object or reference being initialized and the source
2995  //   type is the type of the initializer expression. The source type is not
2996  //   defined when the initializer is a braced-init-list or when it is a
2997  //   parenthesized list of expressions.
2998  QualType DestType = Entity.getType();
2999
3000  if (DestType->isDependentType() ||
3001      Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3002    SequenceKind = DependentSequence;
3003    return;
3004  }
3005
3006  QualType SourceType;
3007  Expr *Initializer = 0;
3008  if (NumArgs == 1) {
3009    Initializer = Args[0];
3010    if (!isa<InitListExpr>(Initializer))
3011      SourceType = Initializer->getType();
3012  }
3013
3014  //     - If the initializer is a braced-init-list, the object is
3015  //       list-initialized (8.5.4).
3016  if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
3017    TryListInitialization(S, Entity, Kind, InitList, *this);
3018    return;
3019  }
3020
3021  //     - If the destination type is a reference type, see 8.5.3.
3022  if (DestType->isReferenceType()) {
3023    // C++0x [dcl.init.ref]p1:
3024    //   A variable declared to be a T& or T&&, that is, "reference to type T"
3025    //   (8.3.2), shall be initialized by an object, or function, of type T or
3026    //   by an object that can be converted into a T.
3027    // (Therefore, multiple arguments are not permitted.)
3028    if (NumArgs != 1)
3029      SetFailed(FK_TooManyInitsForReference);
3030    else
3031      TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
3032    return;
3033  }
3034
3035  //     - If the destination type is an array of characters, an array of
3036  //       char16_t, an array of char32_t, or an array of wchar_t, and the
3037  //       initializer is a string literal, see 8.5.2.
3038  if (Initializer && IsStringInit(Initializer, DestType, Context)) {
3039    TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
3040    return;
3041  }
3042
3043  //     - If the initializer is (), the object is value-initialized.
3044  if (Kind.getKind() == InitializationKind::IK_Value ||
3045      (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
3046    TryValueInitialization(S, Entity, Kind, *this);
3047    return;
3048  }
3049
3050  // Handle default initialization.
3051  if (Kind.getKind() == InitializationKind::IK_Default){
3052    TryDefaultInitialization(S, Entity, Kind, *this);
3053    return;
3054  }
3055
3056  //     - Otherwise, if the destination type is an array, the program is
3057  //       ill-formed.
3058  if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
3059    if (AT->getElementType()->isAnyCharacterType())
3060      SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
3061    else
3062      SetFailed(FK_ArrayNeedsInitList);
3063
3064    return;
3065  }
3066
3067  // Handle initialization in C
3068  if (!S.getLangOptions().CPlusPlus) {
3069    setSequenceKind(CAssignment);
3070    AddCAssignmentStep(DestType);
3071    return;
3072  }
3073
3074  //     - If the destination type is a (possibly cv-qualified) class type:
3075  if (DestType->isRecordType()) {
3076    //     - If the initialization is direct-initialization, or if it is
3077    //       copy-initialization where the cv-unqualified version of the
3078    //       source type is the same class as, or a derived class of, the
3079    //       class of the destination, constructors are considered. [...]
3080    if (Kind.getKind() == InitializationKind::IK_Direct ||
3081        (Kind.getKind() == InitializationKind::IK_Copy &&
3082         (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3083          S.IsDerivedFrom(SourceType, DestType))))
3084      TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
3085                                   Entity.getType(), *this);
3086    //     - Otherwise (i.e., for the remaining copy-initialization cases),
3087    //       user-defined conversion sequences that can convert from the source
3088    //       type to the destination type or (when a conversion function is
3089    //       used) to a derived class thereof are enumerated as described in
3090    //       13.3.1.4, and the best one is chosen through overload resolution
3091    //       (13.3).
3092    else
3093      TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3094    return;
3095  }
3096
3097  if (NumArgs > 1) {
3098    SetFailed(FK_TooManyInitsForScalar);
3099    return;
3100  }
3101  assert(NumArgs == 1 && "Zero-argument case handled above");
3102
3103  //    - Otherwise, if the source type is a (possibly cv-qualified) class
3104  //      type, conversion functions are considered.
3105  if (!SourceType.isNull() && SourceType->isRecordType()) {
3106    TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3107    return;
3108  }
3109
3110  //    - Otherwise, the initial value of the object being initialized is the
3111  //      (possibly converted) value of the initializer expression. Standard
3112  //      conversions (Clause 4) will be used, if necessary, to convert the
3113  //      initializer expression to the cv-unqualified version of the
3114  //      destination type; no user-defined conversions are considered.
3115  if (S.TryImplicitConversion(*this, Entity, Initializer,
3116                              /*SuppressUserConversions*/ true,
3117                              /*AllowExplicitConversions*/ false,
3118                              /*InOverloadResolution*/ false))
3119    SetFailed(InitializationSequence::FK_ConversionFailed);
3120  else
3121    setSequenceKind(StandardConversion);
3122}
3123
3124InitializationSequence::~InitializationSequence() {
3125  for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
3126                                          StepEnd = Steps.end();
3127       Step != StepEnd; ++Step)
3128    Step->Destroy();
3129}
3130
3131//===----------------------------------------------------------------------===//
3132// Perform initialization
3133//===----------------------------------------------------------------------===//
3134static Sema::AssignmentAction
3135getAssignmentAction(const InitializedEntity &Entity) {
3136  switch(Entity.getKind()) {
3137  case InitializedEntity::EK_Variable:
3138  case InitializedEntity::EK_New:
3139    return Sema::AA_Initializing;
3140
3141  case InitializedEntity::EK_Parameter:
3142    if (Entity.getDecl() &&
3143        isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3144      return Sema::AA_Sending;
3145
3146    return Sema::AA_Passing;
3147
3148  case InitializedEntity::EK_Result:
3149    return Sema::AA_Returning;
3150
3151  case InitializedEntity::EK_Exception:
3152  case InitializedEntity::EK_Base:
3153    llvm_unreachable("No assignment action for C++-specific initialization");
3154    break;
3155
3156  case InitializedEntity::EK_Temporary:
3157    // FIXME: Can we tell apart casting vs. converting?
3158    return Sema::AA_Casting;
3159
3160  case InitializedEntity::EK_Member:
3161  case InitializedEntity::EK_ArrayElement:
3162  case InitializedEntity::EK_VectorElement:
3163  case InitializedEntity::EK_BlockElement:
3164    return Sema::AA_Initializing;
3165  }
3166
3167  return Sema::AA_Converting;
3168}
3169
3170/// \brief Whether we should binding a created object as a temporary when
3171/// initializing the given entity.
3172static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
3173  switch (Entity.getKind()) {
3174  case InitializedEntity::EK_ArrayElement:
3175  case InitializedEntity::EK_Member:
3176  case InitializedEntity::EK_Result:
3177  case InitializedEntity::EK_New:
3178  case InitializedEntity::EK_Variable:
3179  case InitializedEntity::EK_Base:
3180  case InitializedEntity::EK_VectorElement:
3181  case InitializedEntity::EK_Exception:
3182  case InitializedEntity::EK_BlockElement:
3183    return false;
3184
3185  case InitializedEntity::EK_Parameter:
3186  case InitializedEntity::EK_Temporary:
3187    return true;
3188  }
3189
3190  llvm_unreachable("missed an InitializedEntity kind?");
3191}
3192
3193/// \brief Whether the given entity, when initialized with an object
3194/// created for that initialization, requires destruction.
3195static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3196  switch (Entity.getKind()) {
3197    case InitializedEntity::EK_Member:
3198    case InitializedEntity::EK_Result:
3199    case InitializedEntity::EK_New:
3200    case InitializedEntity::EK_Base:
3201    case InitializedEntity::EK_VectorElement:
3202    case InitializedEntity::EK_BlockElement:
3203      return false;
3204
3205    case InitializedEntity::EK_Variable:
3206    case InitializedEntity::EK_Parameter:
3207    case InitializedEntity::EK_Temporary:
3208    case InitializedEntity::EK_ArrayElement:
3209    case InitializedEntity::EK_Exception:
3210      return true;
3211  }
3212
3213  llvm_unreachable("missed an InitializedEntity kind?");
3214}
3215
3216/// \brief Make a (potentially elidable) temporary copy of the object
3217/// provided by the given initializer by calling the appropriate copy
3218/// constructor.
3219///
3220/// \param S The Sema object used for type-checking.
3221///
3222/// \param T The type of the temporary object, which must either by
3223/// the type of the initializer expression or a superclass thereof.
3224///
3225/// \param Enter The entity being initialized.
3226///
3227/// \param CurInit The initializer expression.
3228///
3229/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3230/// is permitted in C++03 (but not C++0x) when binding a reference to
3231/// an rvalue.
3232///
3233/// \returns An expression that copies the initializer expression into
3234/// a temporary object, or an error expression if a copy could not be
3235/// created.
3236static Sema::OwningExprResult CopyObject(Sema &S,
3237                                         QualType T,
3238                                         const InitializedEntity &Entity,
3239                                         Sema::OwningExprResult CurInit,
3240                                         bool IsExtraneousCopy) {
3241  // Determine which class type we're copying to.
3242  Expr *CurInitExpr = (Expr *)CurInit.get();
3243  CXXRecordDecl *Class = 0;
3244  if (const RecordType *Record = T->getAs<RecordType>())
3245    Class = cast<CXXRecordDecl>(Record->getDecl());
3246  if (!Class)
3247    return move(CurInit);
3248
3249  // C++0x [class.copy]p34:
3250  //   When certain criteria are met, an implementation is allowed to
3251  //   omit the copy/move construction of a class object, even if the
3252  //   copy/move constructor and/or destructor for the object have
3253  //   side effects. [...]
3254  //     - when a temporary class object that has not been bound to a
3255  //       reference (12.2) would be copied/moved to a class object
3256  //       with the same cv-unqualified type, the copy/move operation
3257  //       can be omitted by constructing the temporary object
3258  //       directly into the target of the omitted copy/move
3259  //
3260  // Note that the other three bullets are handled elsewhere. Copy
3261  // elision for return statements and throw expressions are handled as part
3262  // of constructor initialization, while copy elision for exception handlers
3263  // is handled by the run-time.
3264  bool Elidable = CurInitExpr->isTemporaryObject() &&
3265     S.Context.hasSameUnqualifiedType(T, CurInitExpr->getType());
3266  SourceLocation Loc;
3267  switch (Entity.getKind()) {
3268  case InitializedEntity::EK_Result:
3269    Loc = Entity.getReturnLoc();
3270    break;
3271
3272  case InitializedEntity::EK_Exception:
3273    Loc = Entity.getThrowLoc();
3274    break;
3275
3276  case InitializedEntity::EK_Variable:
3277    Loc = Entity.getDecl()->getLocation();
3278    break;
3279
3280  case InitializedEntity::EK_ArrayElement:
3281  case InitializedEntity::EK_Member:
3282  case InitializedEntity::EK_Parameter:
3283  case InitializedEntity::EK_Temporary:
3284  case InitializedEntity::EK_New:
3285  case InitializedEntity::EK_Base:
3286  case InitializedEntity::EK_VectorElement:
3287  case InitializedEntity::EK_BlockElement:
3288    Loc = CurInitExpr->getLocStart();
3289    break;
3290  }
3291
3292  // Make sure that the type we are copying is complete.
3293  if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3294    return move(CurInit);
3295
3296  // Perform overload resolution using the class's copy constructors.
3297  DeclContext::lookup_iterator Con, ConEnd;
3298  OverloadCandidateSet CandidateSet(Loc);
3299  for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
3300       Con != ConEnd; ++Con) {
3301    // Only consider copy constructors.
3302    CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3303    if (!Constructor || Constructor->isInvalidDecl() ||
3304        !Constructor->isCopyConstructor() ||
3305        !Constructor->isConvertingConstructor(/*AllowExplicit=*/false))
3306      continue;
3307
3308    DeclAccessPair FoundDecl
3309      = DeclAccessPair::make(Constructor, Constructor->getAccess());
3310    S.AddOverloadCandidate(Constructor, FoundDecl,
3311                           &CurInitExpr, 1, CandidateSet);
3312  }
3313
3314  OverloadCandidateSet::iterator Best;
3315  switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3316  case OR_Success:
3317    break;
3318
3319  case OR_No_Viable_Function:
3320    S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3321           ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3322           : diag::err_temp_copy_no_viable)
3323      << (int)Entity.getKind() << CurInitExpr->getType()
3324      << CurInitExpr->getSourceRange();
3325    S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3326                              &CurInitExpr, 1);
3327    if (!IsExtraneousCopy || S.isSFINAEContext())
3328      return S.ExprError();
3329    return move(CurInit);
3330
3331  case OR_Ambiguous:
3332    S.Diag(Loc, diag::err_temp_copy_ambiguous)
3333      << (int)Entity.getKind() << CurInitExpr->getType()
3334      << CurInitExpr->getSourceRange();
3335    S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3336                              &CurInitExpr, 1);
3337    return S.ExprError();
3338
3339  case OR_Deleted:
3340    S.Diag(Loc, diag::err_temp_copy_deleted)
3341      << (int)Entity.getKind() << CurInitExpr->getType()
3342      << CurInitExpr->getSourceRange();
3343    S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3344      << Best->Function->isDeleted();
3345    return S.ExprError();
3346  }
3347
3348  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3349  ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3350  CurInit.release(); // Ownership transferred into MultiExprArg, below.
3351
3352  S.CheckConstructorAccess(Loc, Constructor, Entity,
3353                           Best->FoundDecl.getAccess(), IsExtraneousCopy);
3354
3355  if (IsExtraneousCopy) {
3356    // If this is a totally extraneous copy for C++03 reference
3357    // binding purposes, just return the original initialization
3358    // expression. We don't generate an (elided) copy operation here
3359    // because doing so would require us to pass down a flag to avoid
3360    // infinite recursion, where each step adds another extraneous,
3361    // elidable copy.
3362
3363    // Instantiate the default arguments of any extra parameters in
3364    // the selected copy constructor, as if we were going to create a
3365    // proper call to the copy constructor.
3366    for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
3367      ParmVarDecl *Parm = Constructor->getParamDecl(I);
3368      if (S.RequireCompleteType(Loc, Parm->getType(),
3369                                S.PDiag(diag::err_call_incomplete_argument)))
3370        break;
3371
3372      // Build the default argument expression; we don't actually care
3373      // if this succeeds or not, because this routine will complain
3374      // if there was a problem.
3375      S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
3376    }
3377
3378    return S.Owned(CurInitExpr);
3379  }
3380
3381  // Determine the arguments required to actually perform the
3382  // constructor call (we might have derived-to-base conversions, or
3383  // the copy constructor may have default arguments).
3384  if (S.CompleteConstructorCall(Constructor,
3385                                Sema::MultiExprArg(S,
3386                                                   (void **)&CurInitExpr,
3387                                                   1),
3388                                Loc, ConstructorArgs))
3389    return S.ExprError();
3390
3391  // Actually perform the constructor call.
3392  CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
3393                                    move_arg(ConstructorArgs));
3394
3395  // If we're supposed to bind temporaries, do so.
3396  if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
3397    CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3398  return move(CurInit);
3399}
3400
3401void InitializationSequence::PrintInitLocationNote(Sema &S,
3402                                              const InitializedEntity &Entity) {
3403  if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
3404    if (Entity.getDecl()->getLocation().isInvalid())
3405      return;
3406
3407    if (Entity.getDecl()->getDeclName())
3408      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
3409        << Entity.getDecl()->getDeclName();
3410    else
3411      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
3412  }
3413}
3414
3415Action::OwningExprResult
3416InitializationSequence::Perform(Sema &S,
3417                                const InitializedEntity &Entity,
3418                                const InitializationKind &Kind,
3419                                Action::MultiExprArg Args,
3420                                QualType *ResultType) {
3421  if (SequenceKind == FailedSequence) {
3422    unsigned NumArgs = Args.size();
3423    Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3424    return S.ExprError();
3425  }
3426
3427  if (SequenceKind == DependentSequence) {
3428    // If the declaration is a non-dependent, incomplete array type
3429    // that has an initializer, then its type will be completed once
3430    // the initializer is instantiated.
3431    if (ResultType && !Entity.getType()->isDependentType() &&
3432        Args.size() == 1) {
3433      QualType DeclType = Entity.getType();
3434      if (const IncompleteArrayType *ArrayT
3435                           = S.Context.getAsIncompleteArrayType(DeclType)) {
3436        // FIXME: We don't currently have the ability to accurately
3437        // compute the length of an initializer list without
3438        // performing full type-checking of the initializer list
3439        // (since we have to determine where braces are implicitly
3440        // introduced and such).  So, we fall back to making the array
3441        // type a dependently-sized array type with no specified
3442        // bound.
3443        if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3444          SourceRange Brackets;
3445
3446          // Scavange the location of the brackets from the entity, if we can.
3447          if (DeclaratorDecl *DD = Entity.getDecl()) {
3448            if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3449              TypeLoc TL = TInfo->getTypeLoc();
3450              if (IncompleteArrayTypeLoc *ArrayLoc
3451                                      = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3452              Brackets = ArrayLoc->getBracketsRange();
3453            }
3454          }
3455
3456          *ResultType
3457            = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3458                                                   /*NumElts=*/0,
3459                                                   ArrayT->getSizeModifier(),
3460                                       ArrayT->getIndexTypeCVRQualifiers(),
3461                                                   Brackets);
3462        }
3463
3464      }
3465    }
3466
3467    if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
3468      return Sema::OwningExprResult(S, Args.release()[0]);
3469
3470    if (Args.size() == 0)
3471      return S.Owned((Expr *)0);
3472
3473    unsigned NumArgs = Args.size();
3474    return S.Owned(new (S.Context) ParenListExpr(S.Context,
3475                                                 SourceLocation(),
3476                                                 (Expr **)Args.release(),
3477                                                 NumArgs,
3478                                                 SourceLocation()));
3479  }
3480
3481  if (SequenceKind == NoInitialization)
3482    return S.Owned((Expr *)0);
3483
3484  QualType DestType = Entity.getType().getNonReferenceType();
3485  // FIXME: Ugly hack around the fact that Entity.getType() is not
3486  // the same as Entity.getDecl()->getType() in cases involving type merging,
3487  //  and we want latter when it makes sense.
3488  if (ResultType)
3489    *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
3490                                     Entity.getType();
3491
3492  Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3493
3494  assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3495
3496  // For initialization steps that start with a single initializer,
3497  // grab the only argument out the Args and place it into the "current"
3498  // initializer.
3499  switch (Steps.front().Kind) {
3500  case SK_ResolveAddressOfOverloadedFunction:
3501  case SK_CastDerivedToBaseRValue:
3502  case SK_CastDerivedToBaseLValue:
3503  case SK_BindReference:
3504  case SK_BindReferenceToTemporary:
3505  case SK_ExtraneousCopyToTemporary:
3506  case SK_UserConversion:
3507  case SK_QualificationConversionLValue:
3508  case SK_QualificationConversionRValue:
3509  case SK_ConversionSequence:
3510  case SK_ListInitialization:
3511  case SK_CAssignment:
3512  case SK_StringInit:
3513    assert(Args.size() == 1);
3514    CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3515    if (CurInit.isInvalid())
3516      return S.ExprError();
3517    break;
3518
3519  case SK_ConstructorInitialization:
3520  case SK_ZeroInitialization:
3521    break;
3522  }
3523
3524  // Walk through the computed steps for the initialization sequence,
3525  // performing the specified conversions along the way.
3526  bool ConstructorInitRequiresZeroInit = false;
3527  for (step_iterator Step = step_begin(), StepEnd = step_end();
3528       Step != StepEnd; ++Step) {
3529    if (CurInit.isInvalid())
3530      return S.ExprError();
3531
3532    Expr *CurInitExpr = (Expr *)CurInit.get();
3533    QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
3534
3535    switch (Step->Kind) {
3536    case SK_ResolveAddressOfOverloadedFunction:
3537      // Overload resolution determined which function invoke; update the
3538      // initializer to reflect that choice.
3539      S.CheckAddressOfMemberAccess(CurInitExpr, Step->Function.FoundDecl);
3540      S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
3541      CurInit = S.FixOverloadedFunctionReference(move(CurInit),
3542                                                 Step->Function.FoundDecl,
3543                                                 Step->Function.Function);
3544      break;
3545
3546    case SK_CastDerivedToBaseRValue:
3547    case SK_CastDerivedToBaseLValue: {
3548      // We have a derived-to-base cast that produces either an rvalue or an
3549      // lvalue. Perform that cast.
3550
3551      CXXBaseSpecifierArray BasePath;
3552
3553      // Casts to inaccessible base classes are allowed with C-style casts.
3554      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3555      if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3556                                         CurInitExpr->getLocStart(),
3557                                         CurInitExpr->getSourceRange(),
3558                                         &BasePath, IgnoreBaseAccess))
3559        return S.ExprError();
3560
3561      if (S.BasePathInvolvesVirtualBase(BasePath)) {
3562        QualType T = SourceType;
3563        if (const PointerType *Pointer = T->getAs<PointerType>())
3564          T = Pointer->getPointeeType();
3565        if (const RecordType *RecordTy = T->getAs<RecordType>())
3566          S.MarkVTableUsed(CurInitExpr->getLocStart(),
3567                           cast<CXXRecordDecl>(RecordTy->getDecl()));
3568      }
3569
3570      CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3571                                                    CastExpr::CK_DerivedToBase,
3572                                                    (Expr*)CurInit.release(),
3573                                                    BasePath,
3574                                     Step->Kind == SK_CastDerivedToBaseLValue));
3575      break;
3576    }
3577
3578    case SK_BindReference:
3579      if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3580        // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3581        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3582          << Entity.getType().isVolatileQualified()
3583          << BitField->getDeclName()
3584          << CurInitExpr->getSourceRange();
3585        S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3586        return S.ExprError();
3587      }
3588
3589      if (CurInitExpr->refersToVectorElement()) {
3590        // References cannot bind to vector elements.
3591        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
3592          << Entity.getType().isVolatileQualified()
3593          << CurInitExpr->getSourceRange();
3594        PrintInitLocationNote(S, Entity);
3595        return S.ExprError();
3596      }
3597
3598      // Reference binding does not have any corresponding ASTs.
3599
3600      // Check exception specifications
3601      if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3602        return S.ExprError();
3603
3604      break;
3605
3606    case SK_BindReferenceToTemporary:
3607      // Reference binding does not have any corresponding ASTs.
3608
3609      // Check exception specifications
3610      if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3611        return S.ExprError();
3612
3613      break;
3614
3615    case SK_ExtraneousCopyToTemporary:
3616      CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
3617                           /*IsExtraneousCopy=*/true);
3618      break;
3619
3620    case SK_UserConversion: {
3621      // We have a user-defined conversion that invokes either a constructor
3622      // or a conversion function.
3623      CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
3624      bool IsCopy = false;
3625      FunctionDecl *Fn = Step->Function.Function;
3626      DeclAccessPair FoundFn = Step->Function.FoundDecl;
3627      bool CreatedObject = false;
3628      bool IsLvalue = false;
3629      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
3630        // Build a call to the selected constructor.
3631        ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3632        SourceLocation Loc = CurInitExpr->getLocStart();
3633        CurInit.release(); // Ownership transferred into MultiExprArg, below.
3634
3635        // Determine the arguments required to actually perform the constructor
3636        // call.
3637        if (S.CompleteConstructorCall(Constructor,
3638                                      Sema::MultiExprArg(S,
3639                                                         (void **)&CurInitExpr,
3640                                                         1),
3641                                      Loc, ConstructorArgs))
3642          return S.ExprError();
3643
3644        // Build the an expression that constructs a temporary.
3645        CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3646                                          move_arg(ConstructorArgs));
3647        if (CurInit.isInvalid())
3648          return S.ExprError();
3649
3650        S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
3651                                 FoundFn.getAccess());
3652        S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
3653
3654        CastKind = CastExpr::CK_ConstructorConversion;
3655        QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3656        if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3657            S.IsDerivedFrom(SourceType, Class))
3658          IsCopy = true;
3659
3660        CreatedObject = true;
3661      } else {
3662        // Build a call to the conversion function.
3663        CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
3664        IsLvalue = Conversion->getResultType()->isLValueReferenceType();
3665        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInitExpr, 0,
3666                                    FoundFn);
3667        S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
3668
3669        // FIXME: Should we move this initialization into a separate
3670        // derived-to-base conversion? I believe the answer is "no", because
3671        // we don't want to turn off access control here for c-style casts.
3672        if (S.PerformObjectArgumentInitialization(CurInitExpr, /*Qualifier=*/0,
3673                                                  FoundFn, Conversion))
3674          return S.ExprError();
3675
3676        // Do a little dance to make sure that CurInit has the proper
3677        // pointer.
3678        CurInit.release();
3679
3680        // Build the actual call to the conversion function.
3681        CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, FoundFn,
3682                                                   Conversion));
3683        if (CurInit.isInvalid() || !CurInit.get())
3684          return S.ExprError();
3685
3686        CastKind = CastExpr::CK_UserDefinedConversion;
3687
3688        CreatedObject = Conversion->getResultType()->isRecordType();
3689      }
3690
3691      bool RequiresCopy = !IsCopy &&
3692        getKind() != InitializationSequence::ReferenceBinding;
3693      if (RequiresCopy || shouldBindAsTemporary(Entity))
3694        CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3695      else if (CreatedObject && shouldDestroyTemporary(Entity)) {
3696        CurInitExpr = static_cast<Expr *>(CurInit.get());
3697        QualType T = CurInitExpr->getType();
3698        if (const RecordType *Record = T->getAs<RecordType>()) {
3699          CXXDestructorDecl *Destructor
3700            = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
3701          S.CheckDestructorAccess(CurInitExpr->getLocStart(), Destructor,
3702                                  S.PDiag(diag::err_access_dtor_temp) << T);
3703          S.MarkDeclarationReferenced(CurInitExpr->getLocStart(), Destructor);
3704        }
3705      }
3706
3707      CurInitExpr = CurInit.takeAs<Expr>();
3708      CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3709                                                         CastKind,
3710                                                         CurInitExpr,
3711                                                        CXXBaseSpecifierArray(),
3712                                                         IsLvalue));
3713
3714      if (RequiresCopy)
3715        CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
3716                             move(CurInit), /*IsExtraneousCopy=*/false);
3717
3718      break;
3719    }
3720
3721    case SK_QualificationConversionLValue:
3722    case SK_QualificationConversionRValue:
3723      // Perform a qualification conversion; these can never go wrong.
3724      S.ImpCastExprToType(CurInitExpr, Step->Type,
3725                          CastExpr::CK_NoOp,
3726                          Step->Kind == SK_QualificationConversionLValue);
3727      CurInit.release();
3728      CurInit = S.Owned(CurInitExpr);
3729      break;
3730
3731    case SK_ConversionSequence: {
3732      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3733
3734      if (S.PerformImplicitConversion(CurInitExpr, Step->Type, *Step->ICS,
3735                                      Sema::AA_Converting, IgnoreBaseAccess))
3736        return S.ExprError();
3737
3738      CurInit.release();
3739      CurInit = S.Owned(CurInitExpr);
3740      break;
3741    }
3742
3743    case SK_ListInitialization: {
3744      InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3745      QualType Ty = Step->Type;
3746      if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
3747        return S.ExprError();
3748
3749      CurInit.release();
3750      CurInit = S.Owned(InitList);
3751      break;
3752    }
3753
3754    case SK_ConstructorInitialization: {
3755      unsigned NumArgs = Args.size();
3756      CXXConstructorDecl *Constructor
3757        = cast<CXXConstructorDecl>(Step->Function.Function);
3758
3759      // Build a call to the selected constructor.
3760      ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3761      SourceLocation Loc = Kind.getLocation();
3762
3763      // Determine the arguments required to actually perform the constructor
3764      // call.
3765      if (S.CompleteConstructorCall(Constructor, move(Args),
3766                                    Loc, ConstructorArgs))
3767        return S.ExprError();
3768
3769      // Build the expression that constructs a temporary.
3770      if (Entity.getKind() == InitializedEntity::EK_Temporary &&
3771          NumArgs != 1 && // FIXME: Hack to work around cast weirdness
3772          (Kind.getKind() == InitializationKind::IK_Direct ||
3773           Kind.getKind() == InitializationKind::IK_Value)) {
3774        // An explicitly-constructed temporary, e.g., X(1, 2).
3775        unsigned NumExprs = ConstructorArgs.size();
3776        Expr **Exprs = (Expr **)ConstructorArgs.take();
3777        S.MarkDeclarationReferenced(Kind.getLocation(), Constructor);
3778        CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
3779                                                                 Constructor,
3780                                                              Entity.getType(),
3781                                                            Kind.getLocation(),
3782                                                                 Exprs,
3783                                                                 NumExprs,
3784                                                Kind.getParenRange().getEnd(),
3785                                             ConstructorInitRequiresZeroInit));
3786      } else {
3787        CXXConstructExpr::ConstructionKind ConstructKind =
3788          CXXConstructExpr::CK_Complete;
3789
3790        if (Entity.getKind() == InitializedEntity::EK_Base) {
3791          ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
3792            CXXConstructExpr::CK_VirtualBase :
3793            CXXConstructExpr::CK_NonVirtualBase;
3794        }
3795
3796        // If the entity allows NRVO, mark the construction as elidable
3797        // unconditionally.
3798        if (Entity.allowsNRVO())
3799          CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3800                                            Constructor, /*Elidable=*/true,
3801                                            move_arg(ConstructorArgs),
3802                                            ConstructorInitRequiresZeroInit,
3803                                            ConstructKind);
3804        else
3805          CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
3806                                            Constructor,
3807                                            move_arg(ConstructorArgs),
3808                                            ConstructorInitRequiresZeroInit,
3809                                            ConstructKind);
3810      }
3811      if (CurInit.isInvalid())
3812        return S.ExprError();
3813
3814      // Only check access if all of that succeeded.
3815      S.CheckConstructorAccess(Loc, Constructor, Entity,
3816                               Step->Function.FoundDecl.getAccess());
3817      S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
3818
3819      if (shouldBindAsTemporary(Entity))
3820        CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3821
3822      break;
3823    }
3824
3825    case SK_ZeroInitialization: {
3826      step_iterator NextStep = Step;
3827      ++NextStep;
3828      if (NextStep != StepEnd &&
3829          NextStep->Kind == SK_ConstructorInitialization) {
3830        // The need for zero-initialization is recorded directly into
3831        // the call to the object's constructor within the next step.
3832        ConstructorInitRequiresZeroInit = true;
3833      } else if (Kind.getKind() == InitializationKind::IK_Value &&
3834                 S.getLangOptions().CPlusPlus &&
3835                 !Kind.isImplicitValueInit()) {
3836        CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3837                                                   Kind.getRange().getBegin(),
3838                                                    Kind.getRange().getEnd()));
3839      } else {
3840        CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
3841      }
3842      break;
3843    }
3844
3845    case SK_CAssignment: {
3846      QualType SourceType = CurInitExpr->getType();
3847      Sema::AssignConvertType ConvTy =
3848        S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
3849
3850      // If this is a call, allow conversion to a transparent union.
3851      if (ConvTy != Sema::Compatible &&
3852          Entity.getKind() == InitializedEntity::EK_Parameter &&
3853          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3854            == Sema::Compatible)
3855        ConvTy = Sema::Compatible;
3856
3857      bool Complained;
3858      if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3859                                     Step->Type, SourceType,
3860                                     CurInitExpr,
3861                                     getAssignmentAction(Entity),
3862                                     &Complained)) {
3863        PrintInitLocationNote(S, Entity);
3864        return S.ExprError();
3865      } else if (Complained)
3866        PrintInitLocationNote(S, Entity);
3867
3868      CurInit.release();
3869      CurInit = S.Owned(CurInitExpr);
3870      break;
3871    }
3872
3873    case SK_StringInit: {
3874      QualType Ty = Step->Type;
3875      CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3876      break;
3877    }
3878    }
3879  }
3880
3881  return move(CurInit);
3882}
3883
3884//===----------------------------------------------------------------------===//
3885// Diagnose initialization failures
3886//===----------------------------------------------------------------------===//
3887bool InitializationSequence::Diagnose(Sema &S,
3888                                      const InitializedEntity &Entity,
3889                                      const InitializationKind &Kind,
3890                                      Expr **Args, unsigned NumArgs) {
3891  if (SequenceKind != FailedSequence)
3892    return false;
3893
3894  QualType DestType = Entity.getType();
3895  switch (Failure) {
3896  case FK_TooManyInitsForReference:
3897    // FIXME: Customize for the initialized entity?
3898    if (NumArgs == 0)
3899      S.Diag(Kind.getLocation(), diag::err_reference_without_init)
3900        << DestType.getNonReferenceType();
3901    else  // FIXME: diagnostic below could be better!
3902      S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3903        << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3904    break;
3905
3906  case FK_ArrayNeedsInitList:
3907  case FK_ArrayNeedsInitListOrStringLiteral:
3908    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3909      << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3910    break;
3911
3912  case FK_AddressOfOverloadFailed: {
3913    DeclAccessPair Found;
3914    S.ResolveAddressOfOverloadedFunction(Args[0],
3915                                         DestType.getNonReferenceType(),
3916                                         true,
3917                                         Found);
3918    break;
3919  }
3920
3921  case FK_ReferenceInitOverloadFailed:
3922  case FK_UserConversionOverloadFailed:
3923    switch (FailedOverloadResult) {
3924    case OR_Ambiguous:
3925      if (Failure == FK_UserConversionOverloadFailed)
3926        S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3927          << Args[0]->getType() << DestType
3928          << Args[0]->getSourceRange();
3929      else
3930        S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3931          << DestType << Args[0]->getType()
3932          << Args[0]->getSourceRange();
3933
3934      S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3935                                Args, NumArgs);
3936      break;
3937
3938    case OR_No_Viable_Function:
3939      S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3940        << Args[0]->getType() << DestType.getNonReferenceType()
3941        << Args[0]->getSourceRange();
3942      S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3943                                Args, NumArgs);
3944      break;
3945
3946    case OR_Deleted: {
3947      S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3948        << Args[0]->getType() << DestType.getNonReferenceType()
3949        << Args[0]->getSourceRange();
3950      OverloadCandidateSet::iterator Best;
3951      OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3952                                                   Kind.getLocation(),
3953                                                   Best);
3954      if (Ovl == OR_Deleted) {
3955        S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3956          << Best->Function->isDeleted();
3957      } else {
3958        llvm_unreachable("Inconsistent overload resolution?");
3959      }
3960      break;
3961    }
3962
3963    case OR_Success:
3964      llvm_unreachable("Conversion did not fail!");
3965      break;
3966    }
3967    break;
3968
3969  case FK_NonConstLValueReferenceBindingToTemporary:
3970  case FK_NonConstLValueReferenceBindingToUnrelated:
3971    S.Diag(Kind.getLocation(),
3972           Failure == FK_NonConstLValueReferenceBindingToTemporary
3973             ? diag::err_lvalue_reference_bind_to_temporary
3974             : diag::err_lvalue_reference_bind_to_unrelated)
3975      << DestType.getNonReferenceType().isVolatileQualified()
3976      << DestType.getNonReferenceType()
3977      << Args[0]->getType()
3978      << Args[0]->getSourceRange();
3979    break;
3980
3981  case FK_RValueReferenceBindingToLValue:
3982    S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3983      << Args[0]->getSourceRange();
3984    break;
3985
3986  case FK_ReferenceInitDropsQualifiers:
3987    S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3988      << DestType.getNonReferenceType()
3989      << Args[0]->getType()
3990      << Args[0]->getSourceRange();
3991    break;
3992
3993  case FK_ReferenceInitFailed:
3994    S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3995      << DestType.getNonReferenceType()
3996      << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3997      << Args[0]->getType()
3998      << Args[0]->getSourceRange();
3999    break;
4000
4001  case FK_ConversionFailed:
4002    S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4003      << (int)Entity.getKind()
4004      << DestType
4005      << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
4006      << Args[0]->getType()
4007      << Args[0]->getSourceRange();
4008    break;
4009
4010  case FK_TooManyInitsForScalar: {
4011    SourceRange R;
4012
4013    if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
4014      R = SourceRange(InitList->getInit(1)->getLocStart(),
4015                      InitList->getLocEnd());
4016    else
4017      R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
4018
4019    S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4020      << /*scalar=*/2 << R;
4021    break;
4022  }
4023
4024  case FK_ReferenceBindingToInitList:
4025    S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4026      << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4027    break;
4028
4029  case FK_InitListBadDestinationType:
4030    S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4031      << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4032    break;
4033
4034  case FK_ConstructorOverloadFailed: {
4035    SourceRange ArgsRange;
4036    if (NumArgs)
4037      ArgsRange = SourceRange(Args[0]->getLocStart(),
4038                              Args[NumArgs - 1]->getLocEnd());
4039
4040    // FIXME: Using "DestType" for the entity we're printing is probably
4041    // bad.
4042    switch (FailedOverloadResult) {
4043      case OR_Ambiguous:
4044        S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4045          << DestType << ArgsRange;
4046        S.PrintOverloadCandidates(FailedCandidateSet,
4047                                  Sema::OCD_ViableCandidates, Args, NumArgs);
4048        break;
4049
4050      case OR_No_Viable_Function:
4051        if (Kind.getKind() == InitializationKind::IK_Default &&
4052            (Entity.getKind() == InitializedEntity::EK_Base ||
4053             Entity.getKind() == InitializedEntity::EK_Member) &&
4054            isa<CXXConstructorDecl>(S.CurContext)) {
4055          // This is implicit default initialization of a member or
4056          // base within a constructor. If no viable function was
4057          // found, notify the user that she needs to explicitly
4058          // initialize this base/member.
4059          CXXConstructorDecl *Constructor
4060            = cast<CXXConstructorDecl>(S.CurContext);
4061          if (Entity.getKind() == InitializedEntity::EK_Base) {
4062            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4063              << Constructor->isImplicit()
4064              << S.Context.getTypeDeclType(Constructor->getParent())
4065              << /*base=*/0
4066              << Entity.getType();
4067
4068            RecordDecl *BaseDecl
4069              = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4070                                                                  ->getDecl();
4071            S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4072              << S.Context.getTagDeclType(BaseDecl);
4073          } else {
4074            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4075              << Constructor->isImplicit()
4076              << S.Context.getTypeDeclType(Constructor->getParent())
4077              << /*member=*/1
4078              << Entity.getName();
4079            S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4080
4081            if (const RecordType *Record
4082                                 = Entity.getType()->getAs<RecordType>())
4083              S.Diag(Record->getDecl()->getLocation(),
4084                     diag::note_previous_decl)
4085                << S.Context.getTagDeclType(Record->getDecl());
4086          }
4087          break;
4088        }
4089
4090        S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4091          << DestType << ArgsRange;
4092        S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
4093                                  Args, NumArgs);
4094        break;
4095
4096      case OR_Deleted: {
4097        S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4098          << true << DestType << ArgsRange;
4099        OverloadCandidateSet::iterator Best;
4100        OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
4101                                                     Kind.getLocation(),
4102                                                     Best);
4103        if (Ovl == OR_Deleted) {
4104          S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4105            << Best->Function->isDeleted();
4106        } else {
4107          llvm_unreachable("Inconsistent overload resolution?");
4108        }
4109        break;
4110      }
4111
4112      case OR_Success:
4113        llvm_unreachable("Conversion did not fail!");
4114        break;
4115    }
4116    break;
4117  }
4118
4119  case FK_DefaultInitOfConst:
4120    if (Entity.getKind() == InitializedEntity::EK_Member &&
4121        isa<CXXConstructorDecl>(S.CurContext)) {
4122      // This is implicit default-initialization of a const member in
4123      // a constructor. Complain that it needs to be explicitly
4124      // initialized.
4125      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4126      S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4127        << Constructor->isImplicit()
4128        << S.Context.getTypeDeclType(Constructor->getParent())
4129        << /*const=*/1
4130        << Entity.getName();
4131      S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4132        << Entity.getName();
4133    } else {
4134      S.Diag(Kind.getLocation(), diag::err_default_init_const)
4135        << DestType << (bool)DestType->getAs<RecordType>();
4136    }
4137    break;
4138
4139    case FK_Incomplete:
4140      S.RequireCompleteType(Kind.getLocation(), DestType,
4141                            diag::err_init_incomplete_type);
4142      break;
4143  }
4144
4145  PrintInitLocationNote(S, Entity);
4146  return true;
4147}
4148
4149void InitializationSequence::dump(llvm::raw_ostream &OS) const {
4150  switch (SequenceKind) {
4151  case FailedSequence: {
4152    OS << "Failed sequence: ";
4153    switch (Failure) {
4154    case FK_TooManyInitsForReference:
4155      OS << "too many initializers for reference";
4156      break;
4157
4158    case FK_ArrayNeedsInitList:
4159      OS << "array requires initializer list";
4160      break;
4161
4162    case FK_ArrayNeedsInitListOrStringLiteral:
4163      OS << "array requires initializer list or string literal";
4164      break;
4165
4166    case FK_AddressOfOverloadFailed:
4167      OS << "address of overloaded function failed";
4168      break;
4169
4170    case FK_ReferenceInitOverloadFailed:
4171      OS << "overload resolution for reference initialization failed";
4172      break;
4173
4174    case FK_NonConstLValueReferenceBindingToTemporary:
4175      OS << "non-const lvalue reference bound to temporary";
4176      break;
4177
4178    case FK_NonConstLValueReferenceBindingToUnrelated:
4179      OS << "non-const lvalue reference bound to unrelated type";
4180      break;
4181
4182    case FK_RValueReferenceBindingToLValue:
4183      OS << "rvalue reference bound to an lvalue";
4184      break;
4185
4186    case FK_ReferenceInitDropsQualifiers:
4187      OS << "reference initialization drops qualifiers";
4188      break;
4189
4190    case FK_ReferenceInitFailed:
4191      OS << "reference initialization failed";
4192      break;
4193
4194    case FK_ConversionFailed:
4195      OS << "conversion failed";
4196      break;
4197
4198    case FK_TooManyInitsForScalar:
4199      OS << "too many initializers for scalar";
4200      break;
4201
4202    case FK_ReferenceBindingToInitList:
4203      OS << "referencing binding to initializer list";
4204      break;
4205
4206    case FK_InitListBadDestinationType:
4207      OS << "initializer list for non-aggregate, non-scalar type";
4208      break;
4209
4210    case FK_UserConversionOverloadFailed:
4211      OS << "overloading failed for user-defined conversion";
4212      break;
4213
4214    case FK_ConstructorOverloadFailed:
4215      OS << "constructor overloading failed";
4216      break;
4217
4218    case FK_DefaultInitOfConst:
4219      OS << "default initialization of a const variable";
4220      break;
4221
4222    case FK_Incomplete:
4223      OS << "initialization of incomplete type";
4224      break;
4225    }
4226    OS << '\n';
4227    return;
4228  }
4229
4230  case DependentSequence:
4231    OS << "Dependent sequence: ";
4232    return;
4233
4234  case UserDefinedConversion:
4235    OS << "User-defined conversion sequence: ";
4236    break;
4237
4238  case ConstructorInitialization:
4239    OS << "Constructor initialization sequence: ";
4240    break;
4241
4242  case ReferenceBinding:
4243    OS << "Reference binding: ";
4244    break;
4245
4246  case ListInitialization:
4247    OS << "List initialization: ";
4248    break;
4249
4250  case ZeroInitialization:
4251    OS << "Zero initialization\n";
4252    return;
4253
4254  case NoInitialization:
4255    OS << "No initialization\n";
4256    return;
4257
4258  case StandardConversion:
4259    OS << "Standard conversion: ";
4260    break;
4261
4262  case CAssignment:
4263    OS << "C assignment: ";
4264    break;
4265
4266  case StringInit:
4267    OS << "String initialization: ";
4268    break;
4269  }
4270
4271  for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
4272    if (S != step_begin()) {
4273      OS << " -> ";
4274    }
4275
4276    switch (S->Kind) {
4277    case SK_ResolveAddressOfOverloadedFunction:
4278      OS << "resolve address of overloaded function";
4279      break;
4280
4281    case SK_CastDerivedToBaseRValue:
4282      OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
4283      break;
4284
4285    case SK_CastDerivedToBaseLValue:
4286      OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
4287      break;
4288
4289    case SK_BindReference:
4290      OS << "bind reference to lvalue";
4291      break;
4292
4293    case SK_BindReferenceToTemporary:
4294      OS << "bind reference to a temporary";
4295      break;
4296
4297    case SK_ExtraneousCopyToTemporary:
4298      OS << "extraneous C++03 copy to temporary";
4299      break;
4300
4301    case SK_UserConversion:
4302      OS << "user-defined conversion via " << S->Function.Function;
4303      break;
4304
4305    case SK_QualificationConversionRValue:
4306      OS << "qualification conversion (rvalue)";
4307
4308    case SK_QualificationConversionLValue:
4309      OS << "qualification conversion (lvalue)";
4310      break;
4311
4312    case SK_ConversionSequence:
4313      OS << "implicit conversion sequence (";
4314      S->ICS->DebugPrint(); // FIXME: use OS
4315      OS << ")";
4316      break;
4317
4318    case SK_ListInitialization:
4319      OS << "list initialization";
4320      break;
4321
4322    case SK_ConstructorInitialization:
4323      OS << "constructor initialization";
4324      break;
4325
4326    case SK_ZeroInitialization:
4327      OS << "zero initialization";
4328      break;
4329
4330    case SK_CAssignment:
4331      OS << "C assignment";
4332      break;
4333
4334    case SK_StringInit:
4335      OS << "string initialization";
4336      break;
4337    }
4338  }
4339}
4340
4341void InitializationSequence::dump() const {
4342  dump(llvm::errs());
4343}
4344
4345//===----------------------------------------------------------------------===//
4346// Initialization helper functions
4347//===----------------------------------------------------------------------===//
4348Sema::OwningExprResult
4349Sema::PerformCopyInitialization(const InitializedEntity &Entity,
4350                                SourceLocation EqualLoc,
4351                                OwningExprResult Init) {
4352  if (Init.isInvalid())
4353    return ExprError();
4354
4355  Expr *InitE = (Expr *)Init.get();
4356  assert(InitE && "No initialization expression?");
4357
4358  if (EqualLoc.isInvalid())
4359    EqualLoc = InitE->getLocStart();
4360
4361  InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
4362                                                           EqualLoc);
4363  InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
4364  Init.release();
4365  return Seq.Perform(*this, Entity, Kind,
4366                     MultiExprArg(*this, (void**)&InitE, 1));
4367}
4368