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