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