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