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