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