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