SemaInit.cpp revision 867521c64254727a37bc9e50fa1045ef3c3b647d
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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Initialization.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Sema/Designator.h"
22#include "clang/Sema/Lookup.h"
23#include "clang/Sema/SemaInternal.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28#include <map>
29using namespace clang;
30
31//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
35/// \brief Check whether T is compatible with a wide character type (wchar_t,
36/// char16_t or char32_t).
37static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
38  if (Context.typesAreCompatible(Context.getWideCharType(), T))
39    return true;
40  if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) {
41    return Context.typesAreCompatible(Context.Char16Ty, T) ||
42           Context.typesAreCompatible(Context.Char32Ty, T);
43  }
44  return false;
45}
46
47enum StringInitFailureKind {
48  SIF_None,
49  SIF_NarrowStringIntoWideChar,
50  SIF_WideStringIntoChar,
51  SIF_IncompatWideStringIntoWideChar,
52  SIF_Other
53};
54
55/// \brief Check whether the array of type AT can be initialized by the Init
56/// expression by means of string initialization. Returns SIF_None if so,
57/// otherwise returns a StringInitFailureKind that describes why the
58/// initialization would not work.
59static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
60                                          ASTContext &Context) {
61  if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
62    return SIF_Other;
63
64  // See if this is a string literal or @encode.
65  Init = Init->IgnoreParens();
66
67  // Handle @encode, which is a narrow string.
68  if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
69    return SIF_None;
70
71  // Otherwise we can only handle string literals.
72  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
73  if (SL == 0)
74    return SIF_Other;
75
76  const QualType ElemTy =
77      Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
78
79  switch (SL->getKind()) {
80  case StringLiteral::Ascii:
81  case StringLiteral::UTF8:
82    // char array can be initialized with a narrow string.
83    // Only allow char x[] = "foo";  not char x[] = L"foo";
84    if (ElemTy->isCharType())
85      return SIF_None;
86    if (IsWideCharCompatible(ElemTy, Context))
87      return SIF_NarrowStringIntoWideChar;
88    return SIF_Other;
89  // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
90  // "An array with element type compatible with a qualified or unqualified
91  // version of wchar_t, char16_t, or char32_t may be initialized by a wide
92  // string literal with the corresponding encoding prefix (L, u, or U,
93  // respectively), optionally enclosed in braces.
94  case StringLiteral::UTF16:
95    if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
96      return SIF_None;
97    if (ElemTy->isCharType())
98      return SIF_WideStringIntoChar;
99    if (IsWideCharCompatible(ElemTy, Context))
100      return SIF_IncompatWideStringIntoWideChar;
101    return SIF_Other;
102  case StringLiteral::UTF32:
103    if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
104      return SIF_None;
105    if (ElemTy->isCharType())
106      return SIF_WideStringIntoChar;
107    if (IsWideCharCompatible(ElemTy, Context))
108      return SIF_IncompatWideStringIntoWideChar;
109    return SIF_Other;
110  case StringLiteral::Wide:
111    if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
112      return SIF_None;
113    if (ElemTy->isCharType())
114      return SIF_WideStringIntoChar;
115    if (IsWideCharCompatible(ElemTy, Context))
116      return SIF_IncompatWideStringIntoWideChar;
117    return SIF_Other;
118  }
119
120  llvm_unreachable("missed a StringLiteral kind?");
121}
122
123static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
124                                          ASTContext &Context) {
125  const ArrayType *arrayType = Context.getAsArrayType(declType);
126  if (!arrayType)
127    return SIF_Other;
128  return IsStringInit(init, arrayType, Context);
129}
130
131/// Update the type of a string literal, including any surrounding parentheses,
132/// to match the type of the object which it is initializing.
133static void updateStringLiteralType(Expr *E, QualType Ty) {
134  while (true) {
135    E->setType(Ty);
136    if (isa<StringLiteral>(E) || isa<ObjCEncodeExpr>(E))
137      break;
138    else if (ParenExpr *PE = dyn_cast<ParenExpr>(E))
139      E = PE->getSubExpr();
140    else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
141      E = UO->getSubExpr();
142    else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E))
143      E = GSE->getResultExpr();
144    else
145      llvm_unreachable("unexpected expr in string literal init");
146  }
147}
148
149static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
150                            Sema &S) {
151  // Get the length of the string as parsed.
152  uint64_t StrLength =
153    cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
154
155
156  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
157    // C99 6.7.8p14. We have an array of character type with unknown size
158    // being initialized to a string literal.
159    llvm::APInt ConstVal(32, StrLength);
160    // Return a new array type (C99 6.7.8p22).
161    DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
162                                           ConstVal,
163                                           ArrayType::Normal, 0);
164    updateStringLiteralType(Str, DeclT);
165    return;
166  }
167
168  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
169
170  // We have an array of character type with known size.  However,
171  // the size may be smaller or larger than the string we are initializing.
172  // FIXME: Avoid truncation for 64-bit length strings.
173  if (S.getLangOpts().CPlusPlus) {
174    if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
175      // For Pascal strings it's OK to strip off the terminating null character,
176      // so the example below is valid:
177      //
178      // unsigned char a[2] = "\pa";
179      if (SL->isPascal())
180        StrLength--;
181    }
182
183    // [dcl.init.string]p2
184    if (StrLength > CAT->getSize().getZExtValue())
185      S.Diag(Str->getLocStart(),
186             diag::err_initializer_string_for_char_array_too_long)
187        << Str->getSourceRange();
188  } else {
189    // C99 6.7.8p14.
190    if (StrLength-1 > CAT->getSize().getZExtValue())
191      S.Diag(Str->getLocStart(),
192             diag::warn_initializer_string_for_char_array_too_long)
193        << Str->getSourceRange();
194  }
195
196  // Set the type to the actual size that we are initializing.  If we have
197  // something like:
198  //   char x[1] = "foo";
199  // then this will set the string literal's type to char[1].
200  updateStringLiteralType(Str, DeclT);
201}
202
203//===----------------------------------------------------------------------===//
204// Semantic checking for initializer lists.
205//===----------------------------------------------------------------------===//
206
207/// @brief Semantic checking for initializer lists.
208///
209/// The InitListChecker class contains a set of routines that each
210/// handle the initialization of a certain kind of entity, e.g.,
211/// arrays, vectors, struct/union types, scalars, etc. The
212/// InitListChecker itself performs a recursive walk of the subobject
213/// structure of the type to be initialized, while stepping through
214/// the initializer list one element at a time. The IList and Index
215/// parameters to each of the Check* routines contain the active
216/// (syntactic) initializer list and the index into that initializer
217/// list that represents the current initializer. Each routine is
218/// responsible for moving that Index forward as it consumes elements.
219///
220/// Each Check* routine also has a StructuredList/StructuredIndex
221/// arguments, which contains the current "structured" (semantic)
222/// initializer list and the index into that initializer list where we
223/// are copying initializers as we map them over to the semantic
224/// list. Once we have completed our recursive walk of the subobject
225/// structure, we will have constructed a full semantic initializer
226/// list.
227///
228/// C99 designators cause changes in the initializer list traversal,
229/// because they make the initialization "jump" into a specific
230/// subobject and then continue the initialization from that
231/// point. CheckDesignatedInitializer() recursively steps into the
232/// designated subobject and manages backing out the recursion to
233/// initialize the subobjects after the one designated.
234namespace {
235class InitListChecker {
236  Sema &SemaRef;
237  bool hadError;
238  bool VerifyOnly; // no diagnostics, no structure building
239  llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
240  InitListExpr *FullyStructuredList;
241
242  void CheckImplicitInitList(const InitializedEntity &Entity,
243                             InitListExpr *ParentIList, QualType T,
244                             unsigned &Index, InitListExpr *StructuredList,
245                             unsigned &StructuredIndex);
246  void CheckExplicitInitList(const InitializedEntity &Entity,
247                             InitListExpr *IList, QualType &T,
248                             InitListExpr *StructuredList,
249                             bool TopLevelObject = false);
250  void CheckListElementTypes(const InitializedEntity &Entity,
251                             InitListExpr *IList, QualType &DeclType,
252                             bool SubobjectIsDesignatorContext,
253                             unsigned &Index,
254                             InitListExpr *StructuredList,
255                             unsigned &StructuredIndex,
256                             bool TopLevelObject = false);
257  void CheckSubElementType(const InitializedEntity &Entity,
258                           InitListExpr *IList, QualType ElemType,
259                           unsigned &Index,
260                           InitListExpr *StructuredList,
261                           unsigned &StructuredIndex);
262  void CheckComplexType(const InitializedEntity &Entity,
263                        InitListExpr *IList, QualType DeclType,
264                        unsigned &Index,
265                        InitListExpr *StructuredList,
266                        unsigned &StructuredIndex);
267  void CheckScalarType(const InitializedEntity &Entity,
268                       InitListExpr *IList, QualType DeclType,
269                       unsigned &Index,
270                       InitListExpr *StructuredList,
271                       unsigned &StructuredIndex);
272  void CheckReferenceType(const InitializedEntity &Entity,
273                          InitListExpr *IList, QualType DeclType,
274                          unsigned &Index,
275                          InitListExpr *StructuredList,
276                          unsigned &StructuredIndex);
277  void CheckVectorType(const InitializedEntity &Entity,
278                       InitListExpr *IList, QualType DeclType, unsigned &Index,
279                       InitListExpr *StructuredList,
280                       unsigned &StructuredIndex);
281  void CheckStructUnionTypes(const InitializedEntity &Entity,
282                             InitListExpr *IList, QualType DeclType,
283                             RecordDecl::field_iterator Field,
284                             bool SubobjectIsDesignatorContext, unsigned &Index,
285                             InitListExpr *StructuredList,
286                             unsigned &StructuredIndex,
287                             bool TopLevelObject = false);
288  void CheckArrayType(const InitializedEntity &Entity,
289                      InitListExpr *IList, QualType &DeclType,
290                      llvm::APSInt elementIndex,
291                      bool SubobjectIsDesignatorContext, unsigned &Index,
292                      InitListExpr *StructuredList,
293                      unsigned &StructuredIndex);
294  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
295                                  InitListExpr *IList, DesignatedInitExpr *DIE,
296                                  unsigned DesigIdx,
297                                  QualType &CurrentObjectType,
298                                  RecordDecl::field_iterator *NextField,
299                                  llvm::APSInt *NextElementIndex,
300                                  unsigned &Index,
301                                  InitListExpr *StructuredList,
302                                  unsigned &StructuredIndex,
303                                  bool FinishSubobjectInit,
304                                  bool TopLevelObject);
305  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
306                                           QualType CurrentObjectType,
307                                           InitListExpr *StructuredList,
308                                           unsigned StructuredIndex,
309                                           SourceRange InitRange);
310  void UpdateStructuredListElement(InitListExpr *StructuredList,
311                                   unsigned &StructuredIndex,
312                                   Expr *expr);
313  int numArrayElements(QualType DeclType);
314  int numStructUnionElements(QualType DeclType);
315
316  void FillInValueInitForField(unsigned Init, FieldDecl *Field,
317                               const InitializedEntity &ParentEntity,
318                               InitListExpr *ILE, bool &RequiresSecondPass);
319  void FillInValueInitializations(const InitializedEntity &Entity,
320                                  InitListExpr *ILE, bool &RequiresSecondPass);
321  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
322                              Expr *InitExpr, FieldDecl *Field,
323                              bool TopLevelObject);
324  void CheckValueInitializable(const InitializedEntity &Entity);
325
326public:
327  InitListChecker(Sema &S, const InitializedEntity &Entity,
328                  InitListExpr *IL, QualType &T, bool VerifyOnly);
329  bool HadError() { return hadError; }
330
331  // @brief Retrieves the fully-structured initializer list used for
332  // semantic analysis and code generation.
333  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
334};
335} // end anonymous namespace
336
337void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
338  assert(VerifyOnly &&
339         "CheckValueInitializable is only inteded for verification mode.");
340
341  SourceLocation Loc;
342  InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
343                                                            true);
344  InitializationSequence InitSeq(SemaRef, Entity, Kind, None);
345  if (InitSeq.Failed())
346    hadError = true;
347}
348
349void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
350                                        const InitializedEntity &ParentEntity,
351                                              InitListExpr *ILE,
352                                              bool &RequiresSecondPass) {
353  SourceLocation Loc = ILE->getLocStart();
354  unsigned NumInits = ILE->getNumInits();
355  InitializedEntity MemberEntity
356    = InitializedEntity::InitializeMember(Field, &ParentEntity);
357  if (Init >= NumInits || !ILE->getInit(Init)) {
358    // If there's no explicit initializer but we have a default initializer, use
359    // that. This only happens in C++1y, since classes with default
360    // initializers are not aggregates in C++11.
361    if (Field->hasInClassInitializer()) {
362      Expr *DIE = CXXDefaultInitExpr::Create(SemaRef.Context,
363                                             ILE->getRBraceLoc(), Field);
364      if (Init < NumInits)
365        ILE->setInit(Init, DIE);
366      else {
367        ILE->updateInit(SemaRef.Context, Init, DIE);
368        RequiresSecondPass = true;
369      }
370      return;
371    }
372
373    // FIXME: We probably don't need to handle references
374    // specially here, since value-initialization of references is
375    // handled in InitializationSequence.
376    if (Field->getType()->isReferenceType()) {
377      // C++ [dcl.init.aggr]p9:
378      //   If an incomplete or empty initializer-list leaves a
379      //   member of reference type uninitialized, the program is
380      //   ill-formed.
381      SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
382        << Field->getType()
383        << ILE->getSyntacticForm()->getSourceRange();
384      SemaRef.Diag(Field->getLocation(),
385                   diag::note_uninit_reference_member);
386      hadError = true;
387      return;
388    }
389
390    InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
391                                                              true);
392    InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, None);
393    if (!InitSeq) {
394      InitSeq.Diagnose(SemaRef, MemberEntity, Kind, None);
395      hadError = true;
396      return;
397    }
398
399    ExprResult MemberInit
400      = InitSeq.Perform(SemaRef, MemberEntity, Kind, None);
401    if (MemberInit.isInvalid()) {
402      hadError = true;
403      return;
404    }
405
406    if (hadError) {
407      // Do nothing
408    } else if (Init < NumInits) {
409      ILE->setInit(Init, MemberInit.takeAs<Expr>());
410    } else if (InitSeq.isConstructorInitialization()) {
411      // Value-initialization requires a constructor call, so
412      // extend the initializer list to include the constructor
413      // call and make a note that we'll need to take another pass
414      // through the initializer list.
415      ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
416      RequiresSecondPass = true;
417    }
418  } else if (InitListExpr *InnerILE
419               = dyn_cast<InitListExpr>(ILE->getInit(Init)))
420    FillInValueInitializations(MemberEntity, InnerILE,
421                               RequiresSecondPass);
422}
423
424/// Recursively replaces NULL values within the given initializer list
425/// with expressions that perform value-initialization of the
426/// appropriate type.
427void
428InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
429                                            InitListExpr *ILE,
430                                            bool &RequiresSecondPass) {
431  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
432         "Should not have void type");
433  SourceLocation Loc = ILE->getLocStart();
434  if (ILE->getSyntacticForm())
435    Loc = ILE->getSyntacticForm()->getLocStart();
436
437  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
438    const RecordDecl *RDecl = RType->getDecl();
439    if (RDecl->isUnion() && ILE->getInitializedFieldInUnion())
440      FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
441                              Entity, ILE, RequiresSecondPass);
442    else if (RDecl->isUnion() && isa<CXXRecordDecl>(RDecl) &&
443             cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) {
444      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
445                                      FieldEnd = RDecl->field_end();
446           Field != FieldEnd; ++Field) {
447        if (Field->hasInClassInitializer()) {
448          FillInValueInitForField(0, *Field, Entity, ILE, RequiresSecondPass);
449          break;
450        }
451      }
452    } else {
453      unsigned Init = 0;
454      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
455                                      FieldEnd = RDecl->field_end();
456           Field != FieldEnd; ++Field) {
457        if (Field->isUnnamedBitfield())
458          continue;
459
460        if (hadError)
461          return;
462
463        FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
464        if (hadError)
465          return;
466
467        ++Init;
468
469        // Only look at the first initialization of a union.
470        if (RDecl->isUnion())
471          break;
472      }
473    }
474
475    return;
476  }
477
478  QualType ElementType;
479
480  InitializedEntity ElementEntity = Entity;
481  unsigned NumInits = ILE->getNumInits();
482  unsigned NumElements = NumInits;
483  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
484    ElementType = AType->getElementType();
485    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
486      NumElements = CAType->getSize().getZExtValue();
487    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
488                                                         0, Entity);
489  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
490    ElementType = VType->getElementType();
491    NumElements = VType->getNumElements();
492    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
493                                                         0, Entity);
494  } else
495    ElementType = ILE->getType();
496
497
498  for (unsigned Init = 0; Init != NumElements; ++Init) {
499    if (hadError)
500      return;
501
502    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
503        ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
504      ElementEntity.setElementIndex(Init);
505
506    Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
507    if (!InitExpr && !ILE->hasArrayFiller()) {
508      InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
509                                                                true);
510      InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, None);
511      if (!InitSeq) {
512        InitSeq.Diagnose(SemaRef, ElementEntity, Kind, None);
513        hadError = true;
514        return;
515      }
516
517      ExprResult ElementInit
518        = InitSeq.Perform(SemaRef, ElementEntity, Kind, None);
519      if (ElementInit.isInvalid()) {
520        hadError = true;
521        return;
522      }
523
524      if (hadError) {
525        // Do nothing
526      } else if (Init < NumInits) {
527        // For arrays, just set the expression used for value-initialization
528        // of the "holes" in the array.
529        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
530          ILE->setArrayFiller(ElementInit.takeAs<Expr>());
531        else
532          ILE->setInit(Init, ElementInit.takeAs<Expr>());
533      } else {
534        // For arrays, just set the expression used for value-initialization
535        // of the rest of elements and exit.
536        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
537          ILE->setArrayFiller(ElementInit.takeAs<Expr>());
538          return;
539        }
540
541        if (InitSeq.isConstructorInitialization()) {
542          // Value-initialization requires a constructor call, so
543          // extend the initializer list to include the constructor
544          // call and make a note that we'll need to take another pass
545          // through the initializer list.
546          ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
547          RequiresSecondPass = true;
548        }
549      }
550    } else if (InitListExpr *InnerILE
551                 = dyn_cast_or_null<InitListExpr>(InitExpr))
552      FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
553  }
554}
555
556
557InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
558                                 InitListExpr *IL, QualType &T,
559                                 bool VerifyOnly)
560  : SemaRef(S), VerifyOnly(VerifyOnly) {
561  hadError = false;
562
563  FullyStructuredList =
564      getStructuredSubobjectInit(IL, 0, T, 0, 0, IL->getSourceRange());
565  CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
566                        /*TopLevelObject=*/true);
567
568  if (!hadError && !VerifyOnly) {
569    bool RequiresSecondPass = false;
570    FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
571    if (RequiresSecondPass && !hadError)
572      FillInValueInitializations(Entity, FullyStructuredList,
573                                 RequiresSecondPass);
574  }
575}
576
577int InitListChecker::numArrayElements(QualType DeclType) {
578  // FIXME: use a proper constant
579  int maxElements = 0x7FFFFFFF;
580  if (const ConstantArrayType *CAT =
581        SemaRef.Context.getAsConstantArrayType(DeclType)) {
582    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
583  }
584  return maxElements;
585}
586
587int InitListChecker::numStructUnionElements(QualType DeclType) {
588  RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
589  int InitializableMembers = 0;
590  for (RecordDecl::field_iterator
591         Field = structDecl->field_begin(),
592         FieldEnd = structDecl->field_end();
593       Field != FieldEnd; ++Field) {
594    if (!Field->isUnnamedBitfield())
595      ++InitializableMembers;
596  }
597  if (structDecl->isUnion())
598    return std::min(InitializableMembers, 1);
599  return InitializableMembers - structDecl->hasFlexibleArrayMember();
600}
601
602/// Check whether the range of the initializer \p ParentIList from element
603/// \p Index onwards can be used to initialize an object of type \p T. Update
604/// \p Index to indicate how many elements of the list were consumed.
605///
606/// This also fills in \p StructuredList, from element \p StructuredIndex
607/// onwards, with the fully-braced, desugared form of the initialization.
608void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
609                                            InitListExpr *ParentIList,
610                                            QualType T, unsigned &Index,
611                                            InitListExpr *StructuredList,
612                                            unsigned &StructuredIndex) {
613  int maxElements = 0;
614
615  if (T->isArrayType())
616    maxElements = numArrayElements(T);
617  else if (T->isRecordType())
618    maxElements = numStructUnionElements(T);
619  else if (T->isVectorType())
620    maxElements = T->getAs<VectorType>()->getNumElements();
621  else
622    llvm_unreachable("CheckImplicitInitList(): Illegal type");
623
624  if (maxElements == 0) {
625    if (!VerifyOnly)
626      SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
627                   diag::err_implicit_empty_initializer);
628    ++Index;
629    hadError = true;
630    return;
631  }
632
633  // Build a structured initializer list corresponding to this subobject.
634  InitListExpr *StructuredSubobjectInitList
635    = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
636                                 StructuredIndex,
637          SourceRange(ParentIList->getInit(Index)->getLocStart(),
638                      ParentIList->getSourceRange().getEnd()));
639  unsigned StructuredSubobjectInitIndex = 0;
640
641  // Check the element types and build the structural subobject.
642  unsigned StartIndex = Index;
643  CheckListElementTypes(Entity, ParentIList, T,
644                        /*SubobjectIsDesignatorContext=*/false, Index,
645                        StructuredSubobjectInitList,
646                        StructuredSubobjectInitIndex);
647
648  if (!VerifyOnly) {
649    StructuredSubobjectInitList->setType(T);
650
651    unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
652    // Update the structured sub-object initializer so that it's ending
653    // range corresponds with the end of the last initializer it used.
654    if (EndIndex < ParentIList->getNumInits()) {
655      SourceLocation EndLoc
656        = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
657      StructuredSubobjectInitList->setRBraceLoc(EndLoc);
658    }
659
660    // Complain about missing braces.
661    if (T->isArrayType() || T->isRecordType()) {
662      SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
663                   diag::warn_missing_braces)
664        << StructuredSubobjectInitList->getSourceRange()
665        << FixItHint::CreateInsertion(
666              StructuredSubobjectInitList->getLocStart(), "{")
667        << FixItHint::CreateInsertion(
668              SemaRef.PP.getLocForEndOfToken(
669                                      StructuredSubobjectInitList->getLocEnd()),
670              "}");
671    }
672  }
673}
674
675/// Check whether the initializer \p IList (that was written with explicit
676/// braces) can be used to initialize an object of type \p T.
677///
678/// This also fills in \p StructuredList with the fully-braced, desugared
679/// form of the initialization.
680void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
681                                            InitListExpr *IList, QualType &T,
682                                            InitListExpr *StructuredList,
683                                            bool TopLevelObject) {
684  assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
685  if (!VerifyOnly) {
686    SyntacticToSemantic[IList] = StructuredList;
687    StructuredList->setSyntacticForm(IList);
688  }
689
690  unsigned Index = 0, StructuredIndex = 0;
691  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
692                        Index, StructuredList, StructuredIndex, TopLevelObject);
693  if (!VerifyOnly) {
694    QualType ExprTy = T;
695    if (!ExprTy->isArrayType())
696      ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
697    IList->setType(ExprTy);
698    StructuredList->setType(ExprTy);
699  }
700  if (hadError)
701    return;
702
703  if (Index < IList->getNumInits()) {
704    // We have leftover initializers
705    if (VerifyOnly) {
706      if (SemaRef.getLangOpts().CPlusPlus ||
707          (SemaRef.getLangOpts().OpenCL &&
708           IList->getType()->isVectorType())) {
709        hadError = true;
710      }
711      return;
712    }
713
714    if (StructuredIndex == 1 &&
715        IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
716            SIF_None) {
717      unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
718      if (SemaRef.getLangOpts().CPlusPlus) {
719        DK = diag::err_excess_initializers_in_char_array_initializer;
720        hadError = true;
721      }
722      // Special-case
723      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
724        << IList->getInit(Index)->getSourceRange();
725    } else if (!T->isIncompleteType()) {
726      // Don't complain for incomplete types, since we'll get an error
727      // elsewhere
728      QualType CurrentObjectType = StructuredList->getType();
729      int initKind =
730        CurrentObjectType->isArrayType()? 0 :
731        CurrentObjectType->isVectorType()? 1 :
732        CurrentObjectType->isScalarType()? 2 :
733        CurrentObjectType->isUnionType()? 3 :
734        4;
735
736      unsigned DK = diag::warn_excess_initializers;
737      if (SemaRef.getLangOpts().CPlusPlus) {
738        DK = diag::err_excess_initializers;
739        hadError = true;
740      }
741      if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
742        DK = diag::err_excess_initializers;
743        hadError = true;
744      }
745
746      SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
747        << initKind << IList->getInit(Index)->getSourceRange();
748    }
749  }
750
751  if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
752      !TopLevelObject)
753    SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
754      << IList->getSourceRange()
755      << FixItHint::CreateRemoval(IList->getLocStart())
756      << FixItHint::CreateRemoval(IList->getLocEnd());
757}
758
759void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
760                                            InitListExpr *IList,
761                                            QualType &DeclType,
762                                            bool SubobjectIsDesignatorContext,
763                                            unsigned &Index,
764                                            InitListExpr *StructuredList,
765                                            unsigned &StructuredIndex,
766                                            bool TopLevelObject) {
767  if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
768    // Explicitly braced initializer for complex type can be real+imaginary
769    // parts.
770    CheckComplexType(Entity, IList, DeclType, Index,
771                     StructuredList, StructuredIndex);
772  } else if (DeclType->isScalarType()) {
773    CheckScalarType(Entity, IList, DeclType, Index,
774                    StructuredList, StructuredIndex);
775  } else if (DeclType->isVectorType()) {
776    CheckVectorType(Entity, IList, DeclType, Index,
777                    StructuredList, StructuredIndex);
778  } else if (DeclType->isRecordType()) {
779    assert(DeclType->isAggregateType() &&
780           "non-aggregate records should be handed in CheckSubElementType");
781    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
782    CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
783                          SubobjectIsDesignatorContext, Index,
784                          StructuredList, StructuredIndex,
785                          TopLevelObject);
786  } else if (DeclType->isArrayType()) {
787    llvm::APSInt Zero(
788                    SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
789                    false);
790    CheckArrayType(Entity, IList, DeclType, Zero,
791                   SubobjectIsDesignatorContext, Index,
792                   StructuredList, StructuredIndex);
793  } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
794    // This type is invalid, issue a diagnostic.
795    ++Index;
796    if (!VerifyOnly)
797      SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
798        << DeclType;
799    hadError = true;
800  } else if (DeclType->isReferenceType()) {
801    CheckReferenceType(Entity, IList, DeclType, Index,
802                       StructuredList, StructuredIndex);
803  } else if (DeclType->isObjCObjectType()) {
804    if (!VerifyOnly)
805      SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
806        << DeclType;
807    hadError = true;
808  } else {
809    if (!VerifyOnly)
810      SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
811        << DeclType;
812    hadError = true;
813  }
814}
815
816void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
817                                          InitListExpr *IList,
818                                          QualType ElemType,
819                                          unsigned &Index,
820                                          InitListExpr *StructuredList,
821                                          unsigned &StructuredIndex) {
822  Expr *expr = IList->getInit(Index);
823
824  if (ElemType->isReferenceType())
825    return CheckReferenceType(Entity, IList, ElemType, Index,
826                              StructuredList, StructuredIndex);
827
828  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
829    if (!ElemType->isRecordType() || ElemType->isAggregateType()) {
830      InitListExpr *InnerStructuredList
831        = getStructuredSubobjectInit(IList, Index, ElemType,
832                                     StructuredList, StructuredIndex,
833                                     SubInitList->getSourceRange());
834      CheckExplicitInitList(Entity, SubInitList, ElemType,
835                            InnerStructuredList);
836      ++StructuredIndex;
837      ++Index;
838      return;
839    }
840    assert(SemaRef.getLangOpts().CPlusPlus &&
841           "non-aggregate records are only possible in C++");
842    // C++ initialization is handled later.
843  }
844
845  // FIXME: Need to handle atomic aggregate types with implicit init lists.
846  if (ElemType->isScalarType() || ElemType->isAtomicType())
847    return CheckScalarType(Entity, IList, ElemType, Index,
848                           StructuredList, StructuredIndex);
849
850  assert((ElemType->isRecordType() || ElemType->isVectorType() ||
851          ElemType->isArrayType()) && "Unexpected type");
852
853  if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
854    // arrayType can be incomplete if we're initializing a flexible
855    // array member.  There's nothing we can do with the completed
856    // type here, though.
857
858    if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
859      if (!VerifyOnly) {
860        CheckStringInit(expr, ElemType, arrayType, SemaRef);
861        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
862      }
863      ++Index;
864      return;
865    }
866
867    // Fall through for subaggregate initialization.
868
869  } else if (SemaRef.getLangOpts().CPlusPlus) {
870    // C++ [dcl.init.aggr]p12:
871    //   All implicit type conversions (clause 4) are considered when
872    //   initializing the aggregate member with an initializer from
873    //   an initializer-list. If the initializer can initialize a
874    //   member, the member is initialized. [...]
875
876    // FIXME: Better EqualLoc?
877    InitializationKind Kind =
878      InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
879    InitializationSequence Seq(SemaRef, Entity, Kind, expr);
880
881    if (Seq) {
882      if (!VerifyOnly) {
883        ExprResult Result =
884          Seq.Perform(SemaRef, Entity, Kind, expr);
885        if (Result.isInvalid())
886          hadError = true;
887
888        UpdateStructuredListElement(StructuredList, StructuredIndex,
889                                    Result.takeAs<Expr>());
890      }
891      ++Index;
892      return;
893    }
894
895    // Fall through for subaggregate initialization
896  } else {
897    // C99 6.7.8p13:
898    //
899    //   The initializer for a structure or union object that has
900    //   automatic storage duration shall be either an initializer
901    //   list as described below, or a single expression that has
902    //   compatible structure or union type. In the latter case, the
903    //   initial value of the object, including unnamed members, is
904    //   that of the expression.
905    ExprResult ExprRes = SemaRef.Owned(expr);
906    if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
907        SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
908                                                 !VerifyOnly)
909          != Sema::Incompatible) {
910      if (ExprRes.isInvalid())
911        hadError = true;
912      else {
913        ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
914          if (ExprRes.isInvalid())
915            hadError = true;
916      }
917      UpdateStructuredListElement(StructuredList, StructuredIndex,
918                                  ExprRes.takeAs<Expr>());
919      ++Index;
920      return;
921    }
922    ExprRes.release();
923    // Fall through for subaggregate initialization
924  }
925
926  // C++ [dcl.init.aggr]p12:
927  //
928  //   [...] Otherwise, if the member is itself a non-empty
929  //   subaggregate, brace elision is assumed and the initializer is
930  //   considered for the initialization of the first member of
931  //   the subaggregate.
932  if (!SemaRef.getLangOpts().OpenCL &&
933      (ElemType->isAggregateType() || ElemType->isVectorType())) {
934    CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
935                          StructuredIndex);
936    ++StructuredIndex;
937  } else {
938    if (!VerifyOnly) {
939      // We cannot initialize this element, so let
940      // PerformCopyInitialization produce the appropriate diagnostic.
941      SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
942                                        SemaRef.Owned(expr),
943                                        /*TopLevelOfInitList=*/true);
944    }
945    hadError = true;
946    ++Index;
947    ++StructuredIndex;
948  }
949}
950
951void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
952                                       InitListExpr *IList, QualType DeclType,
953                                       unsigned &Index,
954                                       InitListExpr *StructuredList,
955                                       unsigned &StructuredIndex) {
956  assert(Index == 0 && "Index in explicit init list must be zero");
957
958  // As an extension, clang supports complex initializers, which initialize
959  // a complex number component-wise.  When an explicit initializer list for
960  // a complex number contains two two initializers, this extension kicks in:
961  // it exepcts the initializer list to contain two elements convertible to
962  // the element type of the complex type. The first element initializes
963  // the real part, and the second element intitializes the imaginary part.
964
965  if (IList->getNumInits() != 2)
966    return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
967                           StructuredIndex);
968
969  // This is an extension in C.  (The builtin _Complex type does not exist
970  // in the C++ standard.)
971  if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
972    SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
973      << IList->getSourceRange();
974
975  // Initialize the complex number.
976  QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
977  InitializedEntity ElementEntity =
978    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
979
980  for (unsigned i = 0; i < 2; ++i) {
981    ElementEntity.setElementIndex(Index);
982    CheckSubElementType(ElementEntity, IList, elementType, Index,
983                        StructuredList, StructuredIndex);
984  }
985}
986
987
988void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
989                                      InitListExpr *IList, QualType DeclType,
990                                      unsigned &Index,
991                                      InitListExpr *StructuredList,
992                                      unsigned &StructuredIndex) {
993  if (Index >= IList->getNumInits()) {
994    if (!VerifyOnly)
995      SemaRef.Diag(IList->getLocStart(),
996                   SemaRef.getLangOpts().CPlusPlus11 ?
997                     diag::warn_cxx98_compat_empty_scalar_initializer :
998                     diag::err_empty_scalar_initializer)
999        << IList->getSourceRange();
1000    hadError = !SemaRef.getLangOpts().CPlusPlus11;
1001    ++Index;
1002    ++StructuredIndex;
1003    return;
1004  }
1005
1006  Expr *expr = IList->getInit(Index);
1007  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1008    if (!VerifyOnly)
1009      SemaRef.Diag(SubIList->getLocStart(),
1010                   diag::warn_many_braces_around_scalar_init)
1011        << SubIList->getSourceRange();
1012
1013    CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1014                    StructuredIndex);
1015    return;
1016  } else if (isa<DesignatedInitExpr>(expr)) {
1017    if (!VerifyOnly)
1018      SemaRef.Diag(expr->getLocStart(),
1019                   diag::err_designator_for_scalar_init)
1020        << DeclType << expr->getSourceRange();
1021    hadError = true;
1022    ++Index;
1023    ++StructuredIndex;
1024    return;
1025  }
1026
1027  if (VerifyOnly) {
1028    if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1029      hadError = true;
1030    ++Index;
1031    return;
1032  }
1033
1034  ExprResult Result =
1035    SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1036                                      SemaRef.Owned(expr),
1037                                      /*TopLevelOfInitList=*/true);
1038
1039  Expr *ResultExpr = 0;
1040
1041  if (Result.isInvalid())
1042    hadError = true; // types weren't compatible.
1043  else {
1044    ResultExpr = Result.takeAs<Expr>();
1045
1046    if (ResultExpr != expr) {
1047      // The type was promoted, update initializer list.
1048      IList->setInit(Index, ResultExpr);
1049    }
1050  }
1051  if (hadError)
1052    ++StructuredIndex;
1053  else
1054    UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1055  ++Index;
1056}
1057
1058void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1059                                         InitListExpr *IList, QualType DeclType,
1060                                         unsigned &Index,
1061                                         InitListExpr *StructuredList,
1062                                         unsigned &StructuredIndex) {
1063  if (Index >= IList->getNumInits()) {
1064    // FIXME: It would be wonderful if we could point at the actual member. In
1065    // general, it would be useful to pass location information down the stack,
1066    // so that we know the location (or decl) of the "current object" being
1067    // initialized.
1068    if (!VerifyOnly)
1069      SemaRef.Diag(IList->getLocStart(),
1070                    diag::err_init_reference_member_uninitialized)
1071        << DeclType
1072        << IList->getSourceRange();
1073    hadError = true;
1074    ++Index;
1075    ++StructuredIndex;
1076    return;
1077  }
1078
1079  Expr *expr = IList->getInit(Index);
1080  if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus11) {
1081    if (!VerifyOnly)
1082      SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
1083        << DeclType << IList->getSourceRange();
1084    hadError = true;
1085    ++Index;
1086    ++StructuredIndex;
1087    return;
1088  }
1089
1090  if (VerifyOnly) {
1091    if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1092      hadError = true;
1093    ++Index;
1094    return;
1095  }
1096
1097  ExprResult Result =
1098    SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1099                                      SemaRef.Owned(expr),
1100                                      /*TopLevelOfInitList=*/true);
1101
1102  if (Result.isInvalid())
1103    hadError = true;
1104
1105  expr = Result.takeAs<Expr>();
1106  IList->setInit(Index, expr);
1107
1108  if (hadError)
1109    ++StructuredIndex;
1110  else
1111    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1112  ++Index;
1113}
1114
1115void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1116                                      InitListExpr *IList, QualType DeclType,
1117                                      unsigned &Index,
1118                                      InitListExpr *StructuredList,
1119                                      unsigned &StructuredIndex) {
1120  const VectorType *VT = DeclType->getAs<VectorType>();
1121  unsigned maxElements = VT->getNumElements();
1122  unsigned numEltsInit = 0;
1123  QualType elementType = VT->getElementType();
1124
1125  if (Index >= IList->getNumInits()) {
1126    // Make sure the element type can be value-initialized.
1127    if (VerifyOnly)
1128      CheckValueInitializable(
1129          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1130    return;
1131  }
1132
1133  if (!SemaRef.getLangOpts().OpenCL) {
1134    // If the initializing element is a vector, try to copy-initialize
1135    // instead of breaking it apart (which is doomed to failure anyway).
1136    Expr *Init = IList->getInit(Index);
1137    if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1138      if (VerifyOnly) {
1139        if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1140          hadError = true;
1141        ++Index;
1142        return;
1143      }
1144
1145      ExprResult Result =
1146        SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
1147                                          SemaRef.Owned(Init),
1148                                          /*TopLevelOfInitList=*/true);
1149
1150      Expr *ResultExpr = 0;
1151      if (Result.isInvalid())
1152        hadError = true; // types weren't compatible.
1153      else {
1154        ResultExpr = Result.takeAs<Expr>();
1155
1156        if (ResultExpr != Init) {
1157          // The type was promoted, update initializer list.
1158          IList->setInit(Index, ResultExpr);
1159        }
1160      }
1161      if (hadError)
1162        ++StructuredIndex;
1163      else
1164        UpdateStructuredListElement(StructuredList, StructuredIndex,
1165                                    ResultExpr);
1166      ++Index;
1167      return;
1168    }
1169
1170    InitializedEntity ElementEntity =
1171      InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1172
1173    for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1174      // Don't attempt to go past the end of the init list
1175      if (Index >= IList->getNumInits()) {
1176        if (VerifyOnly)
1177          CheckValueInitializable(ElementEntity);
1178        break;
1179      }
1180
1181      ElementEntity.setElementIndex(Index);
1182      CheckSubElementType(ElementEntity, IList, elementType, Index,
1183                          StructuredList, StructuredIndex);
1184    }
1185    return;
1186  }
1187
1188  InitializedEntity ElementEntity =
1189    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1190
1191  // OpenCL initializers allows vectors to be constructed from vectors.
1192  for (unsigned i = 0; i < maxElements; ++i) {
1193    // Don't attempt to go past the end of the init list
1194    if (Index >= IList->getNumInits())
1195      break;
1196
1197    ElementEntity.setElementIndex(Index);
1198
1199    QualType IType = IList->getInit(Index)->getType();
1200    if (!IType->isVectorType()) {
1201      CheckSubElementType(ElementEntity, IList, elementType, Index,
1202                          StructuredList, StructuredIndex);
1203      ++numEltsInit;
1204    } else {
1205      QualType VecType;
1206      const VectorType *IVT = IType->getAs<VectorType>();
1207      unsigned numIElts = IVT->getNumElements();
1208
1209      if (IType->isExtVectorType())
1210        VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1211      else
1212        VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1213                                                IVT->getVectorKind());
1214      CheckSubElementType(ElementEntity, IList, VecType, Index,
1215                          StructuredList, StructuredIndex);
1216      numEltsInit += numIElts;
1217    }
1218  }
1219
1220  // OpenCL requires all elements to be initialized.
1221  if (numEltsInit != maxElements) {
1222    if (!VerifyOnly)
1223      SemaRef.Diag(IList->getLocStart(),
1224                   diag::err_vector_incorrect_num_initializers)
1225        << (numEltsInit < maxElements) << maxElements << numEltsInit;
1226    hadError = true;
1227  }
1228}
1229
1230void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1231                                     InitListExpr *IList, QualType &DeclType,
1232                                     llvm::APSInt elementIndex,
1233                                     bool SubobjectIsDesignatorContext,
1234                                     unsigned &Index,
1235                                     InitListExpr *StructuredList,
1236                                     unsigned &StructuredIndex) {
1237  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1238
1239  // Check for the special-case of initializing an array with a string.
1240  if (Index < IList->getNumInits()) {
1241    if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1242        SIF_None) {
1243      // We place the string literal directly into the resulting
1244      // initializer list. This is the only place where the structure
1245      // of the structured initializer list doesn't match exactly,
1246      // because doing so would involve allocating one character
1247      // constant for each string.
1248      if (!VerifyOnly) {
1249        CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1250        UpdateStructuredListElement(StructuredList, StructuredIndex,
1251                                    IList->getInit(Index));
1252        StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1253      }
1254      ++Index;
1255      return;
1256    }
1257  }
1258  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1259    // Check for VLAs; in standard C it would be possible to check this
1260    // earlier, but I don't know where clang accepts VLAs (gcc accepts
1261    // them in all sorts of strange places).
1262    if (!VerifyOnly)
1263      SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1264                    diag::err_variable_object_no_init)
1265        << VAT->getSizeExpr()->getSourceRange();
1266    hadError = true;
1267    ++Index;
1268    ++StructuredIndex;
1269    return;
1270  }
1271
1272  // We might know the maximum number of elements in advance.
1273  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1274                           elementIndex.isUnsigned());
1275  bool maxElementsKnown = false;
1276  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1277    maxElements = CAT->getSize();
1278    elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1279    elementIndex.setIsUnsigned(maxElements.isUnsigned());
1280    maxElementsKnown = true;
1281  }
1282
1283  QualType elementType = arrayType->getElementType();
1284  while (Index < IList->getNumInits()) {
1285    Expr *Init = IList->getInit(Index);
1286    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1287      // If we're not the subobject that matches up with the '{' for
1288      // the designator, we shouldn't be handling the
1289      // designator. Return immediately.
1290      if (!SubobjectIsDesignatorContext)
1291        return;
1292
1293      // Handle this designated initializer. elementIndex will be
1294      // updated to be the next array element we'll initialize.
1295      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1296                                     DeclType, 0, &elementIndex, Index,
1297                                     StructuredList, StructuredIndex, true,
1298                                     false)) {
1299        hadError = true;
1300        continue;
1301      }
1302
1303      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1304        maxElements = maxElements.extend(elementIndex.getBitWidth());
1305      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1306        elementIndex = elementIndex.extend(maxElements.getBitWidth());
1307      elementIndex.setIsUnsigned(maxElements.isUnsigned());
1308
1309      // If the array is of incomplete type, keep track of the number of
1310      // elements in the initializer.
1311      if (!maxElementsKnown && elementIndex > maxElements)
1312        maxElements = elementIndex;
1313
1314      continue;
1315    }
1316
1317    // If we know the maximum number of elements, and we've already
1318    // hit it, stop consuming elements in the initializer list.
1319    if (maxElementsKnown && elementIndex == maxElements)
1320      break;
1321
1322    InitializedEntity ElementEntity =
1323      InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1324                                           Entity);
1325    // Check this element.
1326    CheckSubElementType(ElementEntity, IList, elementType, Index,
1327                        StructuredList, StructuredIndex);
1328    ++elementIndex;
1329
1330    // If the array is of incomplete type, keep track of the number of
1331    // elements in the initializer.
1332    if (!maxElementsKnown && elementIndex > maxElements)
1333      maxElements = elementIndex;
1334  }
1335  if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
1336    // If this is an incomplete array type, the actual type needs to
1337    // be calculated here.
1338    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1339    if (maxElements == Zero) {
1340      // Sizing an array implicitly to zero is not allowed by ISO C,
1341      // but is supported by GNU.
1342      SemaRef.Diag(IList->getLocStart(),
1343                    diag::ext_typecheck_zero_array_size);
1344    }
1345
1346    DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
1347                                                     ArrayType::Normal, 0);
1348  }
1349  if (!hadError && VerifyOnly) {
1350    // Check if there are any members of the array that get value-initialized.
1351    // If so, check if doing that is possible.
1352    // FIXME: This needs to detect holes left by designated initializers too.
1353    if (maxElementsKnown && elementIndex < maxElements)
1354      CheckValueInitializable(InitializedEntity::InitializeElement(
1355                                                  SemaRef.Context, 0, Entity));
1356  }
1357}
1358
1359bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1360                                             Expr *InitExpr,
1361                                             FieldDecl *Field,
1362                                             bool TopLevelObject) {
1363  // Handle GNU flexible array initializers.
1364  unsigned FlexArrayDiag;
1365  if (isa<InitListExpr>(InitExpr) &&
1366      cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1367    // Empty flexible array init always allowed as an extension
1368    FlexArrayDiag = diag::ext_flexible_array_init;
1369  } else if (SemaRef.getLangOpts().CPlusPlus) {
1370    // Disallow flexible array init in C++; it is not required for gcc
1371    // compatibility, and it needs work to IRGen correctly in general.
1372    FlexArrayDiag = diag::err_flexible_array_init;
1373  } else if (!TopLevelObject) {
1374    // Disallow flexible array init on non-top-level object
1375    FlexArrayDiag = diag::err_flexible_array_init;
1376  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1377    // Disallow flexible array init on anything which is not a variable.
1378    FlexArrayDiag = diag::err_flexible_array_init;
1379  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1380    // Disallow flexible array init on local variables.
1381    FlexArrayDiag = diag::err_flexible_array_init;
1382  } else {
1383    // Allow other cases.
1384    FlexArrayDiag = diag::ext_flexible_array_init;
1385  }
1386
1387  if (!VerifyOnly) {
1388    SemaRef.Diag(InitExpr->getLocStart(),
1389                 FlexArrayDiag)
1390      << InitExpr->getLocStart();
1391    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1392      << Field;
1393  }
1394
1395  return FlexArrayDiag != diag::ext_flexible_array_init;
1396}
1397
1398void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
1399                                            InitListExpr *IList,
1400                                            QualType DeclType,
1401                                            RecordDecl::field_iterator Field,
1402                                            bool SubobjectIsDesignatorContext,
1403                                            unsigned &Index,
1404                                            InitListExpr *StructuredList,
1405                                            unsigned &StructuredIndex,
1406                                            bool TopLevelObject) {
1407  RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
1408
1409  // If the record is invalid, some of it's members are invalid. To avoid
1410  // confusion, we forgo checking the intializer for the entire record.
1411  if (structDecl->isInvalidDecl()) {
1412    // Assume it was supposed to consume a single initializer.
1413    ++Index;
1414    hadError = true;
1415    return;
1416  }
1417
1418  if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1419    RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1420
1421    // If there's a default initializer, use it.
1422    if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->hasInClassInitializer()) {
1423      if (VerifyOnly)
1424        return;
1425      for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1426           Field != FieldEnd; ++Field) {
1427        if (Field->hasInClassInitializer()) {
1428          StructuredList->setInitializedFieldInUnion(*Field);
1429          // FIXME: Actually build a CXXDefaultInitExpr?
1430          return;
1431        }
1432      }
1433    }
1434
1435    // Value-initialize the first named member of the union.
1436    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1437         Field != FieldEnd; ++Field) {
1438      if (Field->getDeclName()) {
1439        if (VerifyOnly)
1440          CheckValueInitializable(
1441              InitializedEntity::InitializeMember(*Field, &Entity));
1442        else
1443          StructuredList->setInitializedFieldInUnion(*Field);
1444        break;
1445      }
1446    }
1447    return;
1448  }
1449
1450  // If structDecl is a forward declaration, this loop won't do
1451  // anything except look at designated initializers; That's okay,
1452  // because an error should get printed out elsewhere. It might be
1453  // worthwhile to skip over the rest of the initializer, though.
1454  RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1455  RecordDecl::field_iterator FieldEnd = RD->field_end();
1456  bool InitializedSomething = false;
1457  bool CheckForMissingFields = true;
1458  while (Index < IList->getNumInits()) {
1459    Expr *Init = IList->getInit(Index);
1460
1461    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1462      // If we're not the subobject that matches up with the '{' for
1463      // the designator, we shouldn't be handling the
1464      // designator. Return immediately.
1465      if (!SubobjectIsDesignatorContext)
1466        return;
1467
1468      // Handle this designated initializer. Field will be updated to
1469      // the next field that we'll be initializing.
1470      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1471                                     DeclType, &Field, 0, Index,
1472                                     StructuredList, StructuredIndex,
1473                                     true, TopLevelObject))
1474        hadError = true;
1475
1476      InitializedSomething = true;
1477
1478      // Disable check for missing fields when designators are used.
1479      // This matches gcc behaviour.
1480      CheckForMissingFields = false;
1481      continue;
1482    }
1483
1484    if (Field == FieldEnd) {
1485      // We've run out of fields. We're done.
1486      break;
1487    }
1488
1489    // We've already initialized a member of a union. We're done.
1490    if (InitializedSomething && DeclType->isUnionType())
1491      break;
1492
1493    // If we've hit the flexible array member at the end, we're done.
1494    if (Field->getType()->isIncompleteArrayType())
1495      break;
1496
1497    if (Field->isUnnamedBitfield()) {
1498      // Don't initialize unnamed bitfields, e.g. "int : 20;"
1499      ++Field;
1500      continue;
1501    }
1502
1503    // Make sure we can use this declaration.
1504    bool InvalidUse;
1505    if (VerifyOnly)
1506      InvalidUse = !SemaRef.CanUseDecl(*Field);
1507    else
1508      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1509                                          IList->getInit(Index)->getLocStart());
1510    if (InvalidUse) {
1511      ++Index;
1512      ++Field;
1513      hadError = true;
1514      continue;
1515    }
1516
1517    InitializedEntity MemberEntity =
1518      InitializedEntity::InitializeMember(*Field, &Entity);
1519    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1520                        StructuredList, StructuredIndex);
1521    InitializedSomething = true;
1522
1523    if (DeclType->isUnionType() && !VerifyOnly) {
1524      // Initialize the first field within the union.
1525      StructuredList->setInitializedFieldInUnion(*Field);
1526    }
1527
1528    ++Field;
1529  }
1530
1531  // Emit warnings for missing struct field initializers.
1532  if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1533      Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1534      !DeclType->isUnionType()) {
1535    // It is possible we have one or more unnamed bitfields remaining.
1536    // Find first (if any) named field and emit warning.
1537    for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1538         it != end; ++it) {
1539      if (!it->isUnnamedBitfield() && !it->hasInClassInitializer()) {
1540        SemaRef.Diag(IList->getSourceRange().getEnd(),
1541                     diag::warn_missing_field_initializers) << it->getName();
1542        break;
1543      }
1544    }
1545  }
1546
1547  // Check that any remaining fields can be value-initialized.
1548  if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1549      !Field->getType()->isIncompleteArrayType()) {
1550    // FIXME: Should check for holes left by designated initializers too.
1551    for (; Field != FieldEnd && !hadError; ++Field) {
1552      if (!Field->isUnnamedBitfield() && !Field->hasInClassInitializer())
1553        CheckValueInitializable(
1554            InitializedEntity::InitializeMember(*Field, &Entity));
1555    }
1556  }
1557
1558  if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
1559      Index >= IList->getNumInits())
1560    return;
1561
1562  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1563                             TopLevelObject)) {
1564    hadError = true;
1565    ++Index;
1566    return;
1567  }
1568
1569  InitializedEntity MemberEntity =
1570    InitializedEntity::InitializeMember(*Field, &Entity);
1571
1572  if (isa<InitListExpr>(IList->getInit(Index)))
1573    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1574                        StructuredList, StructuredIndex);
1575  else
1576    CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
1577                          StructuredList, StructuredIndex);
1578}
1579
1580/// \brief Expand a field designator that refers to a member of an
1581/// anonymous struct or union into a series of field designators that
1582/// refers to the field within the appropriate subobject.
1583///
1584static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
1585                                           DesignatedInitExpr *DIE,
1586                                           unsigned DesigIdx,
1587                                           IndirectFieldDecl *IndirectField) {
1588  typedef DesignatedInitExpr::Designator Designator;
1589
1590  // Build the replacement designators.
1591  SmallVector<Designator, 4> Replacements;
1592  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1593       PE = IndirectField->chain_end(); PI != PE; ++PI) {
1594    if (PI + 1 == PE)
1595      Replacements.push_back(Designator((IdentifierInfo *)0,
1596                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
1597                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
1598    else
1599      Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1600                                        SourceLocation()));
1601    assert(isa<FieldDecl>(*PI));
1602    Replacements.back().setField(cast<FieldDecl>(*PI));
1603  }
1604
1605  // Expand the current designator into the set of replacement
1606  // designators, so we have a full subobject path down to where the
1607  // member of the anonymous struct/union is actually stored.
1608  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
1609                        &Replacements[0] + Replacements.size());
1610}
1611
1612/// \brief Given an implicit anonymous field, search the IndirectField that
1613///  corresponds to FieldName.
1614static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1615                                                 IdentifierInfo *FieldName) {
1616  if (!FieldName)
1617    return 0;
1618
1619  assert(AnonField->isAnonymousStructOrUnion());
1620  Decl *NextDecl = AnonField->getNextDeclInContext();
1621  while (IndirectFieldDecl *IF =
1622          dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
1623    if (FieldName == IF->getAnonField()->getIdentifier())
1624      return IF;
1625    NextDecl = NextDecl->getNextDeclInContext();
1626  }
1627  return 0;
1628}
1629
1630static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1631                                                   DesignatedInitExpr *DIE) {
1632  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1633  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1634  for (unsigned I = 0; I < NumIndexExprs; ++I)
1635    IndexExprs[I] = DIE->getSubExpr(I + 1);
1636  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1637                                    DIE->size(), IndexExprs,
1638                                    DIE->getEqualOrColonLoc(),
1639                                    DIE->usesGNUSyntax(), DIE->getInit());
1640}
1641
1642namespace {
1643
1644// Callback to only accept typo corrections that are for field members of
1645// the given struct or union.
1646class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1647 public:
1648  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1649      : Record(RD) {}
1650
1651  virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1652    FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1653    return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1654  }
1655
1656 private:
1657  RecordDecl *Record;
1658};
1659
1660}
1661
1662/// @brief Check the well-formedness of a C99 designated initializer.
1663///
1664/// Determines whether the designated initializer @p DIE, which
1665/// resides at the given @p Index within the initializer list @p
1666/// IList, is well-formed for a current object of type @p DeclType
1667/// (C99 6.7.8). The actual subobject that this designator refers to
1668/// within the current subobject is returned in either
1669/// @p NextField or @p NextElementIndex (whichever is appropriate).
1670///
1671/// @param IList  The initializer list in which this designated
1672/// initializer occurs.
1673///
1674/// @param DIE The designated initializer expression.
1675///
1676/// @param DesigIdx  The index of the current designator.
1677///
1678/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
1679/// into which the designation in @p DIE should refer.
1680///
1681/// @param NextField  If non-NULL and the first designator in @p DIE is
1682/// a field, this will be set to the field declaration corresponding
1683/// to the field named by the designator.
1684///
1685/// @param NextElementIndex  If non-NULL and the first designator in @p
1686/// DIE is an array designator or GNU array-range designator, this
1687/// will be set to the last index initialized by this designator.
1688///
1689/// @param Index  Index into @p IList where the designated initializer
1690/// @p DIE occurs.
1691///
1692/// @param StructuredList  The initializer list expression that
1693/// describes all of the subobject initializers in the order they'll
1694/// actually be initialized.
1695///
1696/// @returns true if there was an error, false otherwise.
1697bool
1698InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
1699                                            InitListExpr *IList,
1700                                            DesignatedInitExpr *DIE,
1701                                            unsigned DesigIdx,
1702                                            QualType &CurrentObjectType,
1703                                          RecordDecl::field_iterator *NextField,
1704                                            llvm::APSInt *NextElementIndex,
1705                                            unsigned &Index,
1706                                            InitListExpr *StructuredList,
1707                                            unsigned &StructuredIndex,
1708                                            bool FinishSubobjectInit,
1709                                            bool TopLevelObject) {
1710  if (DesigIdx == DIE->size()) {
1711    // Check the actual initialization for the designated object type.
1712    bool prevHadError = hadError;
1713
1714    // Temporarily remove the designator expression from the
1715    // initializer list that the child calls see, so that we don't try
1716    // to re-process the designator.
1717    unsigned OldIndex = Index;
1718    IList->setInit(OldIndex, DIE->getInit());
1719
1720    CheckSubElementType(Entity, IList, CurrentObjectType, Index,
1721                        StructuredList, StructuredIndex);
1722
1723    // Restore the designated initializer expression in the syntactic
1724    // form of the initializer list.
1725    if (IList->getInit(OldIndex) != DIE->getInit())
1726      DIE->setInit(IList->getInit(OldIndex));
1727    IList->setInit(OldIndex, DIE);
1728
1729    return hadError && !prevHadError;
1730  }
1731
1732  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
1733  bool IsFirstDesignator = (DesigIdx == 0);
1734  if (!VerifyOnly) {
1735    assert((IsFirstDesignator || StructuredList) &&
1736           "Need a non-designated initializer list to start from");
1737
1738    // Determine the structural initializer list that corresponds to the
1739    // current subobject.
1740    StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
1741      : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1742                                   StructuredList, StructuredIndex,
1743                                   SourceRange(D->getLocStart(),
1744                                               DIE->getLocEnd()));
1745    assert(StructuredList && "Expected a structured initializer list");
1746  }
1747
1748  if (D->isFieldDesignator()) {
1749    // C99 6.7.8p7:
1750    //
1751    //   If a designator has the form
1752    //
1753    //      . identifier
1754    //
1755    //   then the current object (defined below) shall have
1756    //   structure or union type and the identifier shall be the
1757    //   name of a member of that type.
1758    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
1759    if (!RT) {
1760      SourceLocation Loc = D->getDotLoc();
1761      if (Loc.isInvalid())
1762        Loc = D->getFieldLoc();
1763      if (!VerifyOnly)
1764        SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1765          << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
1766      ++Index;
1767      return true;
1768    }
1769
1770    // Note: we perform a linear search of the fields here, despite
1771    // the fact that we have a faster lookup method, because we always
1772    // need to compute the field's index.
1773    FieldDecl *KnownField = D->getField();
1774    IdentifierInfo *FieldName = D->getFieldName();
1775    unsigned FieldIndex = 0;
1776    RecordDecl::field_iterator
1777      Field = RT->getDecl()->field_begin(),
1778      FieldEnd = RT->getDecl()->field_end();
1779    for (; Field != FieldEnd; ++Field) {
1780      if (Field->isUnnamedBitfield())
1781        continue;
1782
1783      // If we find a field representing an anonymous field, look in the
1784      // IndirectFieldDecl that follow for the designated initializer.
1785      if (!KnownField && Field->isAnonymousStructOrUnion()) {
1786        if (IndirectFieldDecl *IF =
1787            FindIndirectFieldDesignator(*Field, FieldName)) {
1788          // In verify mode, don't modify the original.
1789          if (VerifyOnly)
1790            DIE = CloneDesignatedInitExpr(SemaRef, DIE);
1791          ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1792          D = DIE->getDesignator(DesigIdx);
1793          break;
1794        }
1795      }
1796      if (KnownField && KnownField == *Field)
1797        break;
1798      if (FieldName && FieldName == Field->getIdentifier())
1799        break;
1800
1801      ++FieldIndex;
1802    }
1803
1804    if (Field == FieldEnd) {
1805      if (VerifyOnly) {
1806        ++Index;
1807        return true; // No typo correction when just trying this out.
1808      }
1809
1810      // There was no normal field in the struct with the designated
1811      // name. Perform another lookup for this name, which may find
1812      // something that we can't designate (e.g., a member function),
1813      // may find nothing, or may find a member of an anonymous
1814      // struct/union.
1815      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
1816      FieldDecl *ReplacementField = 0;
1817      if (Lookup.empty()) {
1818        // Name lookup didn't find anything. Determine whether this
1819        // was a typo for another field name.
1820        FieldInitializerValidatorCCC Validator(RT->getDecl());
1821        if (TypoCorrection Corrected = SemaRef.CorrectTypo(
1822                DeclarationNameInfo(FieldName, D->getFieldLoc()),
1823                Sema::LookupMemberName, /*Scope=*/ 0, /*SS=*/ 0, Validator,
1824                RT->getDecl())) {
1825          SemaRef.diagnoseTypo(
1826              Corrected,
1827              SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
1828                  << FieldName << CurrentObjectType);
1829          ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
1830          hadError = true;
1831        } else {
1832          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1833            << FieldName << CurrentObjectType;
1834          ++Index;
1835          return true;
1836        }
1837      }
1838
1839      if (!ReplacementField) {
1840        // Name lookup found something, but it wasn't a field.
1841        SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
1842          << FieldName;
1843        SemaRef.Diag(Lookup.front()->getLocation(),
1844                      diag::note_field_designator_found);
1845        ++Index;
1846        return true;
1847      }
1848
1849      if (!KnownField) {
1850        // The replacement field comes from typo correction; find it
1851        // in the list of fields.
1852        FieldIndex = 0;
1853        Field = RT->getDecl()->field_begin();
1854        for (; Field != FieldEnd; ++Field) {
1855          if (Field->isUnnamedBitfield())
1856            continue;
1857
1858          if (ReplacementField == *Field ||
1859              Field->getIdentifier() == ReplacementField->getIdentifier())
1860            break;
1861
1862          ++FieldIndex;
1863        }
1864      }
1865    }
1866
1867    // All of the fields of a union are located at the same place in
1868    // the initializer list.
1869    if (RT->getDecl()->isUnion()) {
1870      FieldIndex = 0;
1871      if (!VerifyOnly)
1872        StructuredList->setInitializedFieldInUnion(*Field);
1873    }
1874
1875    // Make sure we can use this declaration.
1876    bool InvalidUse;
1877    if (VerifyOnly)
1878      InvalidUse = !SemaRef.CanUseDecl(*Field);
1879    else
1880      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1881    if (InvalidUse) {
1882      ++Index;
1883      return true;
1884    }
1885
1886    if (!VerifyOnly) {
1887      // Update the designator with the field declaration.
1888      D->setField(*Field);
1889
1890      // Make sure that our non-designated initializer list has space
1891      // for a subobject corresponding to this field.
1892      if (FieldIndex >= StructuredList->getNumInits())
1893        StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1894    }
1895
1896    // This designator names a flexible array member.
1897    if (Field->getType()->isIncompleteArrayType()) {
1898      bool Invalid = false;
1899      if ((DesigIdx + 1) != DIE->size()) {
1900        // We can't designate an object within the flexible array
1901        // member (because GCC doesn't allow it).
1902        if (!VerifyOnly) {
1903          DesignatedInitExpr::Designator *NextD
1904            = DIE->getDesignator(DesigIdx + 1);
1905          SemaRef.Diag(NextD->getLocStart(),
1906                        diag::err_designator_into_flexible_array_member)
1907            << SourceRange(NextD->getLocStart(),
1908                           DIE->getLocEnd());
1909          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1910            << *Field;
1911        }
1912        Invalid = true;
1913      }
1914
1915      if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1916          !isa<StringLiteral>(DIE->getInit())) {
1917        // The initializer is not an initializer list.
1918        if (!VerifyOnly) {
1919          SemaRef.Diag(DIE->getInit()->getLocStart(),
1920                        diag::err_flexible_array_init_needs_braces)
1921            << DIE->getInit()->getSourceRange();
1922          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1923            << *Field;
1924        }
1925        Invalid = true;
1926      }
1927
1928      // Check GNU flexible array initializer.
1929      if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1930                                             TopLevelObject))
1931        Invalid = true;
1932
1933      if (Invalid) {
1934        ++Index;
1935        return true;
1936      }
1937
1938      // Initialize the array.
1939      bool prevHadError = hadError;
1940      unsigned newStructuredIndex = FieldIndex;
1941      unsigned OldIndex = Index;
1942      IList->setInit(Index, DIE->getInit());
1943
1944      InitializedEntity MemberEntity =
1945        InitializedEntity::InitializeMember(*Field, &Entity);
1946      CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1947                          StructuredList, newStructuredIndex);
1948
1949      IList->setInit(OldIndex, DIE);
1950      if (hadError && !prevHadError) {
1951        ++Field;
1952        ++FieldIndex;
1953        if (NextField)
1954          *NextField = Field;
1955        StructuredIndex = FieldIndex;
1956        return true;
1957      }
1958    } else {
1959      // Recurse to check later designated subobjects.
1960      QualType FieldType = Field->getType();
1961      unsigned newStructuredIndex = FieldIndex;
1962
1963      InitializedEntity MemberEntity =
1964        InitializedEntity::InitializeMember(*Field, &Entity);
1965      if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1966                                     FieldType, 0, 0, Index,
1967                                     StructuredList, newStructuredIndex,
1968                                     true, false))
1969        return true;
1970    }
1971
1972    // Find the position of the next field to be initialized in this
1973    // subobject.
1974    ++Field;
1975    ++FieldIndex;
1976
1977    // If this the first designator, our caller will continue checking
1978    // the rest of this struct/class/union subobject.
1979    if (IsFirstDesignator) {
1980      if (NextField)
1981        *NextField = Field;
1982      StructuredIndex = FieldIndex;
1983      return false;
1984    }
1985
1986    if (!FinishSubobjectInit)
1987      return false;
1988
1989    // We've already initialized something in the union; we're done.
1990    if (RT->getDecl()->isUnion())
1991      return hadError;
1992
1993    // Check the remaining fields within this class/struct/union subobject.
1994    bool prevHadError = hadError;
1995
1996    CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
1997                          StructuredList, FieldIndex);
1998    return hadError && !prevHadError;
1999  }
2000
2001  // C99 6.7.8p6:
2002  //
2003  //   If a designator has the form
2004  //
2005  //      [ constant-expression ]
2006  //
2007  //   then the current object (defined below) shall have array
2008  //   type and the expression shall be an integer constant
2009  //   expression. If the array is of unknown size, any
2010  //   nonnegative value is valid.
2011  //
2012  // Additionally, cope with the GNU extension that permits
2013  // designators of the form
2014  //
2015  //      [ constant-expression ... constant-expression ]
2016  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2017  if (!AT) {
2018    if (!VerifyOnly)
2019      SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2020        << CurrentObjectType;
2021    ++Index;
2022    return true;
2023  }
2024
2025  Expr *IndexExpr = 0;
2026  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2027  if (D->isArrayDesignator()) {
2028    IndexExpr = DIE->getArrayIndex(*D);
2029    DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2030    DesignatedEndIndex = DesignatedStartIndex;
2031  } else {
2032    assert(D->isArrayRangeDesignator() && "Need array-range designator");
2033
2034    DesignatedStartIndex =
2035      DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2036    DesignatedEndIndex =
2037      DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2038    IndexExpr = DIE->getArrayRangeEnd(*D);
2039
2040    // Codegen can't handle evaluating array range designators that have side
2041    // effects, because we replicate the AST value for each initialized element.
2042    // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2043    // elements with something that has a side effect, so codegen can emit an
2044    // "error unsupported" error instead of miscompiling the app.
2045    if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2046        DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2047      FullyStructuredList->sawArrayRangeDesignator();
2048  }
2049
2050  if (isa<ConstantArrayType>(AT)) {
2051    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2052    DesignatedStartIndex
2053      = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2054    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2055    DesignatedEndIndex
2056      = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2057    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2058    if (DesignatedEndIndex >= MaxElements) {
2059      if (!VerifyOnly)
2060        SemaRef.Diag(IndexExpr->getLocStart(),
2061                      diag::err_array_designator_too_large)
2062          << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2063          << IndexExpr->getSourceRange();
2064      ++Index;
2065      return true;
2066    }
2067  } else {
2068    // Make sure the bit-widths and signedness match.
2069    if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
2070      DesignatedEndIndex
2071        = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
2072    else if (DesignatedStartIndex.getBitWidth() <
2073             DesignatedEndIndex.getBitWidth())
2074      DesignatedStartIndex
2075        = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
2076    DesignatedStartIndex.setIsUnsigned(true);
2077    DesignatedEndIndex.setIsUnsigned(true);
2078  }
2079
2080  if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2081    // We're modifying a string literal init; we have to decompose the string
2082    // so we can modify the individual characters.
2083    ASTContext &Context = SemaRef.Context;
2084    Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2085
2086    // Compute the character type
2087    QualType CharTy = AT->getElementType();
2088
2089    // Compute the type of the integer literals.
2090    QualType PromotedCharTy = CharTy;
2091    if (CharTy->isPromotableIntegerType())
2092      PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2093    unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2094
2095    if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2096      // Get the length of the string.
2097      uint64_t StrLen = SL->getLength();
2098      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2099        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2100      StructuredList->resizeInits(Context, StrLen);
2101
2102      // Build a literal for each character in the string, and put them into
2103      // the init list.
2104      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2105        llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2106        Expr *Init = new (Context) IntegerLiteral(
2107            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2108        if (CharTy != PromotedCharTy)
2109          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2110                                          Init, 0, VK_RValue);
2111        StructuredList->updateInit(Context, i, Init);
2112      }
2113    } else {
2114      ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2115      std::string Str;
2116      Context.getObjCEncodingForType(E->getEncodedType(), Str);
2117
2118      // Get the length of the string.
2119      uint64_t StrLen = Str.size();
2120      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2121        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2122      StructuredList->resizeInits(Context, StrLen);
2123
2124      // Build a literal for each character in the string, and put them into
2125      // the init list.
2126      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2127        llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2128        Expr *Init = new (Context) IntegerLiteral(
2129            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2130        if (CharTy != PromotedCharTy)
2131          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2132                                          Init, 0, VK_RValue);
2133        StructuredList->updateInit(Context, i, Init);
2134      }
2135    }
2136  }
2137
2138  // Make sure that our non-designated initializer list has space
2139  // for a subobject corresponding to this array element.
2140  if (!VerifyOnly &&
2141      DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2142    StructuredList->resizeInits(SemaRef.Context,
2143                                DesignatedEndIndex.getZExtValue() + 1);
2144
2145  // Repeatedly perform subobject initializations in the range
2146  // [DesignatedStartIndex, DesignatedEndIndex].
2147
2148  // Move to the next designator
2149  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2150  unsigned OldIndex = Index;
2151
2152  InitializedEntity ElementEntity =
2153    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2154
2155  while (DesignatedStartIndex <= DesignatedEndIndex) {
2156    // Recurse to check later designated subobjects.
2157    QualType ElementType = AT->getElementType();
2158    Index = OldIndex;
2159
2160    ElementEntity.setElementIndex(ElementIndex);
2161    if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2162                                   ElementType, 0, 0, Index,
2163                                   StructuredList, ElementIndex,
2164                                   (DesignatedStartIndex == DesignatedEndIndex),
2165                                   false))
2166      return true;
2167
2168    // Move to the next index in the array that we'll be initializing.
2169    ++DesignatedStartIndex;
2170    ElementIndex = DesignatedStartIndex.getZExtValue();
2171  }
2172
2173  // If this the first designator, our caller will continue checking
2174  // the rest of this array subobject.
2175  if (IsFirstDesignator) {
2176    if (NextElementIndex)
2177      *NextElementIndex = DesignatedStartIndex;
2178    StructuredIndex = ElementIndex;
2179    return false;
2180  }
2181
2182  if (!FinishSubobjectInit)
2183    return false;
2184
2185  // Check the remaining elements within this array subobject.
2186  bool prevHadError = hadError;
2187  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2188                 /*SubobjectIsDesignatorContext=*/false, Index,
2189                 StructuredList, ElementIndex);
2190  return hadError && !prevHadError;
2191}
2192
2193// Get the structured initializer list for a subobject of type
2194// @p CurrentObjectType.
2195InitListExpr *
2196InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2197                                            QualType CurrentObjectType,
2198                                            InitListExpr *StructuredList,
2199                                            unsigned StructuredIndex,
2200                                            SourceRange InitRange) {
2201  if (VerifyOnly)
2202    return 0; // No structured list in verification-only mode.
2203  Expr *ExistingInit = 0;
2204  if (!StructuredList)
2205    ExistingInit = SyntacticToSemantic.lookup(IList);
2206  else if (StructuredIndex < StructuredList->getNumInits())
2207    ExistingInit = StructuredList->getInit(StructuredIndex);
2208
2209  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2210    return Result;
2211
2212  if (ExistingInit) {
2213    // We are creating an initializer list that initializes the
2214    // subobjects of the current object, but there was already an
2215    // initialization that completely initialized the current
2216    // subobject, e.g., by a compound literal:
2217    //
2218    // struct X { int a, b; };
2219    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2220    //
2221    // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2222    // designated initializer re-initializes the whole
2223    // subobject [0], overwriting previous initializers.
2224    SemaRef.Diag(InitRange.getBegin(),
2225                 diag::warn_subobject_initializer_overrides)
2226      << InitRange;
2227    SemaRef.Diag(ExistingInit->getLocStart(),
2228                  diag::note_previous_initializer)
2229      << /*FIXME:has side effects=*/0
2230      << ExistingInit->getSourceRange();
2231  }
2232
2233  InitListExpr *Result
2234    = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2235                                         InitRange.getBegin(), None,
2236                                         InitRange.getEnd());
2237
2238  QualType ResultType = CurrentObjectType;
2239  if (!ResultType->isArrayType())
2240    ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2241  Result->setType(ResultType);
2242
2243  // Pre-allocate storage for the structured initializer list.
2244  unsigned NumElements = 0;
2245  unsigned NumInits = 0;
2246  bool GotNumInits = false;
2247  if (!StructuredList) {
2248    NumInits = IList->getNumInits();
2249    GotNumInits = true;
2250  } else if (Index < IList->getNumInits()) {
2251    if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2252      NumInits = SubList->getNumInits();
2253      GotNumInits = true;
2254    }
2255  }
2256
2257  if (const ArrayType *AType
2258      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2259    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2260      NumElements = CAType->getSize().getZExtValue();
2261      // Simple heuristic so that we don't allocate a very large
2262      // initializer with many empty entries at the end.
2263      if (GotNumInits && NumElements > NumInits)
2264        NumElements = 0;
2265    }
2266  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2267    NumElements = VType->getNumElements();
2268  else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2269    RecordDecl *RDecl = RType->getDecl();
2270    if (RDecl->isUnion())
2271      NumElements = 1;
2272    else
2273      NumElements = std::distance(RDecl->field_begin(),
2274                                  RDecl->field_end());
2275  }
2276
2277  Result->reserveInits(SemaRef.Context, NumElements);
2278
2279  // Link this new initializer list into the structured initializer
2280  // lists.
2281  if (StructuredList)
2282    StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2283  else {
2284    Result->setSyntacticForm(IList);
2285    SyntacticToSemantic[IList] = Result;
2286  }
2287
2288  return Result;
2289}
2290
2291/// Update the initializer at index @p StructuredIndex within the
2292/// structured initializer list to the value @p expr.
2293void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2294                                                  unsigned &StructuredIndex,
2295                                                  Expr *expr) {
2296  // No structured initializer list to update
2297  if (!StructuredList)
2298    return;
2299
2300  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2301                                                  StructuredIndex, expr)) {
2302    // This initializer overwrites a previous initializer. Warn.
2303    SemaRef.Diag(expr->getLocStart(),
2304                  diag::warn_initializer_overrides)
2305      << expr->getSourceRange();
2306    SemaRef.Diag(PrevInit->getLocStart(),
2307                  diag::note_previous_initializer)
2308      << /*FIXME:has side effects=*/0
2309      << PrevInit->getSourceRange();
2310  }
2311
2312  ++StructuredIndex;
2313}
2314
2315/// Check that the given Index expression is a valid array designator
2316/// value. This is essentially just a wrapper around
2317/// VerifyIntegerConstantExpression that also checks for negative values
2318/// and produces a reasonable diagnostic if there is a
2319/// failure. Returns the index expression, possibly with an implicit cast
2320/// added, on success.  If everything went okay, Value will receive the
2321/// value of the constant expression.
2322static ExprResult
2323CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2324  SourceLocation Loc = Index->getLocStart();
2325
2326  // Make sure this is an integer constant expression.
2327  ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2328  if (Result.isInvalid())
2329    return Result;
2330
2331  if (Value.isSigned() && Value.isNegative())
2332    return S.Diag(Loc, diag::err_array_designator_negative)
2333      << Value.toString(10) << Index->getSourceRange();
2334
2335  Value.setIsUnsigned(true);
2336  return Result;
2337}
2338
2339ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2340                                            SourceLocation Loc,
2341                                            bool GNUSyntax,
2342                                            ExprResult Init) {
2343  typedef DesignatedInitExpr::Designator ASTDesignator;
2344
2345  bool Invalid = false;
2346  SmallVector<ASTDesignator, 32> Designators;
2347  SmallVector<Expr *, 32> InitExpressions;
2348
2349  // Build designators and check array designator expressions.
2350  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2351    const Designator &D = Desig.getDesignator(Idx);
2352    switch (D.getKind()) {
2353    case Designator::FieldDesignator:
2354      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2355                                          D.getFieldLoc()));
2356      break;
2357
2358    case Designator::ArrayDesignator: {
2359      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2360      llvm::APSInt IndexValue;
2361      if (!Index->isTypeDependent() && !Index->isValueDependent())
2362        Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2363      if (!Index)
2364        Invalid = true;
2365      else {
2366        Designators.push_back(ASTDesignator(InitExpressions.size(),
2367                                            D.getLBracketLoc(),
2368                                            D.getRBracketLoc()));
2369        InitExpressions.push_back(Index);
2370      }
2371      break;
2372    }
2373
2374    case Designator::ArrayRangeDesignator: {
2375      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2376      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2377      llvm::APSInt StartValue;
2378      llvm::APSInt EndValue;
2379      bool StartDependent = StartIndex->isTypeDependent() ||
2380                            StartIndex->isValueDependent();
2381      bool EndDependent = EndIndex->isTypeDependent() ||
2382                          EndIndex->isValueDependent();
2383      if (!StartDependent)
2384        StartIndex =
2385            CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2386      if (!EndDependent)
2387        EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2388
2389      if (!StartIndex || !EndIndex)
2390        Invalid = true;
2391      else {
2392        // Make sure we're comparing values with the same bit width.
2393        if (StartDependent || EndDependent) {
2394          // Nothing to compute.
2395        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2396          EndValue = EndValue.extend(StartValue.getBitWidth());
2397        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2398          StartValue = StartValue.extend(EndValue.getBitWidth());
2399
2400        if (!StartDependent && !EndDependent && EndValue < StartValue) {
2401          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2402            << StartValue.toString(10) << EndValue.toString(10)
2403            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2404          Invalid = true;
2405        } else {
2406          Designators.push_back(ASTDesignator(InitExpressions.size(),
2407                                              D.getLBracketLoc(),
2408                                              D.getEllipsisLoc(),
2409                                              D.getRBracketLoc()));
2410          InitExpressions.push_back(StartIndex);
2411          InitExpressions.push_back(EndIndex);
2412        }
2413      }
2414      break;
2415    }
2416    }
2417  }
2418
2419  if (Invalid || Init.isInvalid())
2420    return ExprError();
2421
2422  // Clear out the expressions within the designation.
2423  Desig.ClearExprs(*this);
2424
2425  DesignatedInitExpr *DIE
2426    = DesignatedInitExpr::Create(Context,
2427                                 Designators.data(), Designators.size(),
2428                                 InitExpressions, Loc, GNUSyntax,
2429                                 Init.takeAs<Expr>());
2430
2431  if (!getLangOpts().C99)
2432    Diag(DIE->getLocStart(), diag::ext_designated_init)
2433      << DIE->getSourceRange();
2434
2435  return Owned(DIE);
2436}
2437
2438//===----------------------------------------------------------------------===//
2439// Initialization entity
2440//===----------------------------------------------------------------------===//
2441
2442InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2443                                     const InitializedEntity &Parent)
2444  : Parent(&Parent), Index(Index)
2445{
2446  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2447    Kind = EK_ArrayElement;
2448    Type = AT->getElementType();
2449  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2450    Kind = EK_VectorElement;
2451    Type = VT->getElementType();
2452  } else {
2453    const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2454    assert(CT && "Unexpected type");
2455    Kind = EK_ComplexElement;
2456    Type = CT->getElementType();
2457  }
2458}
2459
2460InitializedEntity
2461InitializedEntity::InitializeBase(ASTContext &Context,
2462                                  const CXXBaseSpecifier *Base,
2463                                  bool IsInheritedVirtualBase) {
2464  InitializedEntity Result;
2465  Result.Kind = EK_Base;
2466  Result.Parent = 0;
2467  Result.Base = reinterpret_cast<uintptr_t>(Base);
2468  if (IsInheritedVirtualBase)
2469    Result.Base |= 0x01;
2470
2471  Result.Type = Base->getType();
2472  return Result;
2473}
2474
2475DeclarationName InitializedEntity::getName() const {
2476  switch (getKind()) {
2477  case EK_Parameter:
2478  case EK_Parameter_CF_Audited: {
2479    ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2480    return (D ? D->getDeclName() : DeclarationName());
2481  }
2482
2483  case EK_Variable:
2484  case EK_Member:
2485    return VariableOrMember->getDeclName();
2486
2487  case EK_LambdaCapture:
2488    return Capture.Var->getDeclName();
2489
2490  case EK_Result:
2491  case EK_Exception:
2492  case EK_New:
2493  case EK_Temporary:
2494  case EK_Base:
2495  case EK_Delegating:
2496  case EK_ArrayElement:
2497  case EK_VectorElement:
2498  case EK_ComplexElement:
2499  case EK_BlockElement:
2500  case EK_CompoundLiteralInit:
2501  case EK_RelatedResult:
2502    return DeclarationName();
2503  }
2504
2505  llvm_unreachable("Invalid EntityKind!");
2506}
2507
2508DeclaratorDecl *InitializedEntity::getDecl() const {
2509  switch (getKind()) {
2510  case EK_Variable:
2511  case EK_Member:
2512    return VariableOrMember;
2513
2514  case EK_Parameter:
2515  case EK_Parameter_CF_Audited:
2516    return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2517
2518  case EK_Result:
2519  case EK_Exception:
2520  case EK_New:
2521  case EK_Temporary:
2522  case EK_Base:
2523  case EK_Delegating:
2524  case EK_ArrayElement:
2525  case EK_VectorElement:
2526  case EK_ComplexElement:
2527  case EK_BlockElement:
2528  case EK_LambdaCapture:
2529  case EK_CompoundLiteralInit:
2530  case EK_RelatedResult:
2531    return 0;
2532  }
2533
2534  llvm_unreachable("Invalid EntityKind!");
2535}
2536
2537bool InitializedEntity::allowsNRVO() const {
2538  switch (getKind()) {
2539  case EK_Result:
2540  case EK_Exception:
2541    return LocAndNRVO.NRVO;
2542
2543  case EK_Variable:
2544  case EK_Parameter:
2545  case EK_Parameter_CF_Audited:
2546  case EK_Member:
2547  case EK_New:
2548  case EK_Temporary:
2549  case EK_CompoundLiteralInit:
2550  case EK_Base:
2551  case EK_Delegating:
2552  case EK_ArrayElement:
2553  case EK_VectorElement:
2554  case EK_ComplexElement:
2555  case EK_BlockElement:
2556  case EK_LambdaCapture:
2557  case EK_RelatedResult:
2558    break;
2559  }
2560
2561  return false;
2562}
2563
2564unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
2565  assert(getParent() != this);
2566  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2567  for (unsigned I = 0; I != Depth; ++I)
2568    OS << "`-";
2569
2570  switch (getKind()) {
2571  case EK_Variable: OS << "Variable"; break;
2572  case EK_Parameter: OS << "Parameter"; break;
2573  case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2574    break;
2575  case EK_Result: OS << "Result"; break;
2576  case EK_Exception: OS << "Exception"; break;
2577  case EK_Member: OS << "Member"; break;
2578  case EK_New: OS << "New"; break;
2579  case EK_Temporary: OS << "Temporary"; break;
2580  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
2581  case EK_RelatedResult: OS << "RelatedResult"; break;
2582  case EK_Base: OS << "Base"; break;
2583  case EK_Delegating: OS << "Delegating"; break;
2584  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2585  case EK_VectorElement: OS << "VectorElement " << Index; break;
2586  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2587  case EK_BlockElement: OS << "Block"; break;
2588  case EK_LambdaCapture:
2589    OS << "LambdaCapture ";
2590    getCapturedVar()->printName(OS);
2591    break;
2592  }
2593
2594  if (Decl *D = getDecl()) {
2595    OS << " ";
2596    cast<NamedDecl>(D)->printQualifiedName(OS);
2597  }
2598
2599  OS << " '" << getType().getAsString() << "'\n";
2600
2601  return Depth + 1;
2602}
2603
2604void InitializedEntity::dump() const {
2605  dumpImpl(llvm::errs());
2606}
2607
2608//===----------------------------------------------------------------------===//
2609// Initialization sequence
2610//===----------------------------------------------------------------------===//
2611
2612void InitializationSequence::Step::Destroy() {
2613  switch (Kind) {
2614  case SK_ResolveAddressOfOverloadedFunction:
2615  case SK_CastDerivedToBaseRValue:
2616  case SK_CastDerivedToBaseXValue:
2617  case SK_CastDerivedToBaseLValue:
2618  case SK_BindReference:
2619  case SK_BindReferenceToTemporary:
2620  case SK_ExtraneousCopyToTemporary:
2621  case SK_UserConversion:
2622  case SK_QualificationConversionRValue:
2623  case SK_QualificationConversionXValue:
2624  case SK_QualificationConversionLValue:
2625  case SK_LValueToRValue:
2626  case SK_ListInitialization:
2627  case SK_ListConstructorCall:
2628  case SK_UnwrapInitList:
2629  case SK_RewrapInitList:
2630  case SK_ConstructorInitialization:
2631  case SK_ZeroInitialization:
2632  case SK_CAssignment:
2633  case SK_StringInit:
2634  case SK_ObjCObjectConversion:
2635  case SK_ArrayInit:
2636  case SK_ParenthesizedArrayInit:
2637  case SK_PassByIndirectCopyRestore:
2638  case SK_PassByIndirectRestore:
2639  case SK_ProduceObjCObject:
2640  case SK_StdInitializerList:
2641  case SK_OCLSamplerInit:
2642  case SK_OCLZeroEvent:
2643    break;
2644
2645  case SK_ConversionSequence:
2646  case SK_ConversionSequenceNoNarrowing:
2647    delete ICS;
2648  }
2649}
2650
2651bool InitializationSequence::isDirectReferenceBinding() const {
2652  return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2653}
2654
2655bool InitializationSequence::isAmbiguous() const {
2656  if (!Failed())
2657    return false;
2658
2659  switch (getFailureKind()) {
2660  case FK_TooManyInitsForReference:
2661  case FK_ArrayNeedsInitList:
2662  case FK_ArrayNeedsInitListOrStringLiteral:
2663  case FK_ArrayNeedsInitListOrWideStringLiteral:
2664  case FK_NarrowStringIntoWideCharArray:
2665  case FK_WideStringIntoCharArray:
2666  case FK_IncompatWideStringIntoWideChar:
2667  case FK_AddressOfOverloadFailed: // FIXME: Could do better
2668  case FK_NonConstLValueReferenceBindingToTemporary:
2669  case FK_NonConstLValueReferenceBindingToUnrelated:
2670  case FK_RValueReferenceBindingToLValue:
2671  case FK_ReferenceInitDropsQualifiers:
2672  case FK_ReferenceInitFailed:
2673  case FK_ConversionFailed:
2674  case FK_ConversionFromPropertyFailed:
2675  case FK_TooManyInitsForScalar:
2676  case FK_ReferenceBindingToInitList:
2677  case FK_InitListBadDestinationType:
2678  case FK_DefaultInitOfConst:
2679  case FK_Incomplete:
2680  case FK_ArrayTypeMismatch:
2681  case FK_NonConstantArrayInit:
2682  case FK_ListInitializationFailed:
2683  case FK_VariableLengthArrayHasInitializer:
2684  case FK_PlaceholderType:
2685  case FK_ExplicitConstructor:
2686    return false;
2687
2688  case FK_ReferenceInitOverloadFailed:
2689  case FK_UserConversionOverloadFailed:
2690  case FK_ConstructorOverloadFailed:
2691  case FK_ListConstructorOverloadFailed:
2692    return FailedOverloadResult == OR_Ambiguous;
2693  }
2694
2695  llvm_unreachable("Invalid EntityKind!");
2696}
2697
2698bool InitializationSequence::isConstructorInitialization() const {
2699  return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2700}
2701
2702void
2703InitializationSequence
2704::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2705                                   DeclAccessPair Found,
2706                                   bool HadMultipleCandidates) {
2707  Step S;
2708  S.Kind = SK_ResolveAddressOfOverloadedFunction;
2709  S.Type = Function->getType();
2710  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2711  S.Function.Function = Function;
2712  S.Function.FoundDecl = Found;
2713  Steps.push_back(S);
2714}
2715
2716void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2717                                                      ExprValueKind VK) {
2718  Step S;
2719  switch (VK) {
2720  case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2721  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2722  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2723  }
2724  S.Type = BaseType;
2725  Steps.push_back(S);
2726}
2727
2728void InitializationSequence::AddReferenceBindingStep(QualType T,
2729                                                     bool BindingTemporary) {
2730  Step S;
2731  S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2732  S.Type = T;
2733  Steps.push_back(S);
2734}
2735
2736void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2737  Step S;
2738  S.Kind = SK_ExtraneousCopyToTemporary;
2739  S.Type = T;
2740  Steps.push_back(S);
2741}
2742
2743void
2744InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2745                                              DeclAccessPair FoundDecl,
2746                                              QualType T,
2747                                              bool HadMultipleCandidates) {
2748  Step S;
2749  S.Kind = SK_UserConversion;
2750  S.Type = T;
2751  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2752  S.Function.Function = Function;
2753  S.Function.FoundDecl = FoundDecl;
2754  Steps.push_back(S);
2755}
2756
2757void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2758                                                            ExprValueKind VK) {
2759  Step S;
2760  S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2761  switch (VK) {
2762  case VK_RValue:
2763    S.Kind = SK_QualificationConversionRValue;
2764    break;
2765  case VK_XValue:
2766    S.Kind = SK_QualificationConversionXValue;
2767    break;
2768  case VK_LValue:
2769    S.Kind = SK_QualificationConversionLValue;
2770    break;
2771  }
2772  S.Type = Ty;
2773  Steps.push_back(S);
2774}
2775
2776void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2777  assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2778
2779  Step S;
2780  S.Kind = SK_LValueToRValue;
2781  S.Type = Ty;
2782  Steps.push_back(S);
2783}
2784
2785void InitializationSequence::AddConversionSequenceStep(
2786    const ImplicitConversionSequence &ICS, QualType T,
2787    bool TopLevelOfInitList) {
2788  Step S;
2789  S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2790                              : SK_ConversionSequence;
2791  S.Type = T;
2792  S.ICS = new ImplicitConversionSequence(ICS);
2793  Steps.push_back(S);
2794}
2795
2796void InitializationSequence::AddListInitializationStep(QualType T) {
2797  Step S;
2798  S.Kind = SK_ListInitialization;
2799  S.Type = T;
2800  Steps.push_back(S);
2801}
2802
2803void
2804InitializationSequence
2805::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2806                                   AccessSpecifier Access,
2807                                   QualType T,
2808                                   bool HadMultipleCandidates,
2809                                   bool FromInitList, bool AsInitList) {
2810  Step S;
2811  S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2812                                       : SK_ConstructorInitialization;
2813  S.Type = T;
2814  S.Function.HadMultipleCandidates = HadMultipleCandidates;
2815  S.Function.Function = Constructor;
2816  S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2817  Steps.push_back(S);
2818}
2819
2820void InitializationSequence::AddZeroInitializationStep(QualType T) {
2821  Step S;
2822  S.Kind = SK_ZeroInitialization;
2823  S.Type = T;
2824  Steps.push_back(S);
2825}
2826
2827void InitializationSequence::AddCAssignmentStep(QualType T) {
2828  Step S;
2829  S.Kind = SK_CAssignment;
2830  S.Type = T;
2831  Steps.push_back(S);
2832}
2833
2834void InitializationSequence::AddStringInitStep(QualType T) {
2835  Step S;
2836  S.Kind = SK_StringInit;
2837  S.Type = T;
2838  Steps.push_back(S);
2839}
2840
2841void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2842  Step S;
2843  S.Kind = SK_ObjCObjectConversion;
2844  S.Type = T;
2845  Steps.push_back(S);
2846}
2847
2848void InitializationSequence::AddArrayInitStep(QualType T) {
2849  Step S;
2850  S.Kind = SK_ArrayInit;
2851  S.Type = T;
2852  Steps.push_back(S);
2853}
2854
2855void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2856  Step S;
2857  S.Kind = SK_ParenthesizedArrayInit;
2858  S.Type = T;
2859  Steps.push_back(S);
2860}
2861
2862void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2863                                                              bool shouldCopy) {
2864  Step s;
2865  s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2866                       : SK_PassByIndirectRestore);
2867  s.Type = type;
2868  Steps.push_back(s);
2869}
2870
2871void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2872  Step S;
2873  S.Kind = SK_ProduceObjCObject;
2874  S.Type = T;
2875  Steps.push_back(S);
2876}
2877
2878void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2879  Step S;
2880  S.Kind = SK_StdInitializerList;
2881  S.Type = T;
2882  Steps.push_back(S);
2883}
2884
2885void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2886  Step S;
2887  S.Kind = SK_OCLSamplerInit;
2888  S.Type = T;
2889  Steps.push_back(S);
2890}
2891
2892void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2893  Step S;
2894  S.Kind = SK_OCLZeroEvent;
2895  S.Type = T;
2896  Steps.push_back(S);
2897}
2898
2899void InitializationSequence::RewrapReferenceInitList(QualType T,
2900                                                     InitListExpr *Syntactic) {
2901  assert(Syntactic->getNumInits() == 1 &&
2902         "Can only rewrap trivial init lists.");
2903  Step S;
2904  S.Kind = SK_UnwrapInitList;
2905  S.Type = Syntactic->getInit(0)->getType();
2906  Steps.insert(Steps.begin(), S);
2907
2908  S.Kind = SK_RewrapInitList;
2909  S.Type = T;
2910  S.WrappingSyntacticList = Syntactic;
2911  Steps.push_back(S);
2912}
2913
2914void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2915                                                OverloadingResult Result) {
2916  setSequenceKind(FailedSequence);
2917  this->Failure = Failure;
2918  this->FailedOverloadResult = Result;
2919}
2920
2921//===----------------------------------------------------------------------===//
2922// Attempt initialization
2923//===----------------------------------------------------------------------===//
2924
2925static void MaybeProduceObjCObject(Sema &S,
2926                                   InitializationSequence &Sequence,
2927                                   const InitializedEntity &Entity) {
2928  if (!S.getLangOpts().ObjCAutoRefCount) return;
2929
2930  /// When initializing a parameter, produce the value if it's marked
2931  /// __attribute__((ns_consumed)).
2932  if (Entity.isParameterKind()) {
2933    if (!Entity.isParameterConsumed())
2934      return;
2935
2936    assert(Entity.getType()->isObjCRetainableType() &&
2937           "consuming an object of unretainable type?");
2938    Sequence.AddProduceObjCObjectStep(Entity.getType());
2939
2940  /// When initializing a return value, if the return type is a
2941  /// retainable type, then returns need to immediately retain the
2942  /// object.  If an autorelease is required, it will be done at the
2943  /// last instant.
2944  } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2945    if (!Entity.getType()->isObjCRetainableType())
2946      return;
2947
2948    Sequence.AddProduceObjCObjectStep(Entity.getType());
2949  }
2950}
2951
2952static void TryListInitialization(Sema &S,
2953                                  const InitializedEntity &Entity,
2954                                  const InitializationKind &Kind,
2955                                  InitListExpr *InitList,
2956                                  InitializationSequence &Sequence);
2957
2958/// \brief When initializing from init list via constructor, handle
2959/// initialization of an object of type std::initializer_list<T>.
2960///
2961/// \return true if we have handled initialization of an object of type
2962/// std::initializer_list<T>, false otherwise.
2963static bool TryInitializerListConstruction(Sema &S,
2964                                           InitListExpr *List,
2965                                           QualType DestType,
2966                                           InitializationSequence &Sequence) {
2967  QualType E;
2968  if (!S.isStdInitializerList(DestType, &E))
2969    return false;
2970
2971  if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
2972    Sequence.setIncompleteTypeFailure(E);
2973    return true;
2974  }
2975
2976  // Try initializing a temporary array from the init list.
2977  QualType ArrayType = S.Context.getConstantArrayType(
2978      E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
2979                                 List->getNumInits()),
2980      clang::ArrayType::Normal, 0);
2981  InitializedEntity HiddenArray =
2982      InitializedEntity::InitializeTemporary(ArrayType);
2983  InitializationKind Kind =
2984      InitializationKind::CreateDirectList(List->getExprLoc());
2985  TryListInitialization(S, HiddenArray, Kind, List, Sequence);
2986  if (Sequence)
2987    Sequence.AddStdInitializerListConstructionStep(DestType);
2988  return true;
2989}
2990
2991static OverloadingResult
2992ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
2993                           MultiExprArg Args,
2994                           OverloadCandidateSet &CandidateSet,
2995                           ArrayRef<NamedDecl *> Ctors,
2996                           OverloadCandidateSet::iterator &Best,
2997                           bool CopyInitializing, bool AllowExplicit,
2998                           bool OnlyListConstructors, bool InitListSyntax) {
2999  CandidateSet.clear();
3000
3001  for (ArrayRef<NamedDecl *>::iterator
3002         Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
3003    NamedDecl *D = *Con;
3004    DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3005    bool SuppressUserConversions = false;
3006
3007    // Find the constructor (which may be a template).
3008    CXXConstructorDecl *Constructor = 0;
3009    FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3010    if (ConstructorTmpl)
3011      Constructor = cast<CXXConstructorDecl>(
3012                                           ConstructorTmpl->getTemplatedDecl());
3013    else {
3014      Constructor = cast<CXXConstructorDecl>(D);
3015
3016      // C++11 [over.best.ics]p4:
3017      //   However, when considering the argument of a constructor or
3018      //   user-defined conversion function that is a candidate:
3019      //    -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3020      //       in the second step of a class copy-initialization,
3021      //    -- by 13.3.1.7 when passing the initializer list as a single
3022      //       argument or when the initializer list has exactly one elementand
3023      //       a conversion to some class X or reference to (possibly
3024      //       cv-qualified) X is considered for the first parameter of a
3025      //       constructor of X, or
3026      //    -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3027      //   only standard conversion sequences and ellipsis conversion sequences
3028      //   are considered.
3029      if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
3030          Constructor->isCopyOrMoveConstructor())
3031        SuppressUserConversions = true;
3032    }
3033
3034    if (!Constructor->isInvalidDecl() &&
3035        (AllowExplicit || !Constructor->isExplicit()) &&
3036        (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
3037      if (ConstructorTmpl)
3038        S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3039                                       /*ExplicitArgs*/ 0, Args,
3040                                       CandidateSet, SuppressUserConversions);
3041      else {
3042        // C++ [over.match.copy]p1:
3043        //   - When initializing a temporary to be bound to the first parameter
3044        //     of a constructor that takes a reference to possibly cv-qualified
3045        //     T as its first argument, called with a single argument in the
3046        //     context of direct-initialization, explicit conversion functions
3047        //     are also considered.
3048        bool AllowExplicitConv = AllowExplicit && !CopyInitializing &&
3049                                 Args.size() == 1 &&
3050                                 Constructor->isCopyOrMoveConstructor();
3051        S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
3052                               SuppressUserConversions,
3053                               /*PartialOverloading=*/false,
3054                               /*AllowExplicit=*/AllowExplicitConv);
3055      }
3056    }
3057  }
3058
3059  // Perform overload resolution and return the result.
3060  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3061}
3062
3063/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3064/// enumerates the constructors of the initialized entity and performs overload
3065/// resolution to select the best.
3066/// If InitListSyntax is true, this is list-initialization of a non-aggregate
3067/// class type.
3068static void TryConstructorInitialization(Sema &S,
3069                                         const InitializedEntity &Entity,
3070                                         const InitializationKind &Kind,
3071                                         MultiExprArg Args, QualType DestType,
3072                                         InitializationSequence &Sequence,
3073                                         bool InitListSyntax = false) {
3074  assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3075         "InitListSyntax must come with a single initializer list argument.");
3076
3077  // The type we're constructing needs to be complete.
3078  if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3079    Sequence.setIncompleteTypeFailure(DestType);
3080    return;
3081  }
3082
3083  const RecordType *DestRecordType = DestType->getAs<RecordType>();
3084  assert(DestRecordType && "Constructor initialization requires record type");
3085  CXXRecordDecl *DestRecordDecl
3086    = cast<CXXRecordDecl>(DestRecordType->getDecl());
3087
3088  // Build the candidate set directly in the initialization sequence
3089  // structure, so that it will persist if we fail.
3090  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3091
3092  // Determine whether we are allowed to call explicit constructors or
3093  // explicit conversion operators.
3094  bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
3095  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3096
3097  //   - Otherwise, if T is a class type, constructors are considered. The
3098  //     applicable constructors are enumerated, and the best one is chosen
3099  //     through overload resolution.
3100  DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
3101  // The container holding the constructors can under certain conditions
3102  // be changed while iterating (e.g. because of deserialization).
3103  // To be safe we copy the lookup results to a new container.
3104  SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3105
3106  OverloadingResult Result = OR_No_Viable_Function;
3107  OverloadCandidateSet::iterator Best;
3108  bool AsInitializerList = false;
3109
3110  // C++11 [over.match.list]p1:
3111  //   When objects of non-aggregate type T are list-initialized, overload
3112  //   resolution selects the constructor in two phases:
3113  //   - Initially, the candidate functions are the initializer-list
3114  //     constructors of the class T and the argument list consists of the
3115  //     initializer list as a single argument.
3116  if (InitListSyntax) {
3117    InitListExpr *ILE = cast<InitListExpr>(Args[0]);
3118    AsInitializerList = true;
3119
3120    // If the initializer list has no elements and T has a default constructor,
3121    // the first phase is omitted.
3122    if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
3123      Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3124                                          CandidateSet, Ctors, Best,
3125                                          CopyInitialization, AllowExplicit,
3126                                          /*OnlyListConstructor=*/true,
3127                                          InitListSyntax);
3128
3129    // Time to unwrap the init list.
3130    Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
3131  }
3132
3133  // C++11 [over.match.list]p1:
3134  //   - If no viable initializer-list constructor is found, overload resolution
3135  //     is performed again, where the candidate functions are all the
3136  //     constructors of the class T and the argument list consists of the
3137  //     elements of the initializer list.
3138  if (Result == OR_No_Viable_Function) {
3139    AsInitializerList = false;
3140    Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3141                                        CandidateSet, Ctors, Best,
3142                                        CopyInitialization, AllowExplicit,
3143                                        /*OnlyListConstructors=*/false,
3144                                        InitListSyntax);
3145  }
3146  if (Result) {
3147    Sequence.SetOverloadFailure(InitListSyntax ?
3148                      InitializationSequence::FK_ListConstructorOverloadFailed :
3149                      InitializationSequence::FK_ConstructorOverloadFailed,
3150                                Result);
3151    return;
3152  }
3153
3154  // C++11 [dcl.init]p6:
3155  //   If a program calls for the default initialization of an object
3156  //   of a const-qualified type T, T shall be a class type with a
3157  //   user-provided default constructor.
3158  if (Kind.getKind() == InitializationKind::IK_Default &&
3159      Entity.getType().isConstQualified() &&
3160      !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
3161    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3162    return;
3163  }
3164
3165  // C++11 [over.match.list]p1:
3166  //   In copy-list-initialization, if an explicit constructor is chosen, the
3167  //   initializer is ill-formed.
3168  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3169  if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3170    Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3171    return;
3172  }
3173
3174  // Add the constructor initialization step. Any cv-qualification conversion is
3175  // subsumed by the initialization.
3176  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3177  Sequence.AddConstructorInitializationStep(CtorDecl,
3178                                            Best->FoundDecl.getAccess(),
3179                                            DestType, HadMultipleCandidates,
3180                                            InitListSyntax, AsInitializerList);
3181}
3182
3183static bool
3184ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3185                                             Expr *Initializer,
3186                                             QualType &SourceType,
3187                                             QualType &UnqualifiedSourceType,
3188                                             QualType UnqualifiedTargetType,
3189                                             InitializationSequence &Sequence) {
3190  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3191        S.Context.OverloadTy) {
3192    DeclAccessPair Found;
3193    bool HadMultipleCandidates = false;
3194    if (FunctionDecl *Fn
3195        = S.ResolveAddressOfOverloadedFunction(Initializer,
3196                                               UnqualifiedTargetType,
3197                                               false, Found,
3198                                               &HadMultipleCandidates)) {
3199      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3200                                                HadMultipleCandidates);
3201      SourceType = Fn->getType();
3202      UnqualifiedSourceType = SourceType.getUnqualifiedType();
3203    } else if (!UnqualifiedTargetType->isRecordType()) {
3204      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3205      return true;
3206    }
3207  }
3208  return false;
3209}
3210
3211static void TryReferenceInitializationCore(Sema &S,
3212                                           const InitializedEntity &Entity,
3213                                           const InitializationKind &Kind,
3214                                           Expr *Initializer,
3215                                           QualType cv1T1, QualType T1,
3216                                           Qualifiers T1Quals,
3217                                           QualType cv2T2, QualType T2,
3218                                           Qualifiers T2Quals,
3219                                           InitializationSequence &Sequence);
3220
3221static void TryValueInitialization(Sema &S,
3222                                   const InitializedEntity &Entity,
3223                                   const InitializationKind &Kind,
3224                                   InitializationSequence &Sequence,
3225                                   InitListExpr *InitList = 0);
3226
3227/// \brief Attempt list initialization of a reference.
3228static void TryReferenceListInitialization(Sema &S,
3229                                           const InitializedEntity &Entity,
3230                                           const InitializationKind &Kind,
3231                                           InitListExpr *InitList,
3232                                           InitializationSequence &Sequence) {
3233  // First, catch C++03 where this isn't possible.
3234  if (!S.getLangOpts().CPlusPlus11) {
3235    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3236    return;
3237  }
3238
3239  QualType DestType = Entity.getType();
3240  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3241  Qualifiers T1Quals;
3242  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3243
3244  // Reference initialization via an initializer list works thus:
3245  // If the initializer list consists of a single element that is
3246  // reference-related to the referenced type, bind directly to that element
3247  // (possibly creating temporaries).
3248  // Otherwise, initialize a temporary with the initializer list and
3249  // bind to that.
3250  if (InitList->getNumInits() == 1) {
3251    Expr *Initializer = InitList->getInit(0);
3252    QualType cv2T2 = Initializer->getType();
3253    Qualifiers T2Quals;
3254    QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3255
3256    // If this fails, creating a temporary wouldn't work either.
3257    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3258                                                     T1, Sequence))
3259      return;
3260
3261    SourceLocation DeclLoc = Initializer->getLocStart();
3262    bool dummy1, dummy2, dummy3;
3263    Sema::ReferenceCompareResult RefRelationship
3264      = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3265                                       dummy2, dummy3);
3266    if (RefRelationship >= Sema::Ref_Related) {
3267      // Try to bind the reference here.
3268      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3269                                     T1Quals, cv2T2, T2, T2Quals, Sequence);
3270      if (Sequence)
3271        Sequence.RewrapReferenceInitList(cv1T1, InitList);
3272      return;
3273    }
3274
3275    // Update the initializer if we've resolved an overloaded function.
3276    if (Sequence.step_begin() != Sequence.step_end())
3277      Sequence.RewrapReferenceInitList(cv1T1, InitList);
3278  }
3279
3280  // Not reference-related. Create a temporary and bind to that.
3281  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3282
3283  TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3284  if (Sequence) {
3285    if (DestType->isRValueReferenceType() ||
3286        (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3287      Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3288    else
3289      Sequence.SetFailed(
3290          InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3291  }
3292}
3293
3294/// \brief Attempt list initialization (C++0x [dcl.init.list])
3295static void TryListInitialization(Sema &S,
3296                                  const InitializedEntity &Entity,
3297                                  const InitializationKind &Kind,
3298                                  InitListExpr *InitList,
3299                                  InitializationSequence &Sequence) {
3300  QualType DestType = Entity.getType();
3301
3302  // C++ doesn't allow scalar initialization with more than one argument.
3303  // But C99 complex numbers are scalars and it makes sense there.
3304  if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3305      !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3306    Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3307    return;
3308  }
3309  if (DestType->isReferenceType()) {
3310    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3311    return;
3312  }
3313  if (DestType->isRecordType()) {
3314    if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3315      Sequence.setIncompleteTypeFailure(DestType);
3316      return;
3317    }
3318
3319    // C++11 [dcl.init.list]p3:
3320    //   - If T is an aggregate, aggregate initialization is performed.
3321    if (!DestType->isAggregateType()) {
3322      if (S.getLangOpts().CPlusPlus11) {
3323        //   - Otherwise, if the initializer list has no elements and T is a
3324        //     class type with a default constructor, the object is
3325        //     value-initialized.
3326        if (InitList->getNumInits() == 0) {
3327          CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3328          if (RD->hasDefaultConstructor()) {
3329            TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3330            return;
3331          }
3332        }
3333
3334        //   - Otherwise, if T is a specialization of std::initializer_list<E>,
3335        //     an initializer_list object constructed [...]
3336        if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3337          return;
3338
3339        //   - Otherwise, if T is a class type, constructors are considered.
3340        Expr *InitListAsExpr = InitList;
3341        TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3342                                     Sequence, /*InitListSyntax*/true);
3343      } else
3344        Sequence.SetFailed(
3345            InitializationSequence::FK_InitListBadDestinationType);
3346      return;
3347    }
3348  }
3349
3350  InitListChecker CheckInitList(S, Entity, InitList,
3351          DestType, /*VerifyOnly=*/true);
3352  if (CheckInitList.HadError()) {
3353    Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3354    return;
3355  }
3356
3357  // Add the list initialization step with the built init list.
3358  Sequence.AddListInitializationStep(DestType);
3359}
3360
3361/// \brief Try a reference initialization that involves calling a conversion
3362/// function.
3363static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3364                                             const InitializedEntity &Entity,
3365                                             const InitializationKind &Kind,
3366                                             Expr *Initializer,
3367                                             bool AllowRValues,
3368                                             InitializationSequence &Sequence) {
3369  QualType DestType = Entity.getType();
3370  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3371  QualType T1 = cv1T1.getUnqualifiedType();
3372  QualType cv2T2 = Initializer->getType();
3373  QualType T2 = cv2T2.getUnqualifiedType();
3374
3375  bool DerivedToBase;
3376  bool ObjCConversion;
3377  bool ObjCLifetimeConversion;
3378  assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3379                                         T1, T2, DerivedToBase,
3380                                         ObjCConversion,
3381                                         ObjCLifetimeConversion) &&
3382         "Must have incompatible references when binding via conversion");
3383  (void)DerivedToBase;
3384  (void)ObjCConversion;
3385  (void)ObjCLifetimeConversion;
3386
3387  // Build the candidate set directly in the initialization sequence
3388  // structure, so that it will persist if we fail.
3389  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3390  CandidateSet.clear();
3391
3392  // Determine whether we are allowed to call explicit constructors or
3393  // explicit conversion operators.
3394  bool AllowExplicit = Kind.AllowExplicit();
3395  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3396
3397  const RecordType *T1RecordType = 0;
3398  if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3399      !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3400    // The type we're converting to is a class type. Enumerate its constructors
3401    // to see if there is a suitable conversion.
3402    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3403
3404    DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
3405    // The container holding the constructors can under certain conditions
3406    // be changed while iterating (e.g. because of deserialization).
3407    // To be safe we copy the lookup results to a new container.
3408    SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3409    for (SmallVectorImpl<NamedDecl *>::iterator
3410           CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3411      NamedDecl *D = *CI;
3412      DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3413
3414      // Find the constructor (which may be a template).
3415      CXXConstructorDecl *Constructor = 0;
3416      FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3417      if (ConstructorTmpl)
3418        Constructor = cast<CXXConstructorDecl>(
3419                                         ConstructorTmpl->getTemplatedDecl());
3420      else
3421        Constructor = cast<CXXConstructorDecl>(D);
3422
3423      if (!Constructor->isInvalidDecl() &&
3424          Constructor->isConvertingConstructor(AllowExplicit)) {
3425        if (ConstructorTmpl)
3426          S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3427                                         /*ExplicitArgs*/ 0,
3428                                         Initializer, CandidateSet,
3429                                         /*SuppressUserConversions=*/true);
3430        else
3431          S.AddOverloadCandidate(Constructor, FoundDecl,
3432                                 Initializer, CandidateSet,
3433                                 /*SuppressUserConversions=*/true);
3434      }
3435    }
3436  }
3437  if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3438    return OR_No_Viable_Function;
3439
3440  const RecordType *T2RecordType = 0;
3441  if ((T2RecordType = T2->getAs<RecordType>()) &&
3442      !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3443    // The type we're converting from is a class type, enumerate its conversion
3444    // functions.
3445    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3446
3447    std::pair<CXXRecordDecl::conversion_iterator,
3448              CXXRecordDecl::conversion_iterator>
3449      Conversions = T2RecordDecl->getVisibleConversionFunctions();
3450    for (CXXRecordDecl::conversion_iterator
3451           I = Conversions.first, E = Conversions.second; I != E; ++I) {
3452      NamedDecl *D = *I;
3453      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3454      if (isa<UsingShadowDecl>(D))
3455        D = cast<UsingShadowDecl>(D)->getTargetDecl();
3456
3457      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3458      CXXConversionDecl *Conv;
3459      if (ConvTemplate)
3460        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3461      else
3462        Conv = cast<CXXConversionDecl>(D);
3463
3464      // If the conversion function doesn't return a reference type,
3465      // it can't be considered for this conversion unless we're allowed to
3466      // consider rvalues.
3467      // FIXME: Do we need to make sure that we only consider conversion
3468      // candidates with reference-compatible results? That might be needed to
3469      // break recursion.
3470      if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3471          (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3472        if (ConvTemplate)
3473          S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3474                                           ActingDC, Initializer,
3475                                           DestType, CandidateSet);
3476        else
3477          S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3478                                   Initializer, DestType, CandidateSet);
3479      }
3480    }
3481  }
3482  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3483    return OR_No_Viable_Function;
3484
3485  SourceLocation DeclLoc = Initializer->getLocStart();
3486
3487  // Perform overload resolution. If it fails, return the failed result.
3488  OverloadCandidateSet::iterator Best;
3489  if (OverloadingResult Result
3490        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3491    return Result;
3492
3493  FunctionDecl *Function = Best->Function;
3494  // This is the overload that will be used for this initialization step if we
3495  // use this initialization. Mark it as referenced.
3496  Function->setReferenced();
3497
3498  // Compute the returned type of the conversion.
3499  if (isa<CXXConversionDecl>(Function))
3500    T2 = Function->getResultType();
3501  else
3502    T2 = cv1T1;
3503
3504  // Add the user-defined conversion step.
3505  bool HadMultipleCandidates = (CandidateSet.size() > 1);
3506  Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3507                                 T2.getNonLValueExprType(S.Context),
3508                                 HadMultipleCandidates);
3509
3510  // Determine whether we need to perform derived-to-base or
3511  // cv-qualification adjustments.
3512  ExprValueKind VK = VK_RValue;
3513  if (T2->isLValueReferenceType())
3514    VK = VK_LValue;
3515  else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3516    VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3517
3518  bool NewDerivedToBase = false;
3519  bool NewObjCConversion = false;
3520  bool NewObjCLifetimeConversion = false;
3521  Sema::ReferenceCompareResult NewRefRelationship
3522    = S.CompareReferenceRelationship(DeclLoc, T1,
3523                                     T2.getNonLValueExprType(S.Context),
3524                                     NewDerivedToBase, NewObjCConversion,
3525                                     NewObjCLifetimeConversion);
3526  if (NewRefRelationship == Sema::Ref_Incompatible) {
3527    // If the type we've converted to is not reference-related to the
3528    // type we're looking for, then there is another conversion step
3529    // we need to perform to produce a temporary of the right type
3530    // that we'll be binding to.
3531    ImplicitConversionSequence ICS;
3532    ICS.setStandard();
3533    ICS.Standard = Best->FinalConversion;
3534    T2 = ICS.Standard.getToType(2);
3535    Sequence.AddConversionSequenceStep(ICS, T2);
3536  } else if (NewDerivedToBase)
3537    Sequence.AddDerivedToBaseCastStep(
3538                                S.Context.getQualifiedType(T1,
3539                                  T2.getNonReferenceType().getQualifiers()),
3540                                      VK);
3541  else if (NewObjCConversion)
3542    Sequence.AddObjCObjectConversionStep(
3543                                S.Context.getQualifiedType(T1,
3544                                  T2.getNonReferenceType().getQualifiers()));
3545
3546  if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3547    Sequence.AddQualificationConversionStep(cv1T1, VK);
3548
3549  Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3550  return OR_Success;
3551}
3552
3553static void CheckCXX98CompatAccessibleCopy(Sema &S,
3554                                           const InitializedEntity &Entity,
3555                                           Expr *CurInitExpr);
3556
3557/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3558static void TryReferenceInitialization(Sema &S,
3559                                       const InitializedEntity &Entity,
3560                                       const InitializationKind &Kind,
3561                                       Expr *Initializer,
3562                                       InitializationSequence &Sequence) {
3563  QualType DestType = Entity.getType();
3564  QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3565  Qualifiers T1Quals;
3566  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3567  QualType cv2T2 = Initializer->getType();
3568  Qualifiers T2Quals;
3569  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3570
3571  // If the initializer is the address of an overloaded function, try
3572  // to resolve the overloaded function. If all goes well, T2 is the
3573  // type of the resulting function.
3574  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3575                                                   T1, Sequence))
3576    return;
3577
3578  // Delegate everything else to a subfunction.
3579  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3580                                 T1Quals, cv2T2, T2, T2Quals, Sequence);
3581}
3582
3583/// Converts the target of reference initialization so that it has the
3584/// appropriate qualifiers and value kind.
3585///
3586/// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3587/// \code
3588///   int x;
3589///   const int &r = x;
3590/// \endcode
3591///
3592/// In this case the reference is binding to a bitfield lvalue, which isn't
3593/// valid. Perform a load to create a lifetime-extended temporary instead.
3594/// \code
3595///   const int &r = someStruct.bitfield;
3596/// \endcode
3597static ExprValueKind
3598convertQualifiersAndValueKindIfNecessary(Sema &S,
3599                                         InitializationSequence &Sequence,
3600                                         Expr *Initializer,
3601                                         QualType cv1T1,
3602                                         Qualifiers T1Quals,
3603                                         Qualifiers T2Quals,
3604                                         bool IsLValueRef) {
3605  bool IsNonAddressableType = Initializer->refersToBitField() ||
3606                              Initializer->refersToVectorElement();
3607
3608  if (IsNonAddressableType) {
3609    // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3610    // lvalue reference to a non-volatile const type, or the reference shall be
3611    // an rvalue reference.
3612    //
3613    // If not, we can't make a temporary and bind to that. Give up and allow the
3614    // error to be diagnosed later.
3615    if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3616      assert(Initializer->isGLValue());
3617      return Initializer->getValueKind();
3618    }
3619
3620    // Force a load so we can materialize a temporary.
3621    Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3622    return VK_RValue;
3623  }
3624
3625  if (T1Quals != T2Quals) {
3626    Sequence.AddQualificationConversionStep(cv1T1,
3627                                            Initializer->getValueKind());
3628  }
3629
3630  return Initializer->getValueKind();
3631}
3632
3633
3634/// \brief Reference initialization without resolving overloaded functions.
3635static void TryReferenceInitializationCore(Sema &S,
3636                                           const InitializedEntity &Entity,
3637                                           const InitializationKind &Kind,
3638                                           Expr *Initializer,
3639                                           QualType cv1T1, QualType T1,
3640                                           Qualifiers T1Quals,
3641                                           QualType cv2T2, QualType T2,
3642                                           Qualifiers T2Quals,
3643                                           InitializationSequence &Sequence) {
3644  QualType DestType = Entity.getType();
3645  SourceLocation DeclLoc = Initializer->getLocStart();
3646  // Compute some basic properties of the types and the initializer.
3647  bool isLValueRef = DestType->isLValueReferenceType();
3648  bool isRValueRef = !isLValueRef;
3649  bool DerivedToBase = false;
3650  bool ObjCConversion = false;
3651  bool ObjCLifetimeConversion = false;
3652  Expr::Classification InitCategory = Initializer->Classify(S.Context);
3653  Sema::ReferenceCompareResult RefRelationship
3654    = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3655                                     ObjCConversion, ObjCLifetimeConversion);
3656
3657  // C++0x [dcl.init.ref]p5:
3658  //   A reference to type "cv1 T1" is initialized by an expression of type
3659  //   "cv2 T2" as follows:
3660  //
3661  //     - If the reference is an lvalue reference and the initializer
3662  //       expression
3663  // Note the analogous bullet points for rvalue refs to functions. Because
3664  // there are no function rvalues in C++, rvalue refs to functions are treated
3665  // like lvalue refs.
3666  OverloadingResult ConvOvlResult = OR_Success;
3667  bool T1Function = T1->isFunctionType();
3668  if (isLValueRef || T1Function) {
3669    if (InitCategory.isLValue() &&
3670        (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3671         (Kind.isCStyleOrFunctionalCast() &&
3672          RefRelationship == Sema::Ref_Related))) {
3673      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3674      //     reference-compatible with "cv2 T2," or
3675      //
3676      // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3677      // bit-field when we're determining whether the reference initialization
3678      // can occur. However, we do pay attention to whether it is a bit-field
3679      // to decide whether we're actually binding to a temporary created from
3680      // the bit-field.
3681      if (DerivedToBase)
3682        Sequence.AddDerivedToBaseCastStep(
3683                         S.Context.getQualifiedType(T1, T2Quals),
3684                         VK_LValue);
3685      else if (ObjCConversion)
3686        Sequence.AddObjCObjectConversionStep(
3687                                     S.Context.getQualifiedType(T1, T2Quals));
3688
3689      ExprValueKind ValueKind =
3690        convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3691                                                 cv1T1, T1Quals, T2Quals,
3692                                                 isLValueRef);
3693      Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3694      return;
3695    }
3696
3697    //     - has a class type (i.e., T2 is a class type), where T1 is not
3698    //       reference-related to T2, and can be implicitly converted to an
3699    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3700    //       with "cv3 T3" (this conversion is selected by enumerating the
3701    //       applicable conversion functions (13.3.1.6) and choosing the best
3702    //       one through overload resolution (13.3)),
3703    // If we have an rvalue ref to function type here, the rhs must be
3704    // an rvalue. DR1287 removed the "implicitly" here.
3705    if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3706        (isLValueRef || InitCategory.isRValue())) {
3707      ConvOvlResult = TryRefInitWithConversionFunction(
3708          S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
3709      if (ConvOvlResult == OR_Success)
3710        return;
3711      if (ConvOvlResult != OR_No_Viable_Function)
3712        Sequence.SetOverloadFailure(
3713            InitializationSequence::FK_ReferenceInitOverloadFailed,
3714            ConvOvlResult);
3715    }
3716  }
3717
3718  //     - Otherwise, the reference shall be an lvalue reference to a
3719  //       non-volatile const type (i.e., cv1 shall be const), or the reference
3720  //       shall be an rvalue reference.
3721  if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3722    if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3723      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3724    else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3725      Sequence.SetOverloadFailure(
3726                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3727                                  ConvOvlResult);
3728    else
3729      Sequence.SetFailed(InitCategory.isLValue()
3730        ? (RefRelationship == Sema::Ref_Related
3731             ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3732             : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3733        : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3734
3735    return;
3736  }
3737
3738  //    - If the initializer expression
3739  //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3740  //        "cv1 T1" is reference-compatible with "cv2 T2"
3741  // Note: functions are handled below.
3742  if (!T1Function &&
3743      (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3744       (Kind.isCStyleOrFunctionalCast() &&
3745        RefRelationship == Sema::Ref_Related)) &&
3746      (InitCategory.isXValue() ||
3747       (InitCategory.isPRValue() && T2->isRecordType()) ||
3748       (InitCategory.isPRValue() && T2->isArrayType()))) {
3749    ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3750    if (InitCategory.isPRValue() && T2->isRecordType()) {
3751      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3752      // compiler the freedom to perform a copy here or bind to the
3753      // object, while C++0x requires that we bind directly to the
3754      // object. Hence, we always bind to the object without making an
3755      // extra copy. However, in C++03 requires that we check for the
3756      // presence of a suitable copy constructor:
3757      //
3758      //   The constructor that would be used to make the copy shall
3759      //   be callable whether or not the copy is actually done.
3760      if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
3761        Sequence.AddExtraneousCopyToTemporary(cv2T2);
3762      else if (S.getLangOpts().CPlusPlus11)
3763        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3764    }
3765
3766    if (DerivedToBase)
3767      Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3768                                        ValueKind);
3769    else if (ObjCConversion)
3770      Sequence.AddObjCObjectConversionStep(
3771                                       S.Context.getQualifiedType(T1, T2Quals));
3772
3773    ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3774                                                         Initializer, cv1T1,
3775                                                         T1Quals, T2Quals,
3776                                                         isLValueRef);
3777
3778    Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3779    return;
3780  }
3781
3782  //       - has a class type (i.e., T2 is a class type), where T1 is not
3783  //         reference-related to T2, and can be implicitly converted to an
3784  //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
3785  //         where "cv1 T1" is reference-compatible with "cv3 T3",
3786  //
3787  // DR1287 removes the "implicitly" here.
3788  if (T2->isRecordType()) {
3789    if (RefRelationship == Sema::Ref_Incompatible) {
3790      ConvOvlResult = TryRefInitWithConversionFunction(
3791          S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
3792      if (ConvOvlResult)
3793        Sequence.SetOverloadFailure(
3794            InitializationSequence::FK_ReferenceInitOverloadFailed,
3795            ConvOvlResult);
3796
3797      return;
3798    }
3799
3800    if ((RefRelationship == Sema::Ref_Compatible ||
3801         RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3802        isRValueRef && InitCategory.isLValue()) {
3803      Sequence.SetFailed(
3804        InitializationSequence::FK_RValueReferenceBindingToLValue);
3805      return;
3806    }
3807
3808    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3809    return;
3810  }
3811
3812  //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
3813  //        from the initializer expression using the rules for a non-reference
3814  //        copy-initialization (8.5). The reference is then bound to the
3815  //        temporary. [...]
3816
3817  InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3818
3819  // FIXME: Why do we use an implicit conversion here rather than trying
3820  // copy-initialization?
3821  ImplicitConversionSequence ICS
3822    = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3823                              /*SuppressUserConversions=*/false,
3824                              /*AllowExplicit=*/false,
3825                              /*FIXME:InOverloadResolution=*/false,
3826                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3827                              /*AllowObjCWritebackConversion=*/false);
3828
3829  if (ICS.isBad()) {
3830    // FIXME: Use the conversion function set stored in ICS to turn
3831    // this into an overloading ambiguity diagnostic. However, we need
3832    // to keep that set as an OverloadCandidateSet rather than as some
3833    // other kind of set.
3834    if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3835      Sequence.SetOverloadFailure(
3836                        InitializationSequence::FK_ReferenceInitOverloadFailed,
3837                                  ConvOvlResult);
3838    else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3839      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3840    else
3841      Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3842    return;
3843  } else {
3844    Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3845  }
3846
3847  //        [...] If T1 is reference-related to T2, cv1 must be the
3848  //        same cv-qualification as, or greater cv-qualification
3849  //        than, cv2; otherwise, the program is ill-formed.
3850  unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3851  unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3852  if (RefRelationship == Sema::Ref_Related &&
3853      (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3854    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3855    return;
3856  }
3857
3858  //   [...] If T1 is reference-related to T2 and the reference is an rvalue
3859  //   reference, the initializer expression shall not be an lvalue.
3860  if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3861      InitCategory.isLValue()) {
3862    Sequence.SetFailed(
3863                    InitializationSequence::FK_RValueReferenceBindingToLValue);
3864    return;
3865  }
3866
3867  Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3868  return;
3869}
3870
3871/// \brief Attempt character array initialization from a string literal
3872/// (C++ [dcl.init.string], C99 6.7.8).
3873static void TryStringLiteralInitialization(Sema &S,
3874                                           const InitializedEntity &Entity,
3875                                           const InitializationKind &Kind,
3876                                           Expr *Initializer,
3877                                       InitializationSequence &Sequence) {
3878  Sequence.AddStringInitStep(Entity.getType());
3879}
3880
3881/// \brief Attempt value initialization (C++ [dcl.init]p7).
3882static void TryValueInitialization(Sema &S,
3883                                   const InitializedEntity &Entity,
3884                                   const InitializationKind &Kind,
3885                                   InitializationSequence &Sequence,
3886                                   InitListExpr *InitList) {
3887  assert((!InitList || InitList->getNumInits() == 0) &&
3888         "Shouldn't use value-init for non-empty init lists");
3889
3890  // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3891  //
3892  //   To value-initialize an object of type T means:
3893  QualType T = Entity.getType();
3894
3895  //     -- if T is an array type, then each element is value-initialized;
3896  T = S.Context.getBaseElementType(T);
3897
3898  if (const RecordType *RT = T->getAs<RecordType>()) {
3899    if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3900      bool NeedZeroInitialization = true;
3901      if (!S.getLangOpts().CPlusPlus11) {
3902        // C++98:
3903        // -- if T is a class type (clause 9) with a user-declared constructor
3904        //    (12.1), then the default constructor for T is called (and the
3905        //    initialization is ill-formed if T has no accessible default
3906        //    constructor);
3907        if (ClassDecl->hasUserDeclaredConstructor())
3908          NeedZeroInitialization = false;
3909      } else {
3910        // C++11:
3911        // -- if T is a class type (clause 9) with either no default constructor
3912        //    (12.1 [class.ctor]) or a default constructor that is user-provided
3913        //    or deleted, then the object is default-initialized;
3914        CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3915        if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3916          NeedZeroInitialization = false;
3917      }
3918
3919      // -- if T is a (possibly cv-qualified) non-union class type without a
3920      //    user-provided or deleted default constructor, then the object is
3921      //    zero-initialized and, if T has a non-trivial default constructor,
3922      //    default-initialized;
3923      // The 'non-union' here was removed by DR1502. The 'non-trivial default
3924      // constructor' part was removed by DR1507.
3925      if (NeedZeroInitialization)
3926        Sequence.AddZeroInitializationStep(Entity.getType());
3927
3928      // C++03:
3929      // -- if T is a non-union class type without a user-declared constructor,
3930      //    then every non-static data member and base class component of T is
3931      //    value-initialized;
3932      // [...] A program that calls for [...] value-initialization of an
3933      // entity of reference type is ill-formed.
3934      //
3935      // C++11 doesn't need this handling, because value-initialization does not
3936      // occur recursively there, and the implicit default constructor is
3937      // defined as deleted in the problematic cases.
3938      if (!S.getLangOpts().CPlusPlus11 &&
3939          ClassDecl->hasUninitializedReferenceMember()) {
3940        Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3941        return;
3942      }
3943
3944      // If this is list-value-initialization, pass the empty init list on when
3945      // building the constructor call. This affects the semantics of a few
3946      // things (such as whether an explicit default constructor can be called).
3947      Expr *InitListAsExpr = InitList;
3948      MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
3949      bool InitListSyntax = InitList;
3950
3951      return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
3952                                          InitListSyntax);
3953    }
3954  }
3955
3956  Sequence.AddZeroInitializationStep(Entity.getType());
3957}
3958
3959/// \brief Attempt default initialization (C++ [dcl.init]p6).
3960static void TryDefaultInitialization(Sema &S,
3961                                     const InitializedEntity &Entity,
3962                                     const InitializationKind &Kind,
3963                                     InitializationSequence &Sequence) {
3964  assert(Kind.getKind() == InitializationKind::IK_Default);
3965
3966  // C++ [dcl.init]p6:
3967  //   To default-initialize an object of type T means:
3968  //     - if T is an array type, each element is default-initialized;
3969  QualType DestType = S.Context.getBaseElementType(Entity.getType());
3970
3971  //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
3972  //       constructor for T is called (and the initialization is ill-formed if
3973  //       T has no accessible default constructor);
3974  if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
3975    TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
3976    return;
3977  }
3978
3979  //     - otherwise, no initialization is performed.
3980
3981  //   If a program calls for the default initialization of an object of
3982  //   a const-qualified type T, T shall be a class type with a user-provided
3983  //   default constructor.
3984  if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
3985    Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3986    return;
3987  }
3988
3989  // If the destination type has a lifetime property, zero-initialize it.
3990  if (DestType.getQualifiers().hasObjCLifetime()) {
3991    Sequence.AddZeroInitializationStep(Entity.getType());
3992    return;
3993  }
3994}
3995
3996/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3997/// which enumerates all conversion functions and performs overload resolution
3998/// to select the best.
3999static void TryUserDefinedConversion(Sema &S,
4000                                     const InitializedEntity &Entity,
4001                                     const InitializationKind &Kind,
4002                                     Expr *Initializer,
4003                                     InitializationSequence &Sequence,
4004                                     bool TopLevelOfInitList) {
4005  QualType DestType = Entity.getType();
4006  assert(!DestType->isReferenceType() && "References are handled elsewhere");
4007  QualType SourceType = Initializer->getType();
4008  assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4009         "Must have a class type to perform a user-defined conversion");
4010
4011  // Build the candidate set directly in the initialization sequence
4012  // structure, so that it will persist if we fail.
4013  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4014  CandidateSet.clear();
4015
4016  // Determine whether we are allowed to call explicit constructors or
4017  // explicit conversion operators.
4018  bool AllowExplicit = Kind.AllowExplicit();
4019
4020  if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4021    // The type we're converting to is a class type. Enumerate its constructors
4022    // to see if there is a suitable conversion.
4023    CXXRecordDecl *DestRecordDecl
4024      = cast<CXXRecordDecl>(DestRecordType->getDecl());
4025
4026    // Try to complete the type we're converting to.
4027    if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
4028      DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
4029      // The container holding the constructors can under certain conditions
4030      // be changed while iterating. To be safe we copy the lookup results
4031      // to a new container.
4032      SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
4033      for (SmallVectorImpl<NamedDecl *>::iterator
4034             Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
4035           Con != ConEnd; ++Con) {
4036        NamedDecl *D = *Con;
4037        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
4038
4039        // Find the constructor (which may be a template).
4040        CXXConstructorDecl *Constructor = 0;
4041        FunctionTemplateDecl *ConstructorTmpl
4042          = dyn_cast<FunctionTemplateDecl>(D);
4043        if (ConstructorTmpl)
4044          Constructor = cast<CXXConstructorDecl>(
4045                                           ConstructorTmpl->getTemplatedDecl());
4046        else
4047          Constructor = cast<CXXConstructorDecl>(D);
4048
4049        if (!Constructor->isInvalidDecl() &&
4050            Constructor->isConvertingConstructor(AllowExplicit)) {
4051          if (ConstructorTmpl)
4052            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4053                                           /*ExplicitArgs*/ 0,
4054                                           Initializer, CandidateSet,
4055                                           /*SuppressUserConversions=*/true);
4056          else
4057            S.AddOverloadCandidate(Constructor, FoundDecl,
4058                                   Initializer, CandidateSet,
4059                                   /*SuppressUserConversions=*/true);
4060        }
4061      }
4062    }
4063  }
4064
4065  SourceLocation DeclLoc = Initializer->getLocStart();
4066
4067  if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4068    // The type we're converting from is a class type, enumerate its conversion
4069    // functions.
4070
4071    // We can only enumerate the conversion functions for a complete type; if
4072    // the type isn't complete, simply skip this step.
4073    if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4074      CXXRecordDecl *SourceRecordDecl
4075        = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4076
4077      std::pair<CXXRecordDecl::conversion_iterator,
4078                CXXRecordDecl::conversion_iterator>
4079        Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4080      for (CXXRecordDecl::conversion_iterator
4081             I = Conversions.first, E = Conversions.second; I != E; ++I) {
4082        NamedDecl *D = *I;
4083        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4084        if (isa<UsingShadowDecl>(D))
4085          D = cast<UsingShadowDecl>(D)->getTargetDecl();
4086
4087        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4088        CXXConversionDecl *Conv;
4089        if (ConvTemplate)
4090          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4091        else
4092          Conv = cast<CXXConversionDecl>(D);
4093
4094        if (AllowExplicit || !Conv->isExplicit()) {
4095          if (ConvTemplate)
4096            S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4097                                             ActingDC, Initializer, DestType,
4098                                             CandidateSet);
4099          else
4100            S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4101                                     Initializer, DestType, CandidateSet);
4102        }
4103      }
4104    }
4105  }
4106
4107  // Perform overload resolution. If it fails, return the failed result.
4108  OverloadCandidateSet::iterator Best;
4109  if (OverloadingResult Result
4110        = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4111    Sequence.SetOverloadFailure(
4112                        InitializationSequence::FK_UserConversionOverloadFailed,
4113                                Result);
4114    return;
4115  }
4116
4117  FunctionDecl *Function = Best->Function;
4118  Function->setReferenced();
4119  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4120
4121  if (isa<CXXConstructorDecl>(Function)) {
4122    // Add the user-defined conversion step. Any cv-qualification conversion is
4123    // subsumed by the initialization. Per DR5, the created temporary is of the
4124    // cv-unqualified type of the destination.
4125    Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4126                                   DestType.getUnqualifiedType(),
4127                                   HadMultipleCandidates);
4128    return;
4129  }
4130
4131  // Add the user-defined conversion step that calls the conversion function.
4132  QualType ConvType = Function->getCallResultType();
4133  if (ConvType->getAs<RecordType>()) {
4134    // If we're converting to a class type, there may be an copy of
4135    // the resulting temporary object (possible to create an object of
4136    // a base class type). That copy is not a separate conversion, so
4137    // we just make a note of the actual destination type (possibly a
4138    // base class of the type returned by the conversion function) and
4139    // let the user-defined conversion step handle the conversion.
4140    Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4141                                   HadMultipleCandidates);
4142    return;
4143  }
4144
4145  Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4146                                 HadMultipleCandidates);
4147
4148  // If the conversion following the call to the conversion function
4149  // is interesting, add it as a separate step.
4150  if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4151      Best->FinalConversion.Third) {
4152    ImplicitConversionSequence ICS;
4153    ICS.setStandard();
4154    ICS.Standard = Best->FinalConversion;
4155    Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4156  }
4157}
4158
4159/// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4160/// a function with a pointer return type contains a 'return false;' statement.
4161/// In C++11, 'false' is not a null pointer, so this breaks the build of any
4162/// code using that header.
4163///
4164/// Work around this by treating 'return false;' as zero-initializing the result
4165/// if it's used in a pointer-returning function in a system header.
4166static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4167                                              const InitializedEntity &Entity,
4168                                              const Expr *Init) {
4169  return S.getLangOpts().CPlusPlus11 &&
4170         Entity.getKind() == InitializedEntity::EK_Result &&
4171         Entity.getType()->isPointerType() &&
4172         isa<CXXBoolLiteralExpr>(Init) &&
4173         !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4174         S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4175}
4176
4177/// The non-zero enum values here are indexes into diagnostic alternatives.
4178enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4179
4180/// Determines whether this expression is an acceptable ICR source.
4181static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4182                                         bool isAddressOf, bool &isWeakAccess) {
4183  // Skip parens.
4184  e = e->IgnoreParens();
4185
4186  // Skip address-of nodes.
4187  if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4188    if (op->getOpcode() == UO_AddrOf)
4189      return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4190                                isWeakAccess);
4191
4192  // Skip certain casts.
4193  } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4194    switch (ce->getCastKind()) {
4195    case CK_Dependent:
4196    case CK_BitCast:
4197    case CK_LValueBitCast:
4198    case CK_NoOp:
4199      return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4200
4201    case CK_ArrayToPointerDecay:
4202      return IIK_nonscalar;
4203
4204    case CK_NullToPointer:
4205      return IIK_okay;
4206
4207    default:
4208      break;
4209    }
4210
4211  // If we have a declaration reference, it had better be a local variable.
4212  } else if (isa<DeclRefExpr>(e)) {
4213    // set isWeakAccess to true, to mean that there will be an implicit
4214    // load which requires a cleanup.
4215    if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4216      isWeakAccess = true;
4217
4218    if (!isAddressOf) return IIK_nonlocal;
4219
4220    VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4221    if (!var) return IIK_nonlocal;
4222
4223    return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4224
4225  // If we have a conditional operator, check both sides.
4226  } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4227    if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4228                                                isWeakAccess))
4229      return iik;
4230
4231    return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4232
4233  // These are never scalar.
4234  } else if (isa<ArraySubscriptExpr>(e)) {
4235    return IIK_nonscalar;
4236
4237  // Otherwise, it needs to be a null pointer constant.
4238  } else {
4239    return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4240            ? IIK_okay : IIK_nonlocal);
4241  }
4242
4243  return IIK_nonlocal;
4244}
4245
4246/// Check whether the given expression is a valid operand for an
4247/// indirect copy/restore.
4248static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4249  assert(src->isRValue());
4250  bool isWeakAccess = false;
4251  InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4252  // If isWeakAccess to true, there will be an implicit
4253  // load which requires a cleanup.
4254  if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4255    S.ExprNeedsCleanups = true;
4256
4257  if (iik == IIK_okay) return;
4258
4259  S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4260    << ((unsigned) iik - 1)  // shift index into diagnostic explanations
4261    << src->getSourceRange();
4262}
4263
4264/// \brief Determine whether we have compatible array types for the
4265/// purposes of GNU by-copy array initialization.
4266static bool hasCompatibleArrayTypes(ASTContext &Context,
4267                                    const ArrayType *Dest,
4268                                    const ArrayType *Source) {
4269  // If the source and destination array types are equivalent, we're
4270  // done.
4271  if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4272    return true;
4273
4274  // Make sure that the element types are the same.
4275  if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4276    return false;
4277
4278  // The only mismatch we allow is when the destination is an
4279  // incomplete array type and the source is a constant array type.
4280  return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4281}
4282
4283static bool tryObjCWritebackConversion(Sema &S,
4284                                       InitializationSequence &Sequence,
4285                                       const InitializedEntity &Entity,
4286                                       Expr *Initializer) {
4287  bool ArrayDecay = false;
4288  QualType ArgType = Initializer->getType();
4289  QualType ArgPointee;
4290  if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4291    ArrayDecay = true;
4292    ArgPointee = ArgArrayType->getElementType();
4293    ArgType = S.Context.getPointerType(ArgPointee);
4294  }
4295
4296  // Handle write-back conversion.
4297  QualType ConvertedArgType;
4298  if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4299                                   ConvertedArgType))
4300    return false;
4301
4302  // We should copy unless we're passing to an argument explicitly
4303  // marked 'out'.
4304  bool ShouldCopy = true;
4305  if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4306    ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4307
4308  // Do we need an lvalue conversion?
4309  if (ArrayDecay || Initializer->isGLValue()) {
4310    ImplicitConversionSequence ICS;
4311    ICS.setStandard();
4312    ICS.Standard.setAsIdentityConversion();
4313
4314    QualType ResultType;
4315    if (ArrayDecay) {
4316      ICS.Standard.First = ICK_Array_To_Pointer;
4317      ResultType = S.Context.getPointerType(ArgPointee);
4318    } else {
4319      ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4320      ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4321    }
4322
4323    Sequence.AddConversionSequenceStep(ICS, ResultType);
4324  }
4325
4326  Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4327  return true;
4328}
4329
4330static bool TryOCLSamplerInitialization(Sema &S,
4331                                        InitializationSequence &Sequence,
4332                                        QualType DestType,
4333                                        Expr *Initializer) {
4334  if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4335    !Initializer->isIntegerConstantExpr(S.getASTContext()))
4336    return false;
4337
4338  Sequence.AddOCLSamplerInitStep(DestType);
4339  return true;
4340}
4341
4342//
4343// OpenCL 1.2 spec, s6.12.10
4344//
4345// The event argument can also be used to associate the
4346// async_work_group_copy with a previous async copy allowing
4347// an event to be shared by multiple async copies; otherwise
4348// event should be zero.
4349//
4350static bool TryOCLZeroEventInitialization(Sema &S,
4351                                          InitializationSequence &Sequence,
4352                                          QualType DestType,
4353                                          Expr *Initializer) {
4354  if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4355      !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4356      (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4357    return false;
4358
4359  Sequence.AddOCLZeroEventStep(DestType);
4360  return true;
4361}
4362
4363InitializationSequence::InitializationSequence(Sema &S,
4364                                               const InitializedEntity &Entity,
4365                                               const InitializationKind &Kind,
4366                                               MultiExprArg Args,
4367                                               bool TopLevelOfInitList)
4368    : FailedCandidateSet(Kind.getLocation()) {
4369  ASTContext &Context = S.Context;
4370
4371  // Eliminate non-overload placeholder types in the arguments.  We
4372  // need to do this before checking whether types are dependent
4373  // because lowering a pseudo-object expression might well give us
4374  // something of dependent type.
4375  for (unsigned I = 0, E = Args.size(); I != E; ++I)
4376    if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4377      // FIXME: should we be doing this here?
4378      ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4379      if (result.isInvalid()) {
4380        SetFailed(FK_PlaceholderType);
4381        return;
4382      }
4383      Args[I] = result.take();
4384    }
4385
4386  // C++0x [dcl.init]p16:
4387  //   The semantics of initializers are as follows. The destination type is
4388  //   the type of the object or reference being initialized and the source
4389  //   type is the type of the initializer expression. The source type is not
4390  //   defined when the initializer is a braced-init-list or when it is a
4391  //   parenthesized list of expressions.
4392  QualType DestType = Entity.getType();
4393
4394  if (DestType->isDependentType() ||
4395      Expr::hasAnyTypeDependentArguments(Args)) {
4396    SequenceKind = DependentSequence;
4397    return;
4398  }
4399
4400  // Almost everything is a normal sequence.
4401  setSequenceKind(NormalSequence);
4402
4403  QualType SourceType;
4404  Expr *Initializer = 0;
4405  if (Args.size() == 1) {
4406    Initializer = Args[0];
4407    if (!isa<InitListExpr>(Initializer))
4408      SourceType = Initializer->getType();
4409  }
4410
4411  //     - If the initializer is a (non-parenthesized) braced-init-list, the
4412  //       object is list-initialized (8.5.4).
4413  if (Kind.getKind() != InitializationKind::IK_Direct) {
4414    if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4415      TryListInitialization(S, Entity, Kind, InitList, *this);
4416      return;
4417    }
4418  }
4419
4420  //     - If the destination type is a reference type, see 8.5.3.
4421  if (DestType->isReferenceType()) {
4422    // C++0x [dcl.init.ref]p1:
4423    //   A variable declared to be a T& or T&&, that is, "reference to type T"
4424    //   (8.3.2), shall be initialized by an object, or function, of type T or
4425    //   by an object that can be converted into a T.
4426    // (Therefore, multiple arguments are not permitted.)
4427    if (Args.size() != 1)
4428      SetFailed(FK_TooManyInitsForReference);
4429    else
4430      TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4431    return;
4432  }
4433
4434  //     - If the initializer is (), the object is value-initialized.
4435  if (Kind.getKind() == InitializationKind::IK_Value ||
4436      (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
4437    TryValueInitialization(S, Entity, Kind, *this);
4438    return;
4439  }
4440
4441  // Handle default initialization.
4442  if (Kind.getKind() == InitializationKind::IK_Default) {
4443    TryDefaultInitialization(S, Entity, Kind, *this);
4444    return;
4445  }
4446
4447  //     - If the destination type is an array of characters, an array of
4448  //       char16_t, an array of char32_t, or an array of wchar_t, and the
4449  //       initializer is a string literal, see 8.5.2.
4450  //     - Otherwise, if the destination type is an array, the program is
4451  //       ill-formed.
4452  if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4453    if (Initializer && isa<VariableArrayType>(DestAT)) {
4454      SetFailed(FK_VariableLengthArrayHasInitializer);
4455      return;
4456    }
4457
4458    if (Initializer) {
4459      switch (IsStringInit(Initializer, DestAT, Context)) {
4460      case SIF_None:
4461        TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4462        return;
4463      case SIF_NarrowStringIntoWideChar:
4464        SetFailed(FK_NarrowStringIntoWideCharArray);
4465        return;
4466      case SIF_WideStringIntoChar:
4467        SetFailed(FK_WideStringIntoCharArray);
4468        return;
4469      case SIF_IncompatWideStringIntoWideChar:
4470        SetFailed(FK_IncompatWideStringIntoWideChar);
4471        return;
4472      case SIF_Other:
4473        break;
4474      }
4475    }
4476
4477    // Note: as an GNU C extension, we allow initialization of an
4478    // array from a compound literal that creates an array of the same
4479    // type, so long as the initializer has no side effects.
4480    if (!S.getLangOpts().CPlusPlus && Initializer &&
4481        isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4482        Initializer->getType()->isArrayType()) {
4483      const ArrayType *SourceAT
4484        = Context.getAsArrayType(Initializer->getType());
4485      if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4486        SetFailed(FK_ArrayTypeMismatch);
4487      else if (Initializer->HasSideEffects(S.Context))
4488        SetFailed(FK_NonConstantArrayInit);
4489      else {
4490        AddArrayInitStep(DestType);
4491      }
4492    }
4493    // Note: as a GNU C++ extension, we allow list-initialization of a
4494    // class member of array type from a parenthesized initializer list.
4495    else if (S.getLangOpts().CPlusPlus &&
4496             Entity.getKind() == InitializedEntity::EK_Member &&
4497             Initializer && isa<InitListExpr>(Initializer)) {
4498      TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4499                            *this);
4500      AddParenthesizedArrayInitStep(DestType);
4501    } else if (DestAT->getElementType()->isCharType())
4502      SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4503    else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4504      SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
4505    else
4506      SetFailed(FK_ArrayNeedsInitList);
4507
4508    return;
4509  }
4510
4511  // Determine whether we should consider writeback conversions for
4512  // Objective-C ARC.
4513  bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4514         Entity.isParameterKind();
4515
4516  // We're at the end of the line for C: it's either a write-back conversion
4517  // or it's a C assignment. There's no need to check anything else.
4518  if (!S.getLangOpts().CPlusPlus) {
4519    // If allowed, check whether this is an Objective-C writeback conversion.
4520    if (allowObjCWritebackConversion &&
4521        tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4522      return;
4523    }
4524
4525    if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4526      return;
4527
4528    if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4529      return;
4530
4531    // Handle initialization in C
4532    AddCAssignmentStep(DestType);
4533    MaybeProduceObjCObject(S, *this, Entity);
4534    return;
4535  }
4536
4537  assert(S.getLangOpts().CPlusPlus);
4538
4539  //     - If the destination type is a (possibly cv-qualified) class type:
4540  if (DestType->isRecordType()) {
4541    //     - If the initialization is direct-initialization, or if it is
4542    //       copy-initialization where the cv-unqualified version of the
4543    //       source type is the same class as, or a derived class of, the
4544    //       class of the destination, constructors are considered. [...]
4545    if (Kind.getKind() == InitializationKind::IK_Direct ||
4546        (Kind.getKind() == InitializationKind::IK_Copy &&
4547         (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4548          S.IsDerivedFrom(SourceType, DestType))))
4549      TryConstructorInitialization(S, Entity, Kind, Args,
4550                                   Entity.getType(), *this);
4551    //     - Otherwise (i.e., for the remaining copy-initialization cases),
4552    //       user-defined conversion sequences that can convert from the source
4553    //       type to the destination type or (when a conversion function is
4554    //       used) to a derived class thereof are enumerated as described in
4555    //       13.3.1.4, and the best one is chosen through overload resolution
4556    //       (13.3).
4557    else
4558      TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4559                               TopLevelOfInitList);
4560    return;
4561  }
4562
4563  if (Args.size() > 1) {
4564    SetFailed(FK_TooManyInitsForScalar);
4565    return;
4566  }
4567  assert(Args.size() == 1 && "Zero-argument case handled above");
4568
4569  //    - Otherwise, if the source type is a (possibly cv-qualified) class
4570  //      type, conversion functions are considered.
4571  if (!SourceType.isNull() && SourceType->isRecordType()) {
4572    TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4573                             TopLevelOfInitList);
4574    MaybeProduceObjCObject(S, *this, Entity);
4575    return;
4576  }
4577
4578  //    - Otherwise, the initial value of the object being initialized is the
4579  //      (possibly converted) value of the initializer expression. Standard
4580  //      conversions (Clause 4) will be used, if necessary, to convert the
4581  //      initializer expression to the cv-unqualified version of the
4582  //      destination type; no user-defined conversions are considered.
4583
4584  ImplicitConversionSequence ICS
4585    = S.TryImplicitConversion(Initializer, Entity.getType(),
4586                              /*SuppressUserConversions*/true,
4587                              /*AllowExplicitConversions*/ false,
4588                              /*InOverloadResolution*/ false,
4589                              /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4590                              allowObjCWritebackConversion);
4591
4592  if (ICS.isStandard() &&
4593      ICS.Standard.Second == ICK_Writeback_Conversion) {
4594    // Objective-C ARC writeback conversion.
4595
4596    // We should copy unless we're passing to an argument explicitly
4597    // marked 'out'.
4598    bool ShouldCopy = true;
4599    if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4600      ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4601
4602    // If there was an lvalue adjustment, add it as a separate conversion.
4603    if (ICS.Standard.First == ICK_Array_To_Pointer ||
4604        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4605      ImplicitConversionSequence LvalueICS;
4606      LvalueICS.setStandard();
4607      LvalueICS.Standard.setAsIdentityConversion();
4608      LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4609      LvalueICS.Standard.First = ICS.Standard.First;
4610      AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4611    }
4612
4613    AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4614  } else if (ICS.isBad()) {
4615    DeclAccessPair dap;
4616    if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4617      AddZeroInitializationStep(Entity.getType());
4618    } else if (Initializer->getType() == Context.OverloadTy &&
4619               !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4620                                                     false, dap))
4621      SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4622    else
4623      SetFailed(InitializationSequence::FK_ConversionFailed);
4624  } else {
4625    AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
4626
4627    MaybeProduceObjCObject(S, *this, Entity);
4628  }
4629}
4630
4631InitializationSequence::~InitializationSequence() {
4632  for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4633                                          StepEnd = Steps.end();
4634       Step != StepEnd; ++Step)
4635    Step->Destroy();
4636}
4637
4638//===----------------------------------------------------------------------===//
4639// Perform initialization
4640//===----------------------------------------------------------------------===//
4641static Sema::AssignmentAction
4642getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
4643  switch(Entity.getKind()) {
4644  case InitializedEntity::EK_Variable:
4645  case InitializedEntity::EK_New:
4646  case InitializedEntity::EK_Exception:
4647  case InitializedEntity::EK_Base:
4648  case InitializedEntity::EK_Delegating:
4649    return Sema::AA_Initializing;
4650
4651  case InitializedEntity::EK_Parameter:
4652    if (Entity.getDecl() &&
4653        isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4654      return Sema::AA_Sending;
4655
4656    return Sema::AA_Passing;
4657
4658  case InitializedEntity::EK_Parameter_CF_Audited:
4659    if (Entity.getDecl() &&
4660      isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4661      return Sema::AA_Sending;
4662
4663    return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4664
4665  case InitializedEntity::EK_Result:
4666    return Sema::AA_Returning;
4667
4668  case InitializedEntity::EK_Temporary:
4669  case InitializedEntity::EK_RelatedResult:
4670    // FIXME: Can we tell apart casting vs. converting?
4671    return Sema::AA_Casting;
4672
4673  case InitializedEntity::EK_Member:
4674  case InitializedEntity::EK_ArrayElement:
4675  case InitializedEntity::EK_VectorElement:
4676  case InitializedEntity::EK_ComplexElement:
4677  case InitializedEntity::EK_BlockElement:
4678  case InitializedEntity::EK_LambdaCapture:
4679  case InitializedEntity::EK_CompoundLiteralInit:
4680    return Sema::AA_Initializing;
4681  }
4682
4683  llvm_unreachable("Invalid EntityKind!");
4684}
4685
4686/// \brief Whether we should bind a created object as a temporary when
4687/// initializing the given entity.
4688static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4689  switch (Entity.getKind()) {
4690  case InitializedEntity::EK_ArrayElement:
4691  case InitializedEntity::EK_Member:
4692  case InitializedEntity::EK_Result:
4693  case InitializedEntity::EK_New:
4694  case InitializedEntity::EK_Variable:
4695  case InitializedEntity::EK_Base:
4696  case InitializedEntity::EK_Delegating:
4697  case InitializedEntity::EK_VectorElement:
4698  case InitializedEntity::EK_ComplexElement:
4699  case InitializedEntity::EK_Exception:
4700  case InitializedEntity::EK_BlockElement:
4701  case InitializedEntity::EK_LambdaCapture:
4702  case InitializedEntity::EK_CompoundLiteralInit:
4703    return false;
4704
4705  case InitializedEntity::EK_Parameter:
4706  case InitializedEntity::EK_Parameter_CF_Audited:
4707  case InitializedEntity::EK_Temporary:
4708  case InitializedEntity::EK_RelatedResult:
4709    return true;
4710  }
4711
4712  llvm_unreachable("missed an InitializedEntity kind?");
4713}
4714
4715/// \brief Whether the given entity, when initialized with an object
4716/// created for that initialization, requires destruction.
4717static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4718  switch (Entity.getKind()) {
4719    case InitializedEntity::EK_Result:
4720    case InitializedEntity::EK_New:
4721    case InitializedEntity::EK_Base:
4722    case InitializedEntity::EK_Delegating:
4723    case InitializedEntity::EK_VectorElement:
4724    case InitializedEntity::EK_ComplexElement:
4725    case InitializedEntity::EK_BlockElement:
4726    case InitializedEntity::EK_LambdaCapture:
4727      return false;
4728
4729    case InitializedEntity::EK_Member:
4730    case InitializedEntity::EK_Variable:
4731    case InitializedEntity::EK_Parameter:
4732    case InitializedEntity::EK_Parameter_CF_Audited:
4733    case InitializedEntity::EK_Temporary:
4734    case InitializedEntity::EK_ArrayElement:
4735    case InitializedEntity::EK_Exception:
4736    case InitializedEntity::EK_CompoundLiteralInit:
4737    case InitializedEntity::EK_RelatedResult:
4738      return true;
4739  }
4740
4741  llvm_unreachable("missed an InitializedEntity kind?");
4742}
4743
4744/// \brief Look for copy and move constructors and constructor templates, for
4745/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4746static void LookupCopyAndMoveConstructors(Sema &S,
4747                                          OverloadCandidateSet &CandidateSet,
4748                                          CXXRecordDecl *Class,
4749                                          Expr *CurInitExpr) {
4750  DeclContext::lookup_result R = S.LookupConstructors(Class);
4751  // The container holding the constructors can under certain conditions
4752  // be changed while iterating (e.g. because of deserialization).
4753  // To be safe we copy the lookup results to a new container.
4754  SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
4755  for (SmallVectorImpl<NamedDecl *>::iterator
4756         CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4757    NamedDecl *D = *CI;
4758    CXXConstructorDecl *Constructor = 0;
4759
4760    if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
4761      // Handle copy/moveconstructors, only.
4762      if (!Constructor || Constructor->isInvalidDecl() ||
4763          !Constructor->isCopyOrMoveConstructor() ||
4764          !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4765        continue;
4766
4767      DeclAccessPair FoundDecl
4768        = DeclAccessPair::make(Constructor, Constructor->getAccess());
4769      S.AddOverloadCandidate(Constructor, FoundDecl,
4770                             CurInitExpr, CandidateSet);
4771      continue;
4772    }
4773
4774    // Handle constructor templates.
4775    FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
4776    if (ConstructorTmpl->isInvalidDecl())
4777      continue;
4778
4779    Constructor = cast<CXXConstructorDecl>(
4780                                         ConstructorTmpl->getTemplatedDecl());
4781    if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4782      continue;
4783
4784    // FIXME: Do we need to limit this to copy-constructor-like
4785    // candidates?
4786    DeclAccessPair FoundDecl
4787      = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4788    S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4789                                   CurInitExpr, CandidateSet, true);
4790  }
4791}
4792
4793/// \brief Get the location at which initialization diagnostics should appear.
4794static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4795                                           Expr *Initializer) {
4796  switch (Entity.getKind()) {
4797  case InitializedEntity::EK_Result:
4798    return Entity.getReturnLoc();
4799
4800  case InitializedEntity::EK_Exception:
4801    return Entity.getThrowLoc();
4802
4803  case InitializedEntity::EK_Variable:
4804    return Entity.getDecl()->getLocation();
4805
4806  case InitializedEntity::EK_LambdaCapture:
4807    return Entity.getCaptureLoc();
4808
4809  case InitializedEntity::EK_ArrayElement:
4810  case InitializedEntity::EK_Member:
4811  case InitializedEntity::EK_Parameter:
4812  case InitializedEntity::EK_Parameter_CF_Audited:
4813  case InitializedEntity::EK_Temporary:
4814  case InitializedEntity::EK_New:
4815  case InitializedEntity::EK_Base:
4816  case InitializedEntity::EK_Delegating:
4817  case InitializedEntity::EK_VectorElement:
4818  case InitializedEntity::EK_ComplexElement:
4819  case InitializedEntity::EK_BlockElement:
4820  case InitializedEntity::EK_CompoundLiteralInit:
4821  case InitializedEntity::EK_RelatedResult:
4822    return Initializer->getLocStart();
4823  }
4824  llvm_unreachable("missed an InitializedEntity kind?");
4825}
4826
4827/// \brief Make a (potentially elidable) temporary copy of the object
4828/// provided by the given initializer by calling the appropriate copy
4829/// constructor.
4830///
4831/// \param S The Sema object used for type-checking.
4832///
4833/// \param T The type of the temporary object, which must either be
4834/// the type of the initializer expression or a superclass thereof.
4835///
4836/// \param Entity The entity being initialized.
4837///
4838/// \param CurInit The initializer expression.
4839///
4840/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4841/// is permitted in C++03 (but not C++0x) when binding a reference to
4842/// an rvalue.
4843///
4844/// \returns An expression that copies the initializer expression into
4845/// a temporary object, or an error expression if a copy could not be
4846/// created.
4847static ExprResult CopyObject(Sema &S,
4848                             QualType T,
4849                             const InitializedEntity &Entity,
4850                             ExprResult CurInit,
4851                             bool IsExtraneousCopy) {
4852  // Determine which class type we're copying to.
4853  Expr *CurInitExpr = (Expr *)CurInit.get();
4854  CXXRecordDecl *Class = 0;
4855  if (const RecordType *Record = T->getAs<RecordType>())
4856    Class = cast<CXXRecordDecl>(Record->getDecl());
4857  if (!Class)
4858    return CurInit;
4859
4860  // C++0x [class.copy]p32:
4861  //   When certain criteria are met, an implementation is allowed to
4862  //   omit the copy/move construction of a class object, even if the
4863  //   copy/move constructor and/or destructor for the object have
4864  //   side effects. [...]
4865  //     - when a temporary class object that has not been bound to a
4866  //       reference (12.2) would be copied/moved to a class object
4867  //       with the same cv-unqualified type, the copy/move operation
4868  //       can be omitted by constructing the temporary object
4869  //       directly into the target of the omitted copy/move
4870  //
4871  // Note that the other three bullets are handled elsewhere. Copy
4872  // elision for return statements and throw expressions are handled as part
4873  // of constructor initialization, while copy elision for exception handlers
4874  // is handled by the run-time.
4875  bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4876  SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4877
4878  // Make sure that the type we are copying is complete.
4879  if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
4880    return CurInit;
4881
4882  // Perform overload resolution using the class's copy/move constructors.
4883  // Only consider constructors and constructor templates. Per
4884  // C++0x [dcl.init]p16, second bullet to class types, this initialization
4885  // is direct-initialization.
4886  OverloadCandidateSet CandidateSet(Loc);
4887  LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4888
4889  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4890
4891  OverloadCandidateSet::iterator Best;
4892  switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4893  case OR_Success:
4894    break;
4895
4896  case OR_No_Viable_Function:
4897    S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4898           ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4899           : diag::err_temp_copy_no_viable)
4900      << (int)Entity.getKind() << CurInitExpr->getType()
4901      << CurInitExpr->getSourceRange();
4902    CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4903    if (!IsExtraneousCopy || S.isSFINAEContext())
4904      return ExprError();
4905    return CurInit;
4906
4907  case OR_Ambiguous:
4908    S.Diag(Loc, diag::err_temp_copy_ambiguous)
4909      << (int)Entity.getKind() << CurInitExpr->getType()
4910      << CurInitExpr->getSourceRange();
4911    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4912    return ExprError();
4913
4914  case OR_Deleted:
4915    S.Diag(Loc, diag::err_temp_copy_deleted)
4916      << (int)Entity.getKind() << CurInitExpr->getType()
4917      << CurInitExpr->getSourceRange();
4918    S.NoteDeletedFunction(Best->Function);
4919    return ExprError();
4920  }
4921
4922  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4923  SmallVector<Expr*, 8> ConstructorArgs;
4924  CurInit.release(); // Ownership transferred into MultiExprArg, below.
4925
4926  S.CheckConstructorAccess(Loc, Constructor, Entity,
4927                           Best->FoundDecl.getAccess(), IsExtraneousCopy);
4928
4929  if (IsExtraneousCopy) {
4930    // If this is a totally extraneous copy for C++03 reference
4931    // binding purposes, just return the original initialization
4932    // expression. We don't generate an (elided) copy operation here
4933    // because doing so would require us to pass down a flag to avoid
4934    // infinite recursion, where each step adds another extraneous,
4935    // elidable copy.
4936
4937    // Instantiate the default arguments of any extra parameters in
4938    // the selected copy constructor, as if we were going to create a
4939    // proper call to the copy constructor.
4940    for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4941      ParmVarDecl *Parm = Constructor->getParamDecl(I);
4942      if (S.RequireCompleteType(Loc, Parm->getType(),
4943                                diag::err_call_incomplete_argument))
4944        break;
4945
4946      // Build the default argument expression; we don't actually care
4947      // if this succeeds or not, because this routine will complain
4948      // if there was a problem.
4949      S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4950    }
4951
4952    return S.Owned(CurInitExpr);
4953  }
4954
4955  // Determine the arguments required to actually perform the
4956  // constructor call (we might have derived-to-base conversions, or
4957  // the copy constructor may have default arguments).
4958  if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
4959    return ExprError();
4960
4961  // Actually perform the constructor call.
4962  CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
4963                                    ConstructorArgs,
4964                                    HadMultipleCandidates,
4965                                    /*ListInit*/ false,
4966                                    /*ZeroInit*/ false,
4967                                    CXXConstructExpr::CK_Complete,
4968                                    SourceRange());
4969
4970  // If we're supposed to bind temporaries, do so.
4971  if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4972    CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4973  return CurInit;
4974}
4975
4976/// \brief Check whether elidable copy construction for binding a reference to
4977/// a temporary would have succeeded if we were building in C++98 mode, for
4978/// -Wc++98-compat.
4979static void CheckCXX98CompatAccessibleCopy(Sema &S,
4980                                           const InitializedEntity &Entity,
4981                                           Expr *CurInitExpr) {
4982  assert(S.getLangOpts().CPlusPlus11);
4983
4984  const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4985  if (!Record)
4986    return;
4987
4988  SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4989  if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4990        == DiagnosticsEngine::Ignored)
4991    return;
4992
4993  // Find constructors which would have been considered.
4994  OverloadCandidateSet CandidateSet(Loc);
4995  LookupCopyAndMoveConstructors(
4996      S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4997
4998  // Perform overload resolution.
4999  OverloadCandidateSet::iterator Best;
5000  OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5001
5002  PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5003    << OR << (int)Entity.getKind() << CurInitExpr->getType()
5004    << CurInitExpr->getSourceRange();
5005
5006  switch (OR) {
5007  case OR_Success:
5008    S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5009                             Entity, Best->FoundDecl.getAccess(), Diag);
5010    // FIXME: Check default arguments as far as that's possible.
5011    break;
5012
5013  case OR_No_Viable_Function:
5014    S.Diag(Loc, Diag);
5015    CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5016    break;
5017
5018  case OR_Ambiguous:
5019    S.Diag(Loc, Diag);
5020    CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5021    break;
5022
5023  case OR_Deleted:
5024    S.Diag(Loc, Diag);
5025    S.NoteDeletedFunction(Best->Function);
5026    break;
5027  }
5028}
5029
5030void InitializationSequence::PrintInitLocationNote(Sema &S,
5031                                              const InitializedEntity &Entity) {
5032  if (Entity.isParameterKind() && Entity.getDecl()) {
5033    if (Entity.getDecl()->getLocation().isInvalid())
5034      return;
5035
5036    if (Entity.getDecl()->getDeclName())
5037      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5038        << Entity.getDecl()->getDeclName();
5039    else
5040      S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5041  }
5042  else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5043           Entity.getMethodDecl())
5044    S.Diag(Entity.getMethodDecl()->getLocation(),
5045           diag::note_method_return_type_change)
5046      << Entity.getMethodDecl()->getDeclName();
5047}
5048
5049static bool isReferenceBinding(const InitializationSequence::Step &s) {
5050  return s.Kind == InitializationSequence::SK_BindReference ||
5051         s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5052}
5053
5054/// Returns true if the parameters describe a constructor initialization of
5055/// an explicit temporary object, e.g. "Point(x, y)".
5056static bool isExplicitTemporary(const InitializedEntity &Entity,
5057                                const InitializationKind &Kind,
5058                                unsigned NumArgs) {
5059  switch (Entity.getKind()) {
5060  case InitializedEntity::EK_Temporary:
5061  case InitializedEntity::EK_CompoundLiteralInit:
5062  case InitializedEntity::EK_RelatedResult:
5063    break;
5064  default:
5065    return false;
5066  }
5067
5068  switch (Kind.getKind()) {
5069  case InitializationKind::IK_DirectList:
5070    return true;
5071  // FIXME: Hack to work around cast weirdness.
5072  case InitializationKind::IK_Direct:
5073  case InitializationKind::IK_Value:
5074    return NumArgs != 1;
5075  default:
5076    return false;
5077  }
5078}
5079
5080static ExprResult
5081PerformConstructorInitialization(Sema &S,
5082                                 const InitializedEntity &Entity,
5083                                 const InitializationKind &Kind,
5084                                 MultiExprArg Args,
5085                                 const InitializationSequence::Step& Step,
5086                                 bool &ConstructorInitRequiresZeroInit,
5087                                 bool IsListInitialization,
5088                                 SourceLocation LBraceLoc,
5089                                 SourceLocation RBraceLoc) {
5090  unsigned NumArgs = Args.size();
5091  CXXConstructorDecl *Constructor
5092    = cast<CXXConstructorDecl>(Step.Function.Function);
5093  bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5094
5095  // Build a call to the selected constructor.
5096  SmallVector<Expr*, 8> ConstructorArgs;
5097  SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5098                         ? Kind.getEqualLoc()
5099                         : Kind.getLocation();
5100
5101  if (Kind.getKind() == InitializationKind::IK_Default) {
5102    // Force even a trivial, implicit default constructor to be
5103    // semantically checked. We do this explicitly because we don't build
5104    // the definition for completely trivial constructors.
5105    assert(Constructor->getParent() && "No parent class for constructor.");
5106    if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5107        Constructor->isTrivial() && !Constructor->isUsed(false))
5108      S.DefineImplicitDefaultConstructor(Loc, Constructor);
5109  }
5110
5111  ExprResult CurInit = S.Owned((Expr *)0);
5112
5113  // C++ [over.match.copy]p1:
5114  //   - When initializing a temporary to be bound to the first parameter
5115  //     of a constructor that takes a reference to possibly cv-qualified
5116  //     T as its first argument, called with a single argument in the
5117  //     context of direct-initialization, explicit conversion functions
5118  //     are also considered.
5119  bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5120                           Args.size() == 1 &&
5121                           Constructor->isCopyOrMoveConstructor();
5122
5123  // Determine the arguments required to actually perform the constructor
5124  // call.
5125  if (S.CompleteConstructorCall(Constructor, Args,
5126                                Loc, ConstructorArgs,
5127                                AllowExplicitConv,
5128                                IsListInitialization))
5129    return ExprError();
5130
5131
5132  if (isExplicitTemporary(Entity, Kind, NumArgs)) {
5133    // An explicitly-constructed temporary, e.g., X(1, 2).
5134    S.MarkFunctionReferenced(Loc, Constructor);
5135    if (S.DiagnoseUseOfDecl(Constructor, Loc))
5136      return ExprError();
5137
5138    TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5139    if (!TSInfo)
5140      TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
5141    SourceRange ParenOrBraceRange =
5142      (Kind.getKind() == InitializationKind::IK_DirectList)
5143      ? SourceRange(LBraceLoc, RBraceLoc)
5144      : Kind.getParenRange();
5145
5146    CurInit = S.Owned(
5147      new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5148                                             TSInfo, ConstructorArgs,
5149                                             ParenOrBraceRange,
5150                                             HadMultipleCandidates,
5151                                             IsListInitialization,
5152                                             ConstructorInitRequiresZeroInit));
5153  } else {
5154    CXXConstructExpr::ConstructionKind ConstructKind =
5155      CXXConstructExpr::CK_Complete;
5156
5157    if (Entity.getKind() == InitializedEntity::EK_Base) {
5158      ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5159        CXXConstructExpr::CK_VirtualBase :
5160        CXXConstructExpr::CK_NonVirtualBase;
5161    } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5162      ConstructKind = CXXConstructExpr::CK_Delegating;
5163    }
5164
5165    // Only get the parenthesis range if it is a direct construction.
5166    SourceRange parenRange =
5167        Kind.getKind() == InitializationKind::IK_Direct ?
5168        Kind.getParenRange() : SourceRange();
5169
5170    // If the entity allows NRVO, mark the construction as elidable
5171    // unconditionally.
5172    if (Entity.allowsNRVO())
5173      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5174                                        Constructor, /*Elidable=*/true,
5175                                        ConstructorArgs,
5176                                        HadMultipleCandidates,
5177                                        IsListInitialization,
5178                                        ConstructorInitRequiresZeroInit,
5179                                        ConstructKind,
5180                                        parenRange);
5181    else
5182      CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5183                                        Constructor,
5184                                        ConstructorArgs,
5185                                        HadMultipleCandidates,
5186                                        IsListInitialization,
5187                                        ConstructorInitRequiresZeroInit,
5188                                        ConstructKind,
5189                                        parenRange);
5190  }
5191  if (CurInit.isInvalid())
5192    return ExprError();
5193
5194  // Only check access if all of that succeeded.
5195  S.CheckConstructorAccess(Loc, Constructor, Entity,
5196                           Step.Function.FoundDecl.getAccess());
5197  if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5198    return ExprError();
5199
5200  if (shouldBindAsTemporary(Entity))
5201    CurInit = S.MaybeBindToTemporary(CurInit.take());
5202
5203  return CurInit;
5204}
5205
5206/// Determine whether the specified InitializedEntity definitely has a lifetime
5207/// longer than the current full-expression. Conservatively returns false if
5208/// it's unclear.
5209static bool
5210InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5211  const InitializedEntity *Top = &Entity;
5212  while (Top->getParent())
5213    Top = Top->getParent();
5214
5215  switch (Top->getKind()) {
5216  case InitializedEntity::EK_Variable:
5217  case InitializedEntity::EK_Result:
5218  case InitializedEntity::EK_Exception:
5219  case InitializedEntity::EK_Member:
5220  case InitializedEntity::EK_New:
5221  case InitializedEntity::EK_Base:
5222  case InitializedEntity::EK_Delegating:
5223    return true;
5224
5225  case InitializedEntity::EK_ArrayElement:
5226  case InitializedEntity::EK_VectorElement:
5227  case InitializedEntity::EK_BlockElement:
5228  case InitializedEntity::EK_ComplexElement:
5229    // Could not determine what the full initialization is. Assume it might not
5230    // outlive the full-expression.
5231    return false;
5232
5233  case InitializedEntity::EK_Parameter:
5234  case InitializedEntity::EK_Parameter_CF_Audited:
5235  case InitializedEntity::EK_Temporary:
5236  case InitializedEntity::EK_LambdaCapture:
5237  case InitializedEntity::EK_CompoundLiteralInit:
5238  case InitializedEntity::EK_RelatedResult:
5239    // The entity being initialized might not outlive the full-expression.
5240    return false;
5241  }
5242
5243  llvm_unreachable("unknown entity kind");
5244}
5245
5246/// Determine the declaration which an initialized entity ultimately refers to,
5247/// for the purpose of lifetime-extending a temporary bound to a reference in
5248/// the initialization of \p Entity.
5249static const ValueDecl *
5250getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5251                                     const ValueDecl *FallbackDecl = 0) {
5252  // C++11 [class.temporary]p5:
5253  switch (Entity.getKind()) {
5254  case InitializedEntity::EK_Variable:
5255    //   The temporary [...] persists for the lifetime of the reference
5256    return Entity.getDecl();
5257
5258  case InitializedEntity::EK_Member:
5259    // For subobjects, we look at the complete object.
5260    if (Entity.getParent())
5261      return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5262                                                  Entity.getDecl());
5263
5264    //   except:
5265    //   -- A temporary bound to a reference member in a constructor's
5266    //      ctor-initializer persists until the constructor exits.
5267    return Entity.getDecl();
5268
5269  case InitializedEntity::EK_Parameter:
5270  case InitializedEntity::EK_Parameter_CF_Audited:
5271    //   -- A temporary bound to a reference parameter in a function call
5272    //      persists until the completion of the full-expression containing
5273    //      the call.
5274  case InitializedEntity::EK_Result:
5275    //   -- The lifetime of a temporary bound to the returned value in a
5276    //      function return statement is not extended; the temporary is
5277    //      destroyed at the end of the full-expression in the return statement.
5278  case InitializedEntity::EK_New:
5279    //   -- A temporary bound to a reference in a new-initializer persists
5280    //      until the completion of the full-expression containing the
5281    //      new-initializer.
5282    return 0;
5283
5284  case InitializedEntity::EK_Temporary:
5285  case InitializedEntity::EK_CompoundLiteralInit:
5286  case InitializedEntity::EK_RelatedResult:
5287    // We don't yet know the storage duration of the surrounding temporary.
5288    // Assume it's got full-expression duration for now, it will patch up our
5289    // storage duration if that's not correct.
5290    return 0;
5291
5292  case InitializedEntity::EK_ArrayElement:
5293    // For subobjects, we look at the complete object.
5294    return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5295                                                FallbackDecl);
5296
5297  case InitializedEntity::EK_Base:
5298  case InitializedEntity::EK_Delegating:
5299    // We can reach this case for aggregate initialization in a constructor:
5300    //   struct A { int &&r; };
5301    //   struct B : A { B() : A{0} {} };
5302    // In this case, use the innermost field decl as the context.
5303    return FallbackDecl;
5304
5305  case InitializedEntity::EK_BlockElement:
5306  case InitializedEntity::EK_LambdaCapture:
5307  case InitializedEntity::EK_Exception:
5308  case InitializedEntity::EK_VectorElement:
5309  case InitializedEntity::EK_ComplexElement:
5310    return 0;
5311  }
5312  llvm_unreachable("unknown entity kind");
5313}
5314
5315static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5316
5317/// Update a glvalue expression that is used as the initializer of a reference
5318/// to note that its lifetime is extended.
5319/// \return \c true if any temporary had its lifetime extended.
5320static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
5321  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5322    if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5323      // This is just redundant braces around an initializer. Step over it.
5324      Init = ILE->getInit(0);
5325    }
5326  }
5327
5328  // Walk past any constructs which we can lifetime-extend across.
5329  Expr *Old;
5330  do {
5331    Old = Init;
5332
5333    // Step over any subobject adjustments; we may have a materialized
5334    // temporary inside them.
5335    SmallVector<const Expr *, 2> CommaLHSs;
5336    SmallVector<SubobjectAdjustment, 2> Adjustments;
5337    Init = const_cast<Expr *>(
5338        Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5339
5340    // Per current approach for DR1376, look through casts to reference type
5341    // when performing lifetime extension.
5342    if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5343      if (CE->getSubExpr()->isGLValue())
5344        Init = CE->getSubExpr();
5345
5346    // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5347    // It's unclear if binding a reference to that xvalue extends the array
5348    // temporary.
5349  } while (Init != Old);
5350
5351  if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5352    // Update the storage duration of the materialized temporary.
5353    // FIXME: Rebuild the expression instead of mutating it.
5354    ME->setExtendingDecl(ExtendingD);
5355    performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
5356    return true;
5357  }
5358
5359  return false;
5360}
5361
5362/// Update a prvalue expression that is going to be materialized as a
5363/// lifetime-extended temporary.
5364static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5365  // Dig out the expression which constructs the extended temporary.
5366  SmallVector<const Expr *, 2> CommaLHSs;
5367  SmallVector<SubobjectAdjustment, 2> Adjustments;
5368  Init = const_cast<Expr *>(
5369      Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5370
5371  if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5372    Init = BTE->getSubExpr();
5373
5374  if (CXXStdInitializerListExpr *ILE =
5375          dyn_cast<CXXStdInitializerListExpr>(Init)) {
5376    performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5377    return;
5378  }
5379
5380  if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5381    if (ILE->getType()->isArrayType()) {
5382      for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5383        performLifetimeExtension(ILE->getInit(I), ExtendingD);
5384      return;
5385    }
5386
5387    if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
5388      assert(RD->isAggregate() && "aggregate init on non-aggregate");
5389
5390      // If we lifetime-extend a braced initializer which is initializing an
5391      // aggregate, and that aggregate contains reference members which are
5392      // bound to temporaries, those temporaries are also lifetime-extended.
5393      if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5394          ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5395        performReferenceExtension(ILE->getInit(0), ExtendingD);
5396      else {
5397        unsigned Index = 0;
5398        for (RecordDecl::field_iterator I = RD->field_begin(),
5399                                        E = RD->field_end();
5400             I != E; ++I) {
5401          if (Index >= ILE->getNumInits())
5402            break;
5403          if (I->isUnnamedBitfield())
5404            continue;
5405          Expr *SubInit = ILE->getInit(Index);
5406          if (I->getType()->isReferenceType())
5407            performReferenceExtension(SubInit, ExtendingD);
5408          else if (isa<InitListExpr>(SubInit) ||
5409                   isa<CXXStdInitializerListExpr>(SubInit))
5410            // This may be either aggregate-initialization of a member or
5411            // initialization of a std::initializer_list object. Either way,
5412            // we should recursively lifetime-extend that initializer.
5413            performLifetimeExtension(SubInit, ExtendingD);
5414          ++Index;
5415        }
5416      }
5417    }
5418  }
5419}
5420
5421static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5422                                    const Expr *Init, bool IsInitializerList,
5423                                    const ValueDecl *ExtendingDecl) {
5424  // Warn if a field lifetime-extends a temporary.
5425  if (isa<FieldDecl>(ExtendingDecl)) {
5426    if (IsInitializerList) {
5427      S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5428        << /*at end of constructor*/true;
5429      return;
5430    }
5431
5432    bool IsSubobjectMember = false;
5433    for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5434         Ent = Ent->getParent()) {
5435      if (Ent->getKind() != InitializedEntity::EK_Base) {
5436        IsSubobjectMember = true;
5437        break;
5438      }
5439    }
5440    S.Diag(Init->getExprLoc(),
5441           diag::warn_bind_ref_member_to_temporary)
5442      << ExtendingDecl << Init->getSourceRange()
5443      << IsSubobjectMember << IsInitializerList;
5444    if (IsSubobjectMember)
5445      S.Diag(ExtendingDecl->getLocation(),
5446             diag::note_ref_subobject_of_member_declared_here);
5447    else
5448      S.Diag(ExtendingDecl->getLocation(),
5449             diag::note_ref_or_ptr_member_declared_here)
5450        << /*is pointer*/false;
5451  }
5452}
5453
5454static void DiagnoseNarrowingInInitList(Sema &S,
5455                                        const ImplicitConversionSequence &ICS,
5456                                        QualType PreNarrowingType,
5457                                        QualType EntityType,
5458                                        const Expr *PostInit);
5459
5460ExprResult
5461InitializationSequence::Perform(Sema &S,
5462                                const InitializedEntity &Entity,
5463                                const InitializationKind &Kind,
5464                                MultiExprArg Args,
5465                                QualType *ResultType) {
5466  if (Failed()) {
5467    Diagnose(S, Entity, Kind, Args);
5468    return ExprError();
5469  }
5470
5471  if (getKind() == DependentSequence) {
5472    // If the declaration is a non-dependent, incomplete array type
5473    // that has an initializer, then its type will be completed once
5474    // the initializer is instantiated.
5475    if (ResultType && !Entity.getType()->isDependentType() &&
5476        Args.size() == 1) {
5477      QualType DeclType = Entity.getType();
5478      if (const IncompleteArrayType *ArrayT
5479                           = S.Context.getAsIncompleteArrayType(DeclType)) {
5480        // FIXME: We don't currently have the ability to accurately
5481        // compute the length of an initializer list without
5482        // performing full type-checking of the initializer list
5483        // (since we have to determine where braces are implicitly
5484        // introduced and such).  So, we fall back to making the array
5485        // type a dependently-sized array type with no specified
5486        // bound.
5487        if (isa<InitListExpr>((Expr *)Args[0])) {
5488          SourceRange Brackets;
5489
5490          // Scavange the location of the brackets from the entity, if we can.
5491          if (DeclaratorDecl *DD = Entity.getDecl()) {
5492            if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5493              TypeLoc TL = TInfo->getTypeLoc();
5494              if (IncompleteArrayTypeLoc ArrayLoc =
5495                      TL.getAs<IncompleteArrayTypeLoc>())
5496                Brackets = ArrayLoc.getBracketsRange();
5497            }
5498          }
5499
5500          *ResultType
5501            = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5502                                                   /*NumElts=*/0,
5503                                                   ArrayT->getSizeModifier(),
5504                                       ArrayT->getIndexTypeCVRQualifiers(),
5505                                                   Brackets);
5506        }
5507
5508      }
5509    }
5510    if (Kind.getKind() == InitializationKind::IK_Direct &&
5511        !Kind.isExplicitCast()) {
5512      // Rebuild the ParenListExpr.
5513      SourceRange ParenRange = Kind.getParenRange();
5514      return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
5515                                  Args);
5516    }
5517    assert(Kind.getKind() == InitializationKind::IK_Copy ||
5518           Kind.isExplicitCast() ||
5519           Kind.getKind() == InitializationKind::IK_DirectList);
5520    return ExprResult(Args[0]);
5521  }
5522
5523  // No steps means no initialization.
5524  if (Steps.empty())
5525    return S.Owned((Expr *)0);
5526
5527  if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
5528      Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
5529      !Entity.isParameterKind()) {
5530    // Produce a C++98 compatibility warning if we are initializing a reference
5531    // from an initializer list. For parameters, we produce a better warning
5532    // elsewhere.
5533    Expr *Init = Args[0];
5534    S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5535      << Init->getSourceRange();
5536  }
5537
5538  // Diagnose cases where we initialize a pointer to an array temporary, and the
5539  // pointer obviously outlives the temporary.
5540  if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
5541      Entity.getType()->isPointerType() &&
5542      InitializedEntityOutlivesFullExpression(Entity)) {
5543    Expr *Init = Args[0];
5544    Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5545    if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5546      S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5547        << Init->getSourceRange();
5548  }
5549
5550  QualType DestType = Entity.getType().getNonReferenceType();
5551  // FIXME: Ugly hack around the fact that Entity.getType() is not
5552  // the same as Entity.getDecl()->getType() in cases involving type merging,
5553  //  and we want latter when it makes sense.
5554  if (ResultType)
5555    *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
5556                                     Entity.getType();
5557
5558  ExprResult CurInit = S.Owned((Expr *)0);
5559
5560  // For initialization steps that start with a single initializer,
5561  // grab the only argument out the Args and place it into the "current"
5562  // initializer.
5563  switch (Steps.front().Kind) {
5564  case SK_ResolveAddressOfOverloadedFunction:
5565  case SK_CastDerivedToBaseRValue:
5566  case SK_CastDerivedToBaseXValue:
5567  case SK_CastDerivedToBaseLValue:
5568  case SK_BindReference:
5569  case SK_BindReferenceToTemporary:
5570  case SK_ExtraneousCopyToTemporary:
5571  case SK_UserConversion:
5572  case SK_QualificationConversionLValue:
5573  case SK_QualificationConversionXValue:
5574  case SK_QualificationConversionRValue:
5575  case SK_LValueToRValue:
5576  case SK_ConversionSequence:
5577  case SK_ConversionSequenceNoNarrowing:
5578  case SK_ListInitialization:
5579  case SK_UnwrapInitList:
5580  case SK_RewrapInitList:
5581  case SK_CAssignment:
5582  case SK_StringInit:
5583  case SK_ObjCObjectConversion:
5584  case SK_ArrayInit:
5585  case SK_ParenthesizedArrayInit:
5586  case SK_PassByIndirectCopyRestore:
5587  case SK_PassByIndirectRestore:
5588  case SK_ProduceObjCObject:
5589  case SK_StdInitializerList:
5590  case SK_OCLSamplerInit:
5591  case SK_OCLZeroEvent: {
5592    assert(Args.size() == 1);
5593    CurInit = Args[0];
5594    if (!CurInit.get()) return ExprError();
5595    break;
5596  }
5597
5598  case SK_ConstructorInitialization:
5599  case SK_ListConstructorCall:
5600  case SK_ZeroInitialization:
5601    break;
5602  }
5603
5604  // Walk through the computed steps for the initialization sequence,
5605  // performing the specified conversions along the way.
5606  bool ConstructorInitRequiresZeroInit = false;
5607  for (step_iterator Step = step_begin(), StepEnd = step_end();
5608       Step != StepEnd; ++Step) {
5609    if (CurInit.isInvalid())
5610      return ExprError();
5611
5612    QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
5613
5614    switch (Step->Kind) {
5615    case SK_ResolveAddressOfOverloadedFunction:
5616      // Overload resolution determined which function invoke; update the
5617      // initializer to reflect that choice.
5618      S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
5619      if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5620        return ExprError();
5621      CurInit = S.FixOverloadedFunctionReference(CurInit,
5622                                                 Step->Function.FoundDecl,
5623                                                 Step->Function.Function);
5624      break;
5625
5626    case SK_CastDerivedToBaseRValue:
5627    case SK_CastDerivedToBaseXValue:
5628    case SK_CastDerivedToBaseLValue: {
5629      // We have a derived-to-base cast that produces either an rvalue or an
5630      // lvalue. Perform that cast.
5631
5632      CXXCastPath BasePath;
5633
5634      // Casts to inaccessible base classes are allowed with C-style casts.
5635      bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5636      if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
5637                                         CurInit.get()->getLocStart(),
5638                                         CurInit.get()->getSourceRange(),
5639                                         &BasePath, IgnoreBaseAccess))
5640        return ExprError();
5641
5642      if (S.BasePathInvolvesVirtualBase(BasePath)) {
5643        QualType T = SourceType;
5644        if (const PointerType *Pointer = T->getAs<PointerType>())
5645          T = Pointer->getPointeeType();
5646        if (const RecordType *RecordTy = T->getAs<RecordType>())
5647          S.MarkVTableUsed(CurInit.get()->getLocStart(),
5648                           cast<CXXRecordDecl>(RecordTy->getDecl()));
5649      }
5650
5651      ExprValueKind VK =
5652          Step->Kind == SK_CastDerivedToBaseLValue ?
5653              VK_LValue :
5654              (Step->Kind == SK_CastDerivedToBaseXValue ?
5655                   VK_XValue :
5656                   VK_RValue);
5657      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5658                                                 Step->Type,
5659                                                 CK_DerivedToBase,
5660                                                 CurInit.get(),
5661                                                 &BasePath, VK));
5662      break;
5663    }
5664
5665    case SK_BindReference:
5666      // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5667      if (CurInit.get()->refersToBitField()) {
5668        // We don't necessarily have an unambiguous source bit-field.
5669        FieldDecl *BitField = CurInit.get()->getSourceBitField();
5670        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
5671          << Entity.getType().isVolatileQualified()
5672          << (BitField ? BitField->getDeclName() : DeclarationName())
5673          << (BitField != NULL)
5674          << CurInit.get()->getSourceRange();
5675        if (BitField)
5676          S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5677
5678        return ExprError();
5679      }
5680
5681      if (CurInit.get()->refersToVectorElement()) {
5682        // References cannot bind to vector elements.
5683        S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5684          << Entity.getType().isVolatileQualified()
5685          << CurInit.get()->getSourceRange();
5686        PrintInitLocationNote(S, Entity);
5687        return ExprError();
5688      }
5689
5690      // Reference binding does not have any corresponding ASTs.
5691
5692      // Check exception specifications
5693      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5694        return ExprError();
5695
5696      // Even though we didn't materialize a temporary, the binding may still
5697      // extend the lifetime of a temporary. This happens if we bind a reference
5698      // to the result of a cast to reference type.
5699      if (const ValueDecl *ExtendingDecl =
5700              getDeclForTemporaryLifetimeExtension(Entity)) {
5701        if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5702          warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5703                                  ExtendingDecl);
5704      }
5705
5706      break;
5707
5708    case SK_BindReferenceToTemporary: {
5709      // Make sure the "temporary" is actually an rvalue.
5710      assert(CurInit.get()->isRValue() && "not a temporary");
5711
5712      // Check exception specifications
5713      if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5714        return ExprError();
5715
5716      // Maybe lifetime-extend the temporary's subobjects to match the
5717      // entity's lifetime.
5718      const ValueDecl *ExtendingDecl =
5719          getDeclForTemporaryLifetimeExtension(Entity);
5720      if (ExtendingDecl) {
5721        performLifetimeExtension(CurInit.get(), ExtendingDecl);
5722        warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
5723      }
5724
5725      // Materialize the temporary into memory.
5726      MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
5727          Entity.getType().getNonReferenceType(), CurInit.get(),
5728          Entity.getType()->isLValueReferenceType(), ExtendingDecl);
5729
5730      // If we're binding to an Objective-C object that has lifetime, we
5731      // need cleanups. Likewise if we're extending this temporary to automatic
5732      // storage duration -- we need to register its cleanup during the
5733      // full-expression's cleanups.
5734      if ((S.getLangOpts().ObjCAutoRefCount &&
5735           MTE->getType()->isObjCLifetimeType()) ||
5736          (MTE->getStorageDuration() == SD_Automatic &&
5737           MTE->getType().isDestructedType()))
5738        S.ExprNeedsCleanups = true;
5739
5740      CurInit = S.Owned(MTE);
5741      break;
5742    }
5743
5744    case SK_ExtraneousCopyToTemporary:
5745      CurInit = CopyObject(S, Step->Type, Entity, CurInit,
5746                           /*IsExtraneousCopy=*/true);
5747      break;
5748
5749    case SK_UserConversion: {
5750      // We have a user-defined conversion that invokes either a constructor
5751      // or a conversion function.
5752      CastKind CastKind;
5753      bool IsCopy = false;
5754      FunctionDecl *Fn = Step->Function.Function;
5755      DeclAccessPair FoundFn = Step->Function.FoundDecl;
5756      bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
5757      bool CreatedObject = false;
5758      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
5759        // Build a call to the selected constructor.
5760        SmallVector<Expr*, 8> ConstructorArgs;
5761        SourceLocation Loc = CurInit.get()->getLocStart();
5762        CurInit.release(); // Ownership transferred into MultiExprArg, below.
5763
5764        // Determine the arguments required to actually perform the constructor
5765        // call.
5766        Expr *Arg = CurInit.get();
5767        if (S.CompleteConstructorCall(Constructor,
5768                                      MultiExprArg(&Arg, 1),
5769                                      Loc, ConstructorArgs))
5770          return ExprError();
5771
5772        // Build an expression that constructs a temporary.
5773        CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5774                                          ConstructorArgs,
5775                                          HadMultipleCandidates,
5776                                          /*ListInit*/ false,
5777                                          /*ZeroInit*/ false,
5778                                          CXXConstructExpr::CK_Complete,
5779                                          SourceRange());
5780        if (CurInit.isInvalid())
5781          return ExprError();
5782
5783        S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
5784                                 FoundFn.getAccess());
5785        if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5786          return ExprError();
5787
5788        CastKind = CK_ConstructorConversion;
5789        QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5790        if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5791            S.IsDerivedFrom(SourceType, Class))
5792          IsCopy = true;
5793
5794        CreatedObject = true;
5795      } else {
5796        // Build a call to the conversion function.
5797        CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
5798        S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
5799                                    FoundFn);
5800        if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5801          return ExprError();
5802
5803        // FIXME: Should we move this initialization into a separate
5804        // derived-to-base conversion? I believe the answer is "no", because
5805        // we don't want to turn off access control here for c-style casts.
5806        ExprResult CurInitExprRes =
5807          S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5808                                                FoundFn, Conversion);
5809        if(CurInitExprRes.isInvalid())
5810          return ExprError();
5811        CurInit = CurInitExprRes;
5812
5813        // Build the actual call to the conversion function.
5814        CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5815                                           HadMultipleCandidates);
5816        if (CurInit.isInvalid() || !CurInit.get())
5817          return ExprError();
5818
5819        CastKind = CK_UserDefinedConversion;
5820
5821        CreatedObject = Conversion->getResultType()->isRecordType();
5822      }
5823
5824      bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
5825      bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5826
5827      if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
5828        QualType T = CurInit.get()->getType();
5829        if (const RecordType *Record = T->getAs<RecordType>()) {
5830          CXXDestructorDecl *Destructor
5831            = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
5832          S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
5833                                  S.PDiag(diag::err_access_dtor_temp) << T);
5834          S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
5835          if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5836            return ExprError();
5837        }
5838      }
5839
5840      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5841                                                 CurInit.get()->getType(),
5842                                                 CastKind, CurInit.get(), 0,
5843                                                CurInit.get()->getValueKind()));
5844      if (MaybeBindToTemp)
5845        CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5846      if (RequiresCopy)
5847        CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5848                             CurInit, /*IsExtraneousCopy=*/false);
5849      break;
5850    }
5851
5852    case SK_QualificationConversionLValue:
5853    case SK_QualificationConversionXValue:
5854    case SK_QualificationConversionRValue: {
5855      // Perform a qualification conversion; these can never go wrong.
5856      ExprValueKind VK =
5857          Step->Kind == SK_QualificationConversionLValue ?
5858              VK_LValue :
5859              (Step->Kind == SK_QualificationConversionXValue ?
5860                   VK_XValue :
5861                   VK_RValue);
5862      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5863      break;
5864    }
5865
5866    case SK_LValueToRValue: {
5867      assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5868      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5869                                                 CK_LValueToRValue,
5870                                                 CurInit.take(),
5871                                                 /*BasePath=*/0,
5872                                                 VK_RValue));
5873      break;
5874    }
5875
5876    case SK_ConversionSequence:
5877    case SK_ConversionSequenceNoNarrowing: {
5878      Sema::CheckedConversionKind CCK
5879        = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5880        : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5881        : Kind.isExplicitCast()? Sema::CCK_OtherCast
5882        : Sema::CCK_ImplicitConversion;
5883      ExprResult CurInitExprRes =
5884        S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5885                                    getAssignmentAction(Entity), CCK);
5886      if (CurInitExprRes.isInvalid())
5887        return ExprError();
5888      CurInit = CurInitExprRes;
5889
5890      if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5891          S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5892        DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5893                                    CurInit.get());
5894      break;
5895    }
5896
5897    case SK_ListInitialization: {
5898      InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5899      // If we're not initializing the top-level entity, we need to create an
5900      // InitializeTemporary entity for our target type.
5901      QualType Ty = Step->Type;
5902      bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
5903      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5904      InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5905      InitListChecker PerformInitList(S, InitEntity,
5906          InitList, Ty, /*VerifyOnly=*/false);
5907      if (PerformInitList.HadError())
5908        return ExprError();
5909
5910      // Hack: We must update *ResultType if available in order to set the
5911      // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5912      // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5913      if (ResultType &&
5914          ResultType->getNonReferenceType()->isIncompleteArrayType()) {
5915        if ((*ResultType)->isRValueReferenceType())
5916          Ty = S.Context.getRValueReferenceType(Ty);
5917        else if ((*ResultType)->isLValueReferenceType())
5918          Ty = S.Context.getLValueReferenceType(Ty,
5919            (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5920        *ResultType = Ty;
5921      }
5922
5923      InitListExpr *StructuredInitList =
5924          PerformInitList.getFullyStructuredList();
5925      CurInit.release();
5926      CurInit = shouldBindAsTemporary(InitEntity)
5927          ? S.MaybeBindToTemporary(StructuredInitList)
5928          : S.Owned(StructuredInitList);
5929      break;
5930    }
5931
5932    case SK_ListConstructorCall: {
5933      // When an initializer list is passed for a parameter of type "reference
5934      // to object", we don't get an EK_Temporary entity, but instead an
5935      // EK_Parameter entity with reference type.
5936      // FIXME: This is a hack. What we really should do is create a user
5937      // conversion step for this case, but this makes it considerably more
5938      // complicated. For now, this will do.
5939      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5940                                        Entity.getType().getNonReferenceType());
5941      bool UseTemporary = Entity.getType()->isReferenceType();
5942      assert(Args.size() == 1 && "expected a single argument for list init");
5943      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5944      S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
5945        << InitList->getSourceRange();
5946      MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5947      CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
5948                                                                   Entity,
5949                                                 Kind, Arg, *Step,
5950                                               ConstructorInitRequiresZeroInit,
5951                                               /*IsListInitialization*/ true,
5952                                               InitList->getLBraceLoc(),
5953                                               InitList->getRBraceLoc());
5954      break;
5955    }
5956
5957    case SK_UnwrapInitList:
5958      CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5959      break;
5960
5961    case SK_RewrapInitList: {
5962      Expr *E = CurInit.take();
5963      InitListExpr *Syntactic = Step->WrappingSyntacticList;
5964      InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5965          Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
5966      ILE->setSyntacticForm(Syntactic);
5967      ILE->setType(E->getType());
5968      ILE->setValueKind(E->getValueKind());
5969      CurInit = S.Owned(ILE);
5970      break;
5971    }
5972
5973    case SK_ConstructorInitialization: {
5974      // When an initializer list is passed for a parameter of type "reference
5975      // to object", we don't get an EK_Temporary entity, but instead an
5976      // EK_Parameter entity with reference type.
5977      // FIXME: This is a hack. What we really should do is create a user
5978      // conversion step for this case, but this makes it considerably more
5979      // complicated. For now, this will do.
5980      InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5981                                        Entity.getType().getNonReferenceType());
5982      bool UseTemporary = Entity.getType()->isReferenceType();
5983      CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
5984                                                                 : Entity,
5985                                                 Kind, Args, *Step,
5986                                               ConstructorInitRequiresZeroInit,
5987                                               /*IsListInitialization*/ false,
5988                                               /*LBraceLoc*/ SourceLocation(),
5989                                               /*RBraceLoc*/ SourceLocation());
5990      break;
5991    }
5992
5993    case SK_ZeroInitialization: {
5994      step_iterator NextStep = Step;
5995      ++NextStep;
5996      if (NextStep != StepEnd &&
5997          (NextStep->Kind == SK_ConstructorInitialization ||
5998           NextStep->Kind == SK_ListConstructorCall)) {
5999        // The need for zero-initialization is recorded directly into
6000        // the call to the object's constructor within the next step.
6001        ConstructorInitRequiresZeroInit = true;
6002      } else if (Kind.getKind() == InitializationKind::IK_Value &&
6003                 S.getLangOpts().CPlusPlus &&
6004                 !Kind.isImplicitValueInit()) {
6005        TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6006        if (!TSInfo)
6007          TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
6008                                                    Kind.getRange().getBegin());
6009
6010        CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
6011                              TSInfo->getType().getNonLValueExprType(S.Context),
6012                                                                 TSInfo,
6013                                                    Kind.getRange().getEnd()));
6014      } else {
6015        CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
6016      }
6017      break;
6018    }
6019
6020    case SK_CAssignment: {
6021      QualType SourceType = CurInit.get()->getType();
6022      ExprResult Result = CurInit;
6023      Sema::AssignConvertType ConvTy =
6024        S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6025            Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
6026      if (Result.isInvalid())
6027        return ExprError();
6028      CurInit = Result;
6029
6030      // If this is a call, allow conversion to a transparent union.
6031      ExprResult CurInitExprRes = CurInit;
6032      if (ConvTy != Sema::Compatible &&
6033          Entity.isParameterKind() &&
6034          S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
6035            == Sema::Compatible)
6036        ConvTy = Sema::Compatible;
6037      if (CurInitExprRes.isInvalid())
6038        return ExprError();
6039      CurInit = CurInitExprRes;
6040
6041      bool Complained;
6042      if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6043                                     Step->Type, SourceType,
6044                                     CurInit.get(),
6045                                     getAssignmentAction(Entity, true),
6046                                     &Complained)) {
6047        PrintInitLocationNote(S, Entity);
6048        return ExprError();
6049      } else if (Complained)
6050        PrintInitLocationNote(S, Entity);
6051      break;
6052    }
6053
6054    case SK_StringInit: {
6055      QualType Ty = Step->Type;
6056      CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
6057                      S.Context.getAsArrayType(Ty), S);
6058      break;
6059    }
6060
6061    case SK_ObjCObjectConversion:
6062      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6063                          CK_ObjCObjectLValueCast,
6064                          CurInit.get()->getValueKind());
6065      break;
6066
6067    case SK_ArrayInit:
6068      // Okay: we checked everything before creating this step. Note that
6069      // this is a GNU extension.
6070      S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
6071        << Step->Type << CurInit.get()->getType()
6072        << CurInit.get()->getSourceRange();
6073
6074      // If the destination type is an incomplete array type, update the
6075      // type accordingly.
6076      if (ResultType) {
6077        if (const IncompleteArrayType *IncompleteDest
6078                           = S.Context.getAsIncompleteArrayType(Step->Type)) {
6079          if (const ConstantArrayType *ConstantSource
6080                 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
6081            *ResultType = S.Context.getConstantArrayType(
6082                                             IncompleteDest->getElementType(),
6083                                             ConstantSource->getSize(),
6084                                             ArrayType::Normal, 0);
6085          }
6086        }
6087      }
6088      break;
6089
6090    case SK_ParenthesizedArrayInit:
6091      // Okay: we checked everything before creating this step. Note that
6092      // this is a GNU extension.
6093      S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6094        << CurInit.get()->getSourceRange();
6095      break;
6096
6097    case SK_PassByIndirectCopyRestore:
6098    case SK_PassByIndirectRestore:
6099      checkIndirectCopyRestoreSource(S, CurInit.get());
6100      CurInit = S.Owned(new (S.Context)
6101                        ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6102                                Step->Kind == SK_PassByIndirectCopyRestore));
6103      break;
6104
6105    case SK_ProduceObjCObject:
6106      CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
6107                                                 CK_ARCProduceObject,
6108                                                 CurInit.take(), 0, VK_RValue));
6109      break;
6110
6111    case SK_StdInitializerList: {
6112      S.Diag(CurInit.get()->getExprLoc(),
6113             diag::warn_cxx98_compat_initializer_list_init)
6114        << CurInit.get()->getSourceRange();
6115
6116      // Maybe lifetime-extend the array temporary's subobjects to match the
6117      // entity's lifetime.
6118      const ValueDecl *ExtendingDecl =
6119          getDeclForTemporaryLifetimeExtension(Entity);
6120      if (ExtendingDecl) {
6121        performLifetimeExtension(CurInit.get(), ExtendingDecl);
6122        warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
6123      }
6124
6125      // Materialize the temporary into memory.
6126      MaterializeTemporaryExpr *MTE = new (S.Context)
6127          MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6128                                   /*lvalue reference*/ false, ExtendingDecl);
6129
6130      // Wrap it in a construction of a std::initializer_list<T>.
6131      CurInit = S.Owned(
6132          new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6133
6134      // Bind the result, in case the library has given initializer_list a
6135      // non-trivial destructor.
6136      if (shouldBindAsTemporary(Entity))
6137        CurInit = S.MaybeBindToTemporary(CurInit.take());
6138      break;
6139    }
6140
6141    case SK_OCLSamplerInit: {
6142      assert(Step->Type->isSamplerT() &&
6143             "Sampler initialization on non sampler type.");
6144
6145      QualType SourceType = CurInit.get()->getType();
6146
6147      if (Entity.isParameterKind()) {
6148        if (!SourceType->isSamplerT())
6149          S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6150            << SourceType;
6151      } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
6152        llvm_unreachable("Invalid EntityKind!");
6153      }
6154
6155      break;
6156    }
6157    case SK_OCLZeroEvent: {
6158      assert(Step->Type->isEventT() &&
6159             "Event initialization on non event type.");
6160
6161      CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6162                                    CK_ZeroToOCLEvent,
6163                                    CurInit.get()->getValueKind());
6164      break;
6165    }
6166    }
6167  }
6168
6169  // Diagnose non-fatal problems with the completed initialization.
6170  if (Entity.getKind() == InitializedEntity::EK_Member &&
6171      cast<FieldDecl>(Entity.getDecl())->isBitField())
6172    S.CheckBitFieldInitialization(Kind.getLocation(),
6173                                  cast<FieldDecl>(Entity.getDecl()),
6174                                  CurInit.get());
6175
6176  return CurInit;
6177}
6178
6179/// Somewhere within T there is an uninitialized reference subobject.
6180/// Dig it out and diagnose it.
6181static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6182                                           QualType T) {
6183  if (T->isReferenceType()) {
6184    S.Diag(Loc, diag::err_reference_without_init)
6185      << T.getNonReferenceType();
6186    return true;
6187  }
6188
6189  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6190  if (!RD || !RD->hasUninitializedReferenceMember())
6191    return false;
6192
6193  for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6194                                     FE = RD->field_end(); FI != FE; ++FI) {
6195    if (FI->isUnnamedBitfield())
6196      continue;
6197
6198    if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6199      S.Diag(Loc, diag::note_value_initialization_here) << RD;
6200      return true;
6201    }
6202  }
6203
6204  for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6205                                          BE = RD->bases_end();
6206       BI != BE; ++BI) {
6207    if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6208      S.Diag(Loc, diag::note_value_initialization_here) << RD;
6209      return true;
6210    }
6211  }
6212
6213  return false;
6214}
6215
6216
6217//===----------------------------------------------------------------------===//
6218// Diagnose initialization failures
6219//===----------------------------------------------------------------------===//
6220
6221/// Emit notes associated with an initialization that failed due to a
6222/// "simple" conversion failure.
6223static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6224                                   Expr *op) {
6225  QualType destType = entity.getType();
6226  if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6227      op->getType()->isObjCObjectPointerType()) {
6228
6229    // Emit a possible note about the conversion failing because the
6230    // operand is a message send with a related result type.
6231    S.EmitRelatedResultTypeNote(op);
6232
6233    // Emit a possible note about a return failing because we're
6234    // expecting a related result type.
6235    if (entity.getKind() == InitializedEntity::EK_Result)
6236      S.EmitRelatedResultTypeNoteForReturn(destType);
6237  }
6238}
6239
6240bool InitializationSequence::Diagnose(Sema &S,
6241                                      const InitializedEntity &Entity,
6242                                      const InitializationKind &Kind,
6243                                      ArrayRef<Expr *> Args) {
6244  if (!Failed())
6245    return false;
6246
6247  QualType DestType = Entity.getType();
6248  switch (Failure) {
6249  case FK_TooManyInitsForReference:
6250    // FIXME: Customize for the initialized entity?
6251    if (Args.empty()) {
6252      // Dig out the reference subobject which is uninitialized and diagnose it.
6253      // If this is value-initialization, this could be nested some way within
6254      // the target type.
6255      assert(Kind.getKind() == InitializationKind::IK_Value ||
6256             DestType->isReferenceType());
6257      bool Diagnosed =
6258        DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6259      assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6260      (void)Diagnosed;
6261    } else  // FIXME: diagnostic below could be better!
6262      S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
6263        << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
6264    break;
6265
6266  case FK_ArrayNeedsInitList:
6267    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
6268    break;
6269  case FK_ArrayNeedsInitListOrStringLiteral:
6270    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6271    break;
6272  case FK_ArrayNeedsInitListOrWideStringLiteral:
6273    S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6274    break;
6275  case FK_NarrowStringIntoWideCharArray:
6276    S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6277    break;
6278  case FK_WideStringIntoCharArray:
6279    S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6280    break;
6281  case FK_IncompatWideStringIntoWideChar:
6282    S.Diag(Kind.getLocation(),
6283           diag::err_array_init_incompat_wide_string_into_wchar);
6284    break;
6285  case FK_ArrayTypeMismatch:
6286  case FK_NonConstantArrayInit:
6287    S.Diag(Kind.getLocation(),
6288           (Failure == FK_ArrayTypeMismatch
6289              ? diag::err_array_init_different_type
6290              : diag::err_array_init_non_constant_array))
6291      << DestType.getNonReferenceType()
6292      << Args[0]->getType()
6293      << Args[0]->getSourceRange();
6294    break;
6295
6296  case FK_VariableLengthArrayHasInitializer:
6297    S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6298      << Args[0]->getSourceRange();
6299    break;
6300
6301  case FK_AddressOfOverloadFailed: {
6302    DeclAccessPair Found;
6303    S.ResolveAddressOfOverloadedFunction(Args[0],
6304                                         DestType.getNonReferenceType(),
6305                                         true,
6306                                         Found);
6307    break;
6308  }
6309
6310  case FK_ReferenceInitOverloadFailed:
6311  case FK_UserConversionOverloadFailed:
6312    switch (FailedOverloadResult) {
6313    case OR_Ambiguous:
6314      if (Failure == FK_UserConversionOverloadFailed)
6315        S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6316          << Args[0]->getType() << DestType
6317          << Args[0]->getSourceRange();
6318      else
6319        S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6320          << DestType << Args[0]->getType()
6321          << Args[0]->getSourceRange();
6322
6323      FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6324      break;
6325
6326    case OR_No_Viable_Function:
6327      if (!S.RequireCompleteType(Kind.getLocation(),
6328                                 DestType.getNonReferenceType(),
6329                          diag::err_typecheck_nonviable_condition_incomplete,
6330                               Args[0]->getType(), Args[0]->getSourceRange()))
6331        S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6332          << Args[0]->getType() << Args[0]->getSourceRange()
6333          << DestType.getNonReferenceType();
6334
6335      FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6336      break;
6337
6338    case OR_Deleted: {
6339      S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6340        << Args[0]->getType() << DestType.getNonReferenceType()
6341        << Args[0]->getSourceRange();
6342      OverloadCandidateSet::iterator Best;
6343      OverloadingResult Ovl
6344        = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6345                                                true);
6346      if (Ovl == OR_Deleted) {
6347        S.NoteDeletedFunction(Best->Function);
6348      } else {
6349        llvm_unreachable("Inconsistent overload resolution?");
6350      }
6351      break;
6352    }
6353
6354    case OR_Success:
6355      llvm_unreachable("Conversion did not fail!");
6356    }
6357    break;
6358
6359  case FK_NonConstLValueReferenceBindingToTemporary:
6360    if (isa<InitListExpr>(Args[0])) {
6361      S.Diag(Kind.getLocation(),
6362             diag::err_lvalue_reference_bind_to_initlist)
6363      << DestType.getNonReferenceType().isVolatileQualified()
6364      << DestType.getNonReferenceType()
6365      << Args[0]->getSourceRange();
6366      break;
6367    }
6368    // Intentional fallthrough
6369
6370  case FK_NonConstLValueReferenceBindingToUnrelated:
6371    S.Diag(Kind.getLocation(),
6372           Failure == FK_NonConstLValueReferenceBindingToTemporary
6373             ? diag::err_lvalue_reference_bind_to_temporary
6374             : diag::err_lvalue_reference_bind_to_unrelated)
6375      << DestType.getNonReferenceType().isVolatileQualified()
6376      << DestType.getNonReferenceType()
6377      << Args[0]->getType()
6378      << Args[0]->getSourceRange();
6379    break;
6380
6381  case FK_RValueReferenceBindingToLValue:
6382    S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
6383      << DestType.getNonReferenceType() << Args[0]->getType()
6384      << Args[0]->getSourceRange();
6385    break;
6386
6387  case FK_ReferenceInitDropsQualifiers:
6388    S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6389      << DestType.getNonReferenceType()
6390      << Args[0]->getType()
6391      << Args[0]->getSourceRange();
6392    break;
6393
6394  case FK_ReferenceInitFailed:
6395    S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6396      << DestType.getNonReferenceType()
6397      << Args[0]->isLValue()
6398      << Args[0]->getType()
6399      << Args[0]->getSourceRange();
6400    emitBadConversionNotes(S, Entity, Args[0]);
6401    break;
6402
6403  case FK_ConversionFailed: {
6404    QualType FromType = Args[0]->getType();
6405    PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
6406      << (int)Entity.getKind()
6407      << DestType
6408      << Args[0]->isLValue()
6409      << FromType
6410      << Args[0]->getSourceRange();
6411    S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6412    S.Diag(Kind.getLocation(), PDiag);
6413    emitBadConversionNotes(S, Entity, Args[0]);
6414    break;
6415  }
6416
6417  case FK_ConversionFromPropertyFailed:
6418    // No-op. This error has already been reported.
6419    break;
6420
6421  case FK_TooManyInitsForScalar: {
6422    SourceRange R;
6423
6424    if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
6425      R = SourceRange(InitList->getInit(0)->getLocEnd(),
6426                      InitList->getLocEnd());
6427    else
6428      R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
6429
6430    R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6431    if (Kind.isCStyleOrFunctionalCast())
6432      S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6433        << R;
6434    else
6435      S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6436        << /*scalar=*/2 << R;
6437    break;
6438  }
6439
6440  case FK_ReferenceBindingToInitList:
6441    S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6442      << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6443    break;
6444
6445  case FK_InitListBadDestinationType:
6446    S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6447      << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6448    break;
6449
6450  case FK_ListConstructorOverloadFailed:
6451  case FK_ConstructorOverloadFailed: {
6452    SourceRange ArgsRange;
6453    if (Args.size())
6454      ArgsRange = SourceRange(Args.front()->getLocStart(),
6455                              Args.back()->getLocEnd());
6456
6457    if (Failure == FK_ListConstructorOverloadFailed) {
6458      assert(Args.size() == 1 && "List construction from other than 1 argument.");
6459      InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6460      Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
6461    }
6462
6463    // FIXME: Using "DestType" for the entity we're printing is probably
6464    // bad.
6465    switch (FailedOverloadResult) {
6466      case OR_Ambiguous:
6467        S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6468          << DestType << ArgsRange;
6469        FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6470        break;
6471
6472      case OR_No_Viable_Function:
6473        if (Kind.getKind() == InitializationKind::IK_Default &&
6474            (Entity.getKind() == InitializedEntity::EK_Base ||
6475             Entity.getKind() == InitializedEntity::EK_Member) &&
6476            isa<CXXConstructorDecl>(S.CurContext)) {
6477          // This is implicit default initialization of a member or
6478          // base within a constructor. If no viable function was
6479          // found, notify the user that she needs to explicitly
6480          // initialize this base/member.
6481          CXXConstructorDecl *Constructor
6482            = cast<CXXConstructorDecl>(S.CurContext);
6483          if (Entity.getKind() == InitializedEntity::EK_Base) {
6484            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6485              << (Constructor->getInheritedConstructor() ? 2 :
6486                  Constructor->isImplicit() ? 1 : 0)
6487              << S.Context.getTypeDeclType(Constructor->getParent())
6488              << /*base=*/0
6489              << Entity.getType();
6490
6491            RecordDecl *BaseDecl
6492              = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6493                                                                  ->getDecl();
6494            S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6495              << S.Context.getTagDeclType(BaseDecl);
6496          } else {
6497            S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6498              << (Constructor->getInheritedConstructor() ? 2 :
6499                  Constructor->isImplicit() ? 1 : 0)
6500              << S.Context.getTypeDeclType(Constructor->getParent())
6501              << /*member=*/1
6502              << Entity.getName();
6503            S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6504
6505            if (const RecordType *Record
6506                                 = Entity.getType()->getAs<RecordType>())
6507              S.Diag(Record->getDecl()->getLocation(),
6508                     diag::note_previous_decl)
6509                << S.Context.getTagDeclType(Record->getDecl());
6510          }
6511          break;
6512        }
6513
6514        S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6515          << DestType << ArgsRange;
6516        FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6517        break;
6518
6519      case OR_Deleted: {
6520        OverloadCandidateSet::iterator Best;
6521        OverloadingResult Ovl
6522          = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6523        if (Ovl != OR_Deleted) {
6524          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6525            << true << DestType << ArgsRange;
6526          llvm_unreachable("Inconsistent overload resolution?");
6527          break;
6528        }
6529
6530        // If this is a defaulted or implicitly-declared function, then
6531        // it was implicitly deleted. Make it clear that the deletion was
6532        // implicit.
6533        if (S.isImplicitlyDeleted(Best->Function))
6534          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
6535            << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
6536            << DestType << ArgsRange;
6537        else
6538          S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6539            << true << DestType << ArgsRange;
6540
6541        S.NoteDeletedFunction(Best->Function);
6542        break;
6543      }
6544
6545      case OR_Success:
6546        llvm_unreachable("Conversion did not fail!");
6547    }
6548  }
6549  break;
6550
6551  case FK_DefaultInitOfConst:
6552    if (Entity.getKind() == InitializedEntity::EK_Member &&
6553        isa<CXXConstructorDecl>(S.CurContext)) {
6554      // This is implicit default-initialization of a const member in
6555      // a constructor. Complain that it needs to be explicitly
6556      // initialized.
6557      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6558      S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
6559        << (Constructor->getInheritedConstructor() ? 2 :
6560            Constructor->isImplicit() ? 1 : 0)
6561        << S.Context.getTypeDeclType(Constructor->getParent())
6562        << /*const=*/1
6563        << Entity.getName();
6564      S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6565        << Entity.getName();
6566    } else {
6567      S.Diag(Kind.getLocation(), diag::err_default_init_const)
6568        << DestType << (bool)DestType->getAs<RecordType>();
6569    }
6570    break;
6571
6572  case FK_Incomplete:
6573    S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
6574                          diag::err_init_incomplete_type);
6575    break;
6576
6577  case FK_ListInitializationFailed: {
6578    // Run the init list checker again to emit diagnostics.
6579    InitListExpr* InitList = cast<InitListExpr>(Args[0]);
6580    QualType DestType = Entity.getType();
6581    InitListChecker DiagnoseInitList(S, Entity, InitList,
6582            DestType, /*VerifyOnly=*/false);
6583    assert(DiagnoseInitList.HadError() &&
6584           "Inconsistent init list check result.");
6585    break;
6586  }
6587
6588  case FK_PlaceholderType: {
6589    // FIXME: Already diagnosed!
6590    break;
6591  }
6592
6593  case FK_ExplicitConstructor: {
6594    S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6595      << Args[0]->getSourceRange();
6596    OverloadCandidateSet::iterator Best;
6597    OverloadingResult Ovl
6598      = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6599    (void)Ovl;
6600    assert(Ovl == OR_Success && "Inconsistent overload resolution");
6601    CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6602    S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6603    break;
6604  }
6605  }
6606
6607  PrintInitLocationNote(S, Entity);
6608  return true;
6609}
6610
6611void InitializationSequence::dump(raw_ostream &OS) const {
6612  switch (SequenceKind) {
6613  case FailedSequence: {
6614    OS << "Failed sequence: ";
6615    switch (Failure) {
6616    case FK_TooManyInitsForReference:
6617      OS << "too many initializers for reference";
6618      break;
6619
6620    case FK_ArrayNeedsInitList:
6621      OS << "array requires initializer list";
6622      break;
6623
6624    case FK_ArrayNeedsInitListOrStringLiteral:
6625      OS << "array requires initializer list or string literal";
6626      break;
6627
6628    case FK_ArrayNeedsInitListOrWideStringLiteral:
6629      OS << "array requires initializer list or wide string literal";
6630      break;
6631
6632    case FK_NarrowStringIntoWideCharArray:
6633      OS << "narrow string into wide char array";
6634      break;
6635
6636    case FK_WideStringIntoCharArray:
6637      OS << "wide string into char array";
6638      break;
6639
6640    case FK_IncompatWideStringIntoWideChar:
6641      OS << "incompatible wide string into wide char array";
6642      break;
6643
6644    case FK_ArrayTypeMismatch:
6645      OS << "array type mismatch";
6646      break;
6647
6648    case FK_NonConstantArrayInit:
6649      OS << "non-constant array initializer";
6650      break;
6651
6652    case FK_AddressOfOverloadFailed:
6653      OS << "address of overloaded function failed";
6654      break;
6655
6656    case FK_ReferenceInitOverloadFailed:
6657      OS << "overload resolution for reference initialization failed";
6658      break;
6659
6660    case FK_NonConstLValueReferenceBindingToTemporary:
6661      OS << "non-const lvalue reference bound to temporary";
6662      break;
6663
6664    case FK_NonConstLValueReferenceBindingToUnrelated:
6665      OS << "non-const lvalue reference bound to unrelated type";
6666      break;
6667
6668    case FK_RValueReferenceBindingToLValue:
6669      OS << "rvalue reference bound to an lvalue";
6670      break;
6671
6672    case FK_ReferenceInitDropsQualifiers:
6673      OS << "reference initialization drops qualifiers";
6674      break;
6675
6676    case FK_ReferenceInitFailed:
6677      OS << "reference initialization failed";
6678      break;
6679
6680    case FK_ConversionFailed:
6681      OS << "conversion failed";
6682      break;
6683
6684    case FK_ConversionFromPropertyFailed:
6685      OS << "conversion from property failed";
6686      break;
6687
6688    case FK_TooManyInitsForScalar:
6689      OS << "too many initializers for scalar";
6690      break;
6691
6692    case FK_ReferenceBindingToInitList:
6693      OS << "referencing binding to initializer list";
6694      break;
6695
6696    case FK_InitListBadDestinationType:
6697      OS << "initializer list for non-aggregate, non-scalar type";
6698      break;
6699
6700    case FK_UserConversionOverloadFailed:
6701      OS << "overloading failed for user-defined conversion";
6702      break;
6703
6704    case FK_ConstructorOverloadFailed:
6705      OS << "constructor overloading failed";
6706      break;
6707
6708    case FK_DefaultInitOfConst:
6709      OS << "default initialization of a const variable";
6710      break;
6711
6712    case FK_Incomplete:
6713      OS << "initialization of incomplete type";
6714      break;
6715
6716    case FK_ListInitializationFailed:
6717      OS << "list initialization checker failure";
6718      break;
6719
6720    case FK_VariableLengthArrayHasInitializer:
6721      OS << "variable length array has an initializer";
6722      break;
6723
6724    case FK_PlaceholderType:
6725      OS << "initializer expression isn't contextually valid";
6726      break;
6727
6728    case FK_ListConstructorOverloadFailed:
6729      OS << "list constructor overloading failed";
6730      break;
6731
6732    case FK_ExplicitConstructor:
6733      OS << "list copy initialization chose explicit constructor";
6734      break;
6735    }
6736    OS << '\n';
6737    return;
6738  }
6739
6740  case DependentSequence:
6741    OS << "Dependent sequence\n";
6742    return;
6743
6744  case NormalSequence:
6745    OS << "Normal sequence: ";
6746    break;
6747  }
6748
6749  for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6750    if (S != step_begin()) {
6751      OS << " -> ";
6752    }
6753
6754    switch (S->Kind) {
6755    case SK_ResolveAddressOfOverloadedFunction:
6756      OS << "resolve address of overloaded function";
6757      break;
6758
6759    case SK_CastDerivedToBaseRValue:
6760      OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6761      break;
6762
6763    case SK_CastDerivedToBaseXValue:
6764      OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6765      break;
6766
6767    case SK_CastDerivedToBaseLValue:
6768      OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6769      break;
6770
6771    case SK_BindReference:
6772      OS << "bind reference to lvalue";
6773      break;
6774
6775    case SK_BindReferenceToTemporary:
6776      OS << "bind reference to a temporary";
6777      break;
6778
6779    case SK_ExtraneousCopyToTemporary:
6780      OS << "extraneous C++03 copy to temporary";
6781      break;
6782
6783    case SK_UserConversion:
6784      OS << "user-defined conversion via " << *S->Function.Function;
6785      break;
6786
6787    case SK_QualificationConversionRValue:
6788      OS << "qualification conversion (rvalue)";
6789      break;
6790
6791    case SK_QualificationConversionXValue:
6792      OS << "qualification conversion (xvalue)";
6793      break;
6794
6795    case SK_QualificationConversionLValue:
6796      OS << "qualification conversion (lvalue)";
6797      break;
6798
6799    case SK_LValueToRValue:
6800      OS << "load (lvalue to rvalue)";
6801      break;
6802
6803    case SK_ConversionSequence:
6804      OS << "implicit conversion sequence (";
6805      S->ICS->DebugPrint(); // FIXME: use OS
6806      OS << ")";
6807      break;
6808
6809    case SK_ConversionSequenceNoNarrowing:
6810      OS << "implicit conversion sequence with narrowing prohibited (";
6811      S->ICS->DebugPrint(); // FIXME: use OS
6812      OS << ")";
6813      break;
6814
6815    case SK_ListInitialization:
6816      OS << "list aggregate initialization";
6817      break;
6818
6819    case SK_ListConstructorCall:
6820      OS << "list initialization via constructor";
6821      break;
6822
6823    case SK_UnwrapInitList:
6824      OS << "unwrap reference initializer list";
6825      break;
6826
6827    case SK_RewrapInitList:
6828      OS << "rewrap reference initializer list";
6829      break;
6830
6831    case SK_ConstructorInitialization:
6832      OS << "constructor initialization";
6833      break;
6834
6835    case SK_ZeroInitialization:
6836      OS << "zero initialization";
6837      break;
6838
6839    case SK_CAssignment:
6840      OS << "C assignment";
6841      break;
6842
6843    case SK_StringInit:
6844      OS << "string initialization";
6845      break;
6846
6847    case SK_ObjCObjectConversion:
6848      OS << "Objective-C object conversion";
6849      break;
6850
6851    case SK_ArrayInit:
6852      OS << "array initialization";
6853      break;
6854
6855    case SK_ParenthesizedArrayInit:
6856      OS << "parenthesized array initialization";
6857      break;
6858
6859    case SK_PassByIndirectCopyRestore:
6860      OS << "pass by indirect copy and restore";
6861      break;
6862
6863    case SK_PassByIndirectRestore:
6864      OS << "pass by indirect restore";
6865      break;
6866
6867    case SK_ProduceObjCObject:
6868      OS << "Objective-C object retension";
6869      break;
6870
6871    case SK_StdInitializerList:
6872      OS << "std::initializer_list from initializer list";
6873      break;
6874
6875    case SK_OCLSamplerInit:
6876      OS << "OpenCL sampler_t from integer constant";
6877      break;
6878
6879    case SK_OCLZeroEvent:
6880      OS << "OpenCL event_t from zero";
6881      break;
6882    }
6883
6884    OS << " [" << S->Type.getAsString() << ']';
6885  }
6886
6887  OS << '\n';
6888}
6889
6890void InitializationSequence::dump() const {
6891  dump(llvm::errs());
6892}
6893
6894static void DiagnoseNarrowingInInitList(Sema &S,
6895                                        const ImplicitConversionSequence &ICS,
6896                                        QualType PreNarrowingType,
6897                                        QualType EntityType,
6898                                        const Expr *PostInit) {
6899  const StandardConversionSequence *SCS = 0;
6900  switch (ICS.getKind()) {
6901  case ImplicitConversionSequence::StandardConversion:
6902    SCS = &ICS.Standard;
6903    break;
6904  case ImplicitConversionSequence::UserDefinedConversion:
6905    SCS = &ICS.UserDefined.After;
6906    break;
6907  case ImplicitConversionSequence::AmbiguousConversion:
6908  case ImplicitConversionSequence::EllipsisConversion:
6909  case ImplicitConversionSequence::BadConversion:
6910    return;
6911  }
6912
6913  // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6914  APValue ConstantValue;
6915  QualType ConstantType;
6916  switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6917                                ConstantType)) {
6918  case NK_Not_Narrowing:
6919    // No narrowing occurred.
6920    return;
6921
6922  case NK_Type_Narrowing:
6923    // This was a floating-to-integer conversion, which is always considered a
6924    // narrowing conversion even if the value is a constant and can be
6925    // represented exactly as an integer.
6926    S.Diag(PostInit->getLocStart(),
6927           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6928             diag::warn_init_list_type_narrowing
6929           : S.isSFINAEContext()?
6930             diag::err_init_list_type_narrowing_sfinae
6931           : diag::err_init_list_type_narrowing)
6932      << PostInit->getSourceRange()
6933      << PreNarrowingType.getLocalUnqualifiedType()
6934      << EntityType.getLocalUnqualifiedType();
6935    break;
6936
6937  case NK_Constant_Narrowing:
6938    // A constant value was narrowed.
6939    S.Diag(PostInit->getLocStart(),
6940           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6941             diag::warn_init_list_constant_narrowing
6942           : S.isSFINAEContext()?
6943             diag::err_init_list_constant_narrowing_sfinae
6944           : diag::err_init_list_constant_narrowing)
6945      << PostInit->getSourceRange()
6946      << ConstantValue.getAsString(S.getASTContext(), ConstantType)
6947      << EntityType.getLocalUnqualifiedType();
6948    break;
6949
6950  case NK_Variable_Narrowing:
6951    // A variable's value may have been narrowed.
6952    S.Diag(PostInit->getLocStart(),
6953           S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11?
6954             diag::warn_init_list_variable_narrowing
6955           : S.isSFINAEContext()?
6956             diag::err_init_list_variable_narrowing_sfinae
6957           : diag::err_init_list_variable_narrowing)
6958      << PostInit->getSourceRange()
6959      << PreNarrowingType.getLocalUnqualifiedType()
6960      << EntityType.getLocalUnqualifiedType();
6961    break;
6962  }
6963
6964  SmallString<128> StaticCast;
6965  llvm::raw_svector_ostream OS(StaticCast);
6966  OS << "static_cast<";
6967  if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
6968    // It's important to use the typedef's name if there is one so that the
6969    // fixit doesn't break code using types like int64_t.
6970    //
6971    // FIXME: This will break if the typedef requires qualification.  But
6972    // getQualifiedNameAsString() includes non-machine-parsable components.
6973    OS << *TT->getDecl();
6974  } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
6975    OS << BT->getName(S.getLangOpts());
6976  else {
6977    // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
6978    // with a broken cast.
6979    return;
6980  }
6981  OS << ">(";
6982  S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
6983    << PostInit->getSourceRange()
6984    << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
6985    << FixItHint::CreateInsertion(
6986      S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
6987}
6988
6989//===----------------------------------------------------------------------===//
6990// Initialization helper functions
6991//===----------------------------------------------------------------------===//
6992bool
6993Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
6994                                   ExprResult Init) {
6995  if (Init.isInvalid())
6996    return false;
6997
6998  Expr *InitE = Init.get();
6999  assert(InitE && "No initialization expression");
7000
7001  InitializationKind Kind
7002    = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
7003  InitializationSequence Seq(*this, Entity, Kind, InitE);
7004  return !Seq.Failed();
7005}
7006
7007ExprResult
7008Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7009                                SourceLocation EqualLoc,
7010                                ExprResult Init,
7011                                bool TopLevelOfInitList,
7012                                bool AllowExplicit) {
7013  if (Init.isInvalid())
7014    return ExprError();
7015
7016  Expr *InitE = Init.get();
7017  assert(InitE && "No initialization expression?");
7018
7019  if (EqualLoc.isInvalid())
7020    EqualLoc = InitE->getLocStart();
7021
7022  InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
7023                                                           EqualLoc,
7024                                                           AllowExplicit);
7025  InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
7026  Init.release();
7027
7028  ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
7029
7030  return Result;
7031}
7032