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