]> CyberLeo.Net >> Repos - FreeBSD/releng/10.2.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaInit.cpp
- Copy stable/10@285827 to releng/10.2 in preparation for 10.2-RC1
[FreeBSD/releng/10.2.git] / contrib / llvm / tools / clang / lib / Sema / SemaInit.cpp
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>
29 using 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).
37 static 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
47 enum 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.
59 static 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
123 static 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.
133 static 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
149 static 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.
234 namespace {
235 class 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
326 public:
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
337 void 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
349 void 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.
427 void
428 InitListChecker::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
557 InitListChecker::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
577 int 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
587 int 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.
608 void 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.
680 void 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
759 void 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
816 void 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
951 void 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
988 void 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
1058 void 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
1115 void 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
1230 void 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
1359 bool 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
1398 void 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 ///
1584 static 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.
1614 static 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
1630 static 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
1642 namespace {
1643
1644 // Callback to only accept typo corrections that are for field members of
1645 // the given struct or union.
1646 class 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.
1697 bool
1698 InitListChecker::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         FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
1873         if (CurrentField && CurrentField != *Field) {
1874           assert(StructuredList->getNumInits() == 1
1875                  && "A union should never have more than one initializer!");
1876
1877           // we're about to throw away an initializer, emit warning
1878           SemaRef.Diag(D->getFieldLoc(),
1879                        diag::warn_initializer_overrides)
1880             << D->getSourceRange();
1881           Expr *ExistingInit = StructuredList->getInit(0);
1882           SemaRef.Diag(ExistingInit->getLocStart(),
1883                        diag::note_previous_initializer)
1884             << /*FIXME:has side effects=*/0
1885             << ExistingInit->getSourceRange();
1886
1887           // remove existing initializer
1888           StructuredList->resizeInits(SemaRef.Context, 0);
1889           StructuredList->setInitializedFieldInUnion(0);
1890         }
1891
1892         StructuredList->setInitializedFieldInUnion(*Field);
1893       }
1894     }
1895
1896     // Make sure we can use this declaration.
1897     bool InvalidUse;
1898     if (VerifyOnly)
1899       InvalidUse = !SemaRef.CanUseDecl(*Field);
1900     else
1901       InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1902     if (InvalidUse) {
1903       ++Index;
1904       return true;
1905     }
1906
1907     if (!VerifyOnly) {
1908       // Update the designator with the field declaration.
1909       D->setField(*Field);
1910
1911       // Make sure that our non-designated initializer list has space
1912       // for a subobject corresponding to this field.
1913       if (FieldIndex >= StructuredList->getNumInits())
1914         StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1915     }
1916
1917     // This designator names a flexible array member.
1918     if (Field->getType()->isIncompleteArrayType()) {
1919       bool Invalid = false;
1920       if ((DesigIdx + 1) != DIE->size()) {
1921         // We can't designate an object within the flexible array
1922         // member (because GCC doesn't allow it).
1923         if (!VerifyOnly) {
1924           DesignatedInitExpr::Designator *NextD
1925             = DIE->getDesignator(DesigIdx + 1);
1926           SemaRef.Diag(NextD->getLocStart(),
1927                         diag::err_designator_into_flexible_array_member)
1928             << SourceRange(NextD->getLocStart(),
1929                            DIE->getLocEnd());
1930           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1931             << *Field;
1932         }
1933         Invalid = true;
1934       }
1935
1936       if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1937           !isa<StringLiteral>(DIE->getInit())) {
1938         // The initializer is not an initializer list.
1939         if (!VerifyOnly) {
1940           SemaRef.Diag(DIE->getInit()->getLocStart(),
1941                         diag::err_flexible_array_init_needs_braces)
1942             << DIE->getInit()->getSourceRange();
1943           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1944             << *Field;
1945         }
1946         Invalid = true;
1947       }
1948
1949       // Check GNU flexible array initializer.
1950       if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1951                                              TopLevelObject))
1952         Invalid = true;
1953
1954       if (Invalid) {
1955         ++Index;
1956         return true;
1957       }
1958
1959       // Initialize the array.
1960       bool prevHadError = hadError;
1961       unsigned newStructuredIndex = FieldIndex;
1962       unsigned OldIndex = Index;
1963       IList->setInit(Index, DIE->getInit());
1964
1965       InitializedEntity MemberEntity =
1966         InitializedEntity::InitializeMember(*Field, &Entity);
1967       CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1968                           StructuredList, newStructuredIndex);
1969
1970       IList->setInit(OldIndex, DIE);
1971       if (hadError && !prevHadError) {
1972         ++Field;
1973         ++FieldIndex;
1974         if (NextField)
1975           *NextField = Field;
1976         StructuredIndex = FieldIndex;
1977         return true;
1978       }
1979     } else {
1980       // Recurse to check later designated subobjects.
1981       QualType FieldType = Field->getType();
1982       unsigned newStructuredIndex = FieldIndex;
1983
1984       InitializedEntity MemberEntity =
1985         InitializedEntity::InitializeMember(*Field, &Entity);
1986       if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1987                                      FieldType, 0, 0, Index,
1988                                      StructuredList, newStructuredIndex,
1989                                      true, false))
1990         return true;
1991     }
1992
1993     // Find the position of the next field to be initialized in this
1994     // subobject.
1995     ++Field;
1996     ++FieldIndex;
1997
1998     // If this the first designator, our caller will continue checking
1999     // the rest of this struct/class/union subobject.
2000     if (IsFirstDesignator) {
2001       if (NextField)
2002         *NextField = Field;
2003       StructuredIndex = FieldIndex;
2004       return false;
2005     }
2006
2007     if (!FinishSubobjectInit)
2008       return false;
2009
2010     // We've already initialized something in the union; we're done.
2011     if (RT->getDecl()->isUnion())
2012       return hadError;
2013
2014     // Check the remaining fields within this class/struct/union subobject.
2015     bool prevHadError = hadError;
2016
2017     CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
2018                           StructuredList, FieldIndex);
2019     return hadError && !prevHadError;
2020   }
2021
2022   // C99 6.7.8p6:
2023   //
2024   //   If a designator has the form
2025   //
2026   //      [ constant-expression ]
2027   //
2028   //   then the current object (defined below) shall have array
2029   //   type and the expression shall be an integer constant
2030   //   expression. If the array is of unknown size, any
2031   //   nonnegative value is valid.
2032   //
2033   // Additionally, cope with the GNU extension that permits
2034   // designators of the form
2035   //
2036   //      [ constant-expression ... constant-expression ]
2037   const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2038   if (!AT) {
2039     if (!VerifyOnly)
2040       SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2041         << CurrentObjectType;
2042     ++Index;
2043     return true;
2044   }
2045
2046   Expr *IndexExpr = 0;
2047   llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2048   if (D->isArrayDesignator()) {
2049     IndexExpr = DIE->getArrayIndex(*D);
2050     DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2051     DesignatedEndIndex = DesignatedStartIndex;
2052   } else {
2053     assert(D->isArrayRangeDesignator() && "Need array-range designator");
2054
2055     DesignatedStartIndex =
2056       DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2057     DesignatedEndIndex =
2058       DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2059     IndexExpr = DIE->getArrayRangeEnd(*D);
2060
2061     // Codegen can't handle evaluating array range designators that have side
2062     // effects, because we replicate the AST value for each initialized element.
2063     // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2064     // elements with something that has a side effect, so codegen can emit an
2065     // "error unsupported" error instead of miscompiling the app.
2066     if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2067         DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
2068       FullyStructuredList->sawArrayRangeDesignator();
2069   }
2070
2071   if (isa<ConstantArrayType>(AT)) {
2072     llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2073     DesignatedStartIndex
2074       = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2075     DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2076     DesignatedEndIndex
2077       = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2078     DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2079     if (DesignatedEndIndex >= MaxElements) {
2080       if (!VerifyOnly)
2081         SemaRef.Diag(IndexExpr->getLocStart(),
2082                       diag::err_array_designator_too_large)
2083           << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
2084           << IndexExpr->getSourceRange();
2085       ++Index;
2086       return true;
2087     }
2088   } else {
2089     // Make sure the bit-widths and signedness match.
2090     if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
2091       DesignatedEndIndex
2092         = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
2093     else if (DesignatedStartIndex.getBitWidth() <
2094              DesignatedEndIndex.getBitWidth())
2095       DesignatedStartIndex
2096         = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
2097     DesignatedStartIndex.setIsUnsigned(true);
2098     DesignatedEndIndex.setIsUnsigned(true);
2099   }
2100
2101   if (!VerifyOnly && StructuredList->isStringLiteralInit()) {
2102     // We're modifying a string literal init; we have to decompose the string
2103     // so we can modify the individual characters.
2104     ASTContext &Context = SemaRef.Context;
2105     Expr *SubExpr = StructuredList->getInit(0)->IgnoreParens();
2106
2107     // Compute the character type
2108     QualType CharTy = AT->getElementType();
2109
2110     // Compute the type of the integer literals.
2111     QualType PromotedCharTy = CharTy;
2112     if (CharTy->isPromotableIntegerType())
2113       PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2114     unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2115
2116     if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2117       // Get the length of the string.
2118       uint64_t StrLen = SL->getLength();
2119       if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2120         StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2121       StructuredList->resizeInits(Context, StrLen);
2122
2123       // Build a literal for each character in the string, and put them into
2124       // the init list.
2125       for (unsigned i = 0, e = StrLen; i != e; ++i) {
2126         llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2127         Expr *Init = new (Context) IntegerLiteral(
2128             Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2129         if (CharTy != PromotedCharTy)
2130           Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2131                                           Init, 0, VK_RValue);
2132         StructuredList->updateInit(Context, i, Init);
2133       }
2134     } else {
2135       ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2136       std::string Str;
2137       Context.getObjCEncodingForType(E->getEncodedType(), Str);
2138
2139       // Get the length of the string.
2140       uint64_t StrLen = Str.size();
2141       if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2142         StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2143       StructuredList->resizeInits(Context, StrLen);
2144
2145       // Build a literal for each character in the string, and put them into
2146       // the init list.
2147       for (unsigned i = 0, e = StrLen; i != e; ++i) {
2148         llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2149         Expr *Init = new (Context) IntegerLiteral(
2150             Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2151         if (CharTy != PromotedCharTy)
2152           Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2153                                           Init, 0, VK_RValue);
2154         StructuredList->updateInit(Context, i, Init);
2155       }
2156     }
2157   }
2158
2159   // Make sure that our non-designated initializer list has space
2160   // for a subobject corresponding to this array element.
2161   if (!VerifyOnly &&
2162       DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
2163     StructuredList->resizeInits(SemaRef.Context,
2164                                 DesignatedEndIndex.getZExtValue() + 1);
2165
2166   // Repeatedly perform subobject initializations in the range
2167   // [DesignatedStartIndex, DesignatedEndIndex].
2168
2169   // Move to the next designator
2170   unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2171   unsigned OldIndex = Index;
2172
2173   InitializedEntity ElementEntity =
2174     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
2175
2176   while (DesignatedStartIndex <= DesignatedEndIndex) {
2177     // Recurse to check later designated subobjects.
2178     QualType ElementType = AT->getElementType();
2179     Index = OldIndex;
2180
2181     ElementEntity.setElementIndex(ElementIndex);
2182     if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2183                                    ElementType, 0, 0, Index,
2184                                    StructuredList, ElementIndex,
2185                                    (DesignatedStartIndex == DesignatedEndIndex),
2186                                    false))
2187       return true;
2188
2189     // Move to the next index in the array that we'll be initializing.
2190     ++DesignatedStartIndex;
2191     ElementIndex = DesignatedStartIndex.getZExtValue();
2192   }
2193
2194   // If this the first designator, our caller will continue checking
2195   // the rest of this array subobject.
2196   if (IsFirstDesignator) {
2197     if (NextElementIndex)
2198       *NextElementIndex = DesignatedStartIndex;
2199     StructuredIndex = ElementIndex;
2200     return false;
2201   }
2202
2203   if (!FinishSubobjectInit)
2204     return false;
2205
2206   // Check the remaining elements within this array subobject.
2207   bool prevHadError = hadError;
2208   CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
2209                  /*SubobjectIsDesignatorContext=*/false, Index,
2210                  StructuredList, ElementIndex);
2211   return hadError && !prevHadError;
2212 }
2213
2214 // Get the structured initializer list for a subobject of type
2215 // @p CurrentObjectType.
2216 InitListExpr *
2217 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2218                                             QualType CurrentObjectType,
2219                                             InitListExpr *StructuredList,
2220                                             unsigned StructuredIndex,
2221                                             SourceRange InitRange) {
2222   if (VerifyOnly)
2223     return 0; // No structured list in verification-only mode.
2224   Expr *ExistingInit = 0;
2225   if (!StructuredList)
2226     ExistingInit = SyntacticToSemantic.lookup(IList);
2227   else if (StructuredIndex < StructuredList->getNumInits())
2228     ExistingInit = StructuredList->getInit(StructuredIndex);
2229
2230   if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2231     return Result;
2232
2233   if (ExistingInit) {
2234     // We are creating an initializer list that initializes the
2235     // subobjects of the current object, but there was already an
2236     // initialization that completely initialized the current
2237     // subobject, e.g., by a compound literal:
2238     //
2239     // struct X { int a, b; };
2240     // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2241     //
2242     // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2243     // designated initializer re-initializes the whole
2244     // subobject [0], overwriting previous initializers.
2245     SemaRef.Diag(InitRange.getBegin(),
2246                  diag::warn_subobject_initializer_overrides)
2247       << InitRange;
2248     SemaRef.Diag(ExistingInit->getLocStart(),
2249                   diag::note_previous_initializer)
2250       << /*FIXME:has side effects=*/0
2251       << ExistingInit->getSourceRange();
2252   }
2253
2254   InitListExpr *Result
2255     = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2256                                          InitRange.getBegin(), None,
2257                                          InitRange.getEnd());
2258
2259   QualType ResultType = CurrentObjectType;
2260   if (!ResultType->isArrayType())
2261     ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
2262   Result->setType(ResultType);
2263
2264   // Pre-allocate storage for the structured initializer list.
2265   unsigned NumElements = 0;
2266   unsigned NumInits = 0;
2267   bool GotNumInits = false;
2268   if (!StructuredList) {
2269     NumInits = IList->getNumInits();
2270     GotNumInits = true;
2271   } else if (Index < IList->getNumInits()) {
2272     if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
2273       NumInits = SubList->getNumInits();
2274       GotNumInits = true;
2275     }
2276   }
2277
2278   if (const ArrayType *AType
2279       = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2280     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2281       NumElements = CAType->getSize().getZExtValue();
2282       // Simple heuristic so that we don't allocate a very large
2283       // initializer with many empty entries at the end.
2284       if (GotNumInits && NumElements > NumInits)
2285         NumElements = 0;
2286     }
2287   } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
2288     NumElements = VType->getNumElements();
2289   else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
2290     RecordDecl *RDecl = RType->getDecl();
2291     if (RDecl->isUnion())
2292       NumElements = 1;
2293     else
2294       NumElements = std::distance(RDecl->field_begin(),
2295                                   RDecl->field_end());
2296   }
2297
2298   Result->reserveInits(SemaRef.Context, NumElements);
2299
2300   // Link this new initializer list into the structured initializer
2301   // lists.
2302   if (StructuredList)
2303     StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
2304   else {
2305     Result->setSyntacticForm(IList);
2306     SyntacticToSemantic[IList] = Result;
2307   }
2308
2309   return Result;
2310 }
2311
2312 /// Update the initializer at index @p StructuredIndex within the
2313 /// structured initializer list to the value @p expr.
2314 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2315                                                   unsigned &StructuredIndex,
2316                                                   Expr *expr) {
2317   // No structured initializer list to update
2318   if (!StructuredList)
2319     return;
2320
2321   if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2322                                                   StructuredIndex, expr)) {
2323     // This initializer overwrites a previous initializer. Warn.
2324     SemaRef.Diag(expr->getLocStart(),
2325                   diag::warn_initializer_overrides)
2326       << expr->getSourceRange();
2327     SemaRef.Diag(PrevInit->getLocStart(),
2328                   diag::note_previous_initializer)
2329       << /*FIXME:has side effects=*/0
2330       << PrevInit->getSourceRange();
2331   }
2332
2333   ++StructuredIndex;
2334 }
2335
2336 /// Check that the given Index expression is a valid array designator
2337 /// value. This is essentially just a wrapper around
2338 /// VerifyIntegerConstantExpression that also checks for negative values
2339 /// and produces a reasonable diagnostic if there is a
2340 /// failure. Returns the index expression, possibly with an implicit cast
2341 /// added, on success.  If everything went okay, Value will receive the
2342 /// value of the constant expression.
2343 static ExprResult
2344 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
2345   SourceLocation Loc = Index->getLocStart();
2346
2347   // Make sure this is an integer constant expression.
2348   ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
2349   if (Result.isInvalid())
2350     return Result;
2351
2352   if (Value.isSigned() && Value.isNegative())
2353     return S.Diag(Loc, diag::err_array_designator_negative)
2354       << Value.toString(10) << Index->getSourceRange();
2355
2356   Value.setIsUnsigned(true);
2357   return Result;
2358 }
2359
2360 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
2361                                             SourceLocation Loc,
2362                                             bool GNUSyntax,
2363                                             ExprResult Init) {
2364   typedef DesignatedInitExpr::Designator ASTDesignator;
2365
2366   bool Invalid = false;
2367   SmallVector<ASTDesignator, 32> Designators;
2368   SmallVector<Expr *, 32> InitExpressions;
2369
2370   // Build designators and check array designator expressions.
2371   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2372     const Designator &D = Desig.getDesignator(Idx);
2373     switch (D.getKind()) {
2374     case Designator::FieldDesignator:
2375       Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
2376                                           D.getFieldLoc()));
2377       break;
2378
2379     case Designator::ArrayDesignator: {
2380       Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2381       llvm::APSInt IndexValue;
2382       if (!Index->isTypeDependent() && !Index->isValueDependent())
2383         Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
2384       if (!Index)
2385         Invalid = true;
2386       else {
2387         Designators.push_back(ASTDesignator(InitExpressions.size(),
2388                                             D.getLBracketLoc(),
2389                                             D.getRBracketLoc()));
2390         InitExpressions.push_back(Index);
2391       }
2392       break;
2393     }
2394
2395     case Designator::ArrayRangeDesignator: {
2396       Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2397       Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2398       llvm::APSInt StartValue;
2399       llvm::APSInt EndValue;
2400       bool StartDependent = StartIndex->isTypeDependent() ||
2401                             StartIndex->isValueDependent();
2402       bool EndDependent = EndIndex->isTypeDependent() ||
2403                           EndIndex->isValueDependent();
2404       if (!StartDependent)
2405         StartIndex =
2406             CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
2407       if (!EndDependent)
2408         EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
2409
2410       if (!StartIndex || !EndIndex)
2411         Invalid = true;
2412       else {
2413         // Make sure we're comparing values with the same bit width.
2414         if (StartDependent || EndDependent) {
2415           // Nothing to compute.
2416         } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
2417           EndValue = EndValue.extend(StartValue.getBitWidth());
2418         else if (StartValue.getBitWidth() < EndValue.getBitWidth())
2419           StartValue = StartValue.extend(EndValue.getBitWidth());
2420
2421         if (!StartDependent && !EndDependent && EndValue < StartValue) {
2422           Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
2423             << StartValue.toString(10) << EndValue.toString(10)
2424             << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2425           Invalid = true;
2426         } else {
2427           Designators.push_back(ASTDesignator(InitExpressions.size(),
2428                                               D.getLBracketLoc(),
2429                                               D.getEllipsisLoc(),
2430                                               D.getRBracketLoc()));
2431           InitExpressions.push_back(StartIndex);
2432           InitExpressions.push_back(EndIndex);
2433         }
2434       }
2435       break;
2436     }
2437     }
2438   }
2439
2440   if (Invalid || Init.isInvalid())
2441     return ExprError();
2442
2443   // Clear out the expressions within the designation.
2444   Desig.ClearExprs(*this);
2445
2446   DesignatedInitExpr *DIE
2447     = DesignatedInitExpr::Create(Context,
2448                                  Designators.data(), Designators.size(),
2449                                  InitExpressions, Loc, GNUSyntax,
2450                                  Init.takeAs<Expr>());
2451
2452   if (!getLangOpts().C99)
2453     Diag(DIE->getLocStart(), diag::ext_designated_init)
2454       << DIE->getSourceRange();
2455
2456   return Owned(DIE);
2457 }
2458
2459 //===----------------------------------------------------------------------===//
2460 // Initialization entity
2461 //===----------------------------------------------------------------------===//
2462
2463 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
2464                                      const InitializedEntity &Parent)
2465   : Parent(&Parent), Index(Index)
2466 {
2467   if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2468     Kind = EK_ArrayElement;
2469     Type = AT->getElementType();
2470   } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
2471     Kind = EK_VectorElement;
2472     Type = VT->getElementType();
2473   } else {
2474     const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2475     assert(CT && "Unexpected type");
2476     Kind = EK_ComplexElement;
2477     Type = CT->getElementType();
2478   }
2479 }
2480
2481 InitializedEntity
2482 InitializedEntity::InitializeBase(ASTContext &Context,
2483                                   const CXXBaseSpecifier *Base,
2484                                   bool IsInheritedVirtualBase) {
2485   InitializedEntity Result;
2486   Result.Kind = EK_Base;
2487   Result.Parent = 0;
2488   Result.Base = reinterpret_cast<uintptr_t>(Base);
2489   if (IsInheritedVirtualBase)
2490     Result.Base |= 0x01;
2491
2492   Result.Type = Base->getType();
2493   return Result;
2494 }
2495
2496 DeclarationName InitializedEntity::getName() const {
2497   switch (getKind()) {
2498   case EK_Parameter:
2499   case EK_Parameter_CF_Audited: {
2500     ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2501     return (D ? D->getDeclName() : DeclarationName());
2502   }
2503
2504   case EK_Variable:
2505   case EK_Member:
2506     return VariableOrMember->getDeclName();
2507
2508   case EK_LambdaCapture:
2509     return DeclarationName(Capture.VarID);
2510       
2511   case EK_Result:
2512   case EK_Exception:
2513   case EK_New:
2514   case EK_Temporary:
2515   case EK_Base:
2516   case EK_Delegating:
2517   case EK_ArrayElement:
2518   case EK_VectorElement:
2519   case EK_ComplexElement:
2520   case EK_BlockElement:
2521   case EK_CompoundLiteralInit:
2522   case EK_RelatedResult:
2523     return DeclarationName();
2524   }
2525
2526   llvm_unreachable("Invalid EntityKind!");
2527 }
2528
2529 DeclaratorDecl *InitializedEntity::getDecl() const {
2530   switch (getKind()) {
2531   case EK_Variable:
2532   case EK_Member:
2533     return VariableOrMember;
2534
2535   case EK_Parameter:
2536   case EK_Parameter_CF_Audited:
2537     return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2538
2539   case EK_Result:
2540   case EK_Exception:
2541   case EK_New:
2542   case EK_Temporary:
2543   case EK_Base:
2544   case EK_Delegating:
2545   case EK_ArrayElement:
2546   case EK_VectorElement:
2547   case EK_ComplexElement:
2548   case EK_BlockElement:
2549   case EK_LambdaCapture:
2550   case EK_CompoundLiteralInit:
2551   case EK_RelatedResult:
2552     return 0;
2553   }
2554
2555   llvm_unreachable("Invalid EntityKind!");
2556 }
2557
2558 bool InitializedEntity::allowsNRVO() const {
2559   switch (getKind()) {
2560   case EK_Result:
2561   case EK_Exception:
2562     return LocAndNRVO.NRVO;
2563
2564   case EK_Variable:
2565   case EK_Parameter:
2566   case EK_Parameter_CF_Audited:
2567   case EK_Member:
2568   case EK_New:
2569   case EK_Temporary:
2570   case EK_CompoundLiteralInit:
2571   case EK_Base:
2572   case EK_Delegating:
2573   case EK_ArrayElement:
2574   case EK_VectorElement:
2575   case EK_ComplexElement:
2576   case EK_BlockElement:
2577   case EK_LambdaCapture:
2578   case EK_RelatedResult:
2579     break;
2580   }
2581
2582   return false;
2583 }
2584
2585 unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
2586   assert(getParent() != this);
2587   unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
2588   for (unsigned I = 0; I != Depth; ++I)
2589     OS << "`-";
2590
2591   switch (getKind()) {
2592   case EK_Variable: OS << "Variable"; break;
2593   case EK_Parameter: OS << "Parameter"; break;
2594   case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
2595     break;
2596   case EK_Result: OS << "Result"; break;
2597   case EK_Exception: OS << "Exception"; break;
2598   case EK_Member: OS << "Member"; break;
2599   case EK_New: OS << "New"; break;
2600   case EK_Temporary: OS << "Temporary"; break;
2601   case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
2602   case EK_RelatedResult: OS << "RelatedResult"; break;
2603   case EK_Base: OS << "Base"; break;
2604   case EK_Delegating: OS << "Delegating"; break;
2605   case EK_ArrayElement: OS << "ArrayElement " << Index; break;
2606   case EK_VectorElement: OS << "VectorElement " << Index; break;
2607   case EK_ComplexElement: OS << "ComplexElement " << Index; break;
2608   case EK_BlockElement: OS << "Block"; break;
2609   case EK_LambdaCapture:
2610     OS << "LambdaCapture ";
2611     OS << DeclarationName(Capture.VarID);
2612     break;
2613   }
2614
2615   if (Decl *D = getDecl()) {
2616     OS << " ";
2617     cast<NamedDecl>(D)->printQualifiedName(OS);
2618   }
2619
2620   OS << " '" << getType().getAsString() << "'\n";
2621
2622   return Depth + 1;
2623 }
2624
2625 void InitializedEntity::dump() const {
2626   dumpImpl(llvm::errs());
2627 }
2628
2629 //===----------------------------------------------------------------------===//
2630 // Initialization sequence
2631 //===----------------------------------------------------------------------===//
2632
2633 void InitializationSequence::Step::Destroy() {
2634   switch (Kind) {
2635   case SK_ResolveAddressOfOverloadedFunction:
2636   case SK_CastDerivedToBaseRValue:
2637   case SK_CastDerivedToBaseXValue:
2638   case SK_CastDerivedToBaseLValue:
2639   case SK_BindReference:
2640   case SK_BindReferenceToTemporary:
2641   case SK_ExtraneousCopyToTemporary:
2642   case SK_UserConversion:
2643   case SK_QualificationConversionRValue:
2644   case SK_QualificationConversionXValue:
2645   case SK_QualificationConversionLValue:
2646   case SK_LValueToRValue:
2647   case SK_ListInitialization:
2648   case SK_ListConstructorCall:
2649   case SK_UnwrapInitList:
2650   case SK_RewrapInitList:
2651   case SK_ConstructorInitialization:
2652   case SK_ZeroInitialization:
2653   case SK_CAssignment:
2654   case SK_StringInit:
2655   case SK_ObjCObjectConversion:
2656   case SK_ArrayInit:
2657   case SK_ParenthesizedArrayInit:
2658   case SK_PassByIndirectCopyRestore:
2659   case SK_PassByIndirectRestore:
2660   case SK_ProduceObjCObject:
2661   case SK_StdInitializerList:
2662   case SK_OCLSamplerInit:
2663   case SK_OCLZeroEvent:
2664     break;
2665
2666   case SK_ConversionSequence:
2667   case SK_ConversionSequenceNoNarrowing:
2668     delete ICS;
2669   }
2670 }
2671
2672 bool InitializationSequence::isDirectReferenceBinding() const {
2673   return !Steps.empty() && Steps.back().Kind == SK_BindReference;
2674 }
2675
2676 bool InitializationSequence::isAmbiguous() const {
2677   if (!Failed())
2678     return false;
2679
2680   switch (getFailureKind()) {
2681   case FK_TooManyInitsForReference:
2682   case FK_ArrayNeedsInitList:
2683   case FK_ArrayNeedsInitListOrStringLiteral:
2684   case FK_ArrayNeedsInitListOrWideStringLiteral:
2685   case FK_NarrowStringIntoWideCharArray:
2686   case FK_WideStringIntoCharArray:
2687   case FK_IncompatWideStringIntoWideChar:
2688   case FK_AddressOfOverloadFailed: // FIXME: Could do better
2689   case FK_NonConstLValueReferenceBindingToTemporary:
2690   case FK_NonConstLValueReferenceBindingToUnrelated:
2691   case FK_RValueReferenceBindingToLValue:
2692   case FK_ReferenceInitDropsQualifiers:
2693   case FK_ReferenceInitFailed:
2694   case FK_ConversionFailed:
2695   case FK_ConversionFromPropertyFailed:
2696   case FK_TooManyInitsForScalar:
2697   case FK_ReferenceBindingToInitList:
2698   case FK_InitListBadDestinationType:
2699   case FK_DefaultInitOfConst:
2700   case FK_Incomplete:
2701   case FK_ArrayTypeMismatch:
2702   case FK_NonConstantArrayInit:
2703   case FK_ListInitializationFailed:
2704   case FK_VariableLengthArrayHasInitializer:
2705   case FK_PlaceholderType:
2706   case FK_ExplicitConstructor:
2707     return false;
2708
2709   case FK_ReferenceInitOverloadFailed:
2710   case FK_UserConversionOverloadFailed:
2711   case FK_ConstructorOverloadFailed:
2712   case FK_ListConstructorOverloadFailed:
2713     return FailedOverloadResult == OR_Ambiguous;
2714   }
2715
2716   llvm_unreachable("Invalid EntityKind!");
2717 }
2718
2719 bool InitializationSequence::isConstructorInitialization() const {
2720   return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2721 }
2722
2723 void
2724 InitializationSequence
2725 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2726                                    DeclAccessPair Found,
2727                                    bool HadMultipleCandidates) {
2728   Step S;
2729   S.Kind = SK_ResolveAddressOfOverloadedFunction;
2730   S.Type = Function->getType();
2731   S.Function.HadMultipleCandidates = HadMultipleCandidates;
2732   S.Function.Function = Function;
2733   S.Function.FoundDecl = Found;
2734   Steps.push_back(S);
2735 }
2736
2737 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2738                                                       ExprValueKind VK) {
2739   Step S;
2740   switch (VK) {
2741   case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2742   case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2743   case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
2744   }
2745   S.Type = BaseType;
2746   Steps.push_back(S);
2747 }
2748
2749 void InitializationSequence::AddReferenceBindingStep(QualType T,
2750                                                      bool BindingTemporary) {
2751   Step S;
2752   S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2753   S.Type = T;
2754   Steps.push_back(S);
2755 }
2756
2757 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2758   Step S;
2759   S.Kind = SK_ExtraneousCopyToTemporary;
2760   S.Type = T;
2761   Steps.push_back(S);
2762 }
2763
2764 void
2765 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2766                                               DeclAccessPair FoundDecl,
2767                                               QualType T,
2768                                               bool HadMultipleCandidates) {
2769   Step S;
2770   S.Kind = SK_UserConversion;
2771   S.Type = T;
2772   S.Function.HadMultipleCandidates = HadMultipleCandidates;
2773   S.Function.Function = Function;
2774   S.Function.FoundDecl = FoundDecl;
2775   Steps.push_back(S);
2776 }
2777
2778 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2779                                                             ExprValueKind VK) {
2780   Step S;
2781   S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
2782   switch (VK) {
2783   case VK_RValue:
2784     S.Kind = SK_QualificationConversionRValue;
2785     break;
2786   case VK_XValue:
2787     S.Kind = SK_QualificationConversionXValue;
2788     break;
2789   case VK_LValue:
2790     S.Kind = SK_QualificationConversionLValue;
2791     break;
2792   }
2793   S.Type = Ty;
2794   Steps.push_back(S);
2795 }
2796
2797 void InitializationSequence::AddLValueToRValueStep(QualType Ty) {
2798   assert(!Ty.hasQualifiers() && "rvalues may not have qualifiers");
2799
2800   Step S;
2801   S.Kind = SK_LValueToRValue;
2802   S.Type = Ty;
2803   Steps.push_back(S);
2804 }
2805
2806 void InitializationSequence::AddConversionSequenceStep(
2807     const ImplicitConversionSequence &ICS, QualType T,
2808     bool TopLevelOfInitList) {
2809   Step S;
2810   S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing
2811                               : SK_ConversionSequence;
2812   S.Type = T;
2813   S.ICS = new ImplicitConversionSequence(ICS);
2814   Steps.push_back(S);
2815 }
2816
2817 void InitializationSequence::AddListInitializationStep(QualType T) {
2818   Step S;
2819   S.Kind = SK_ListInitialization;
2820   S.Type = T;
2821   Steps.push_back(S);
2822 }
2823
2824 void
2825 InitializationSequence
2826 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2827                                    AccessSpecifier Access,
2828                                    QualType T,
2829                                    bool HadMultipleCandidates,
2830                                    bool FromInitList, bool AsInitList) {
2831   Step S;
2832   S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
2833                                        : SK_ConstructorInitialization;
2834   S.Type = T;
2835   S.Function.HadMultipleCandidates = HadMultipleCandidates;
2836   S.Function.Function = Constructor;
2837   S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
2838   Steps.push_back(S);
2839 }
2840
2841 void InitializationSequence::AddZeroInitializationStep(QualType T) {
2842   Step S;
2843   S.Kind = SK_ZeroInitialization;
2844   S.Type = T;
2845   Steps.push_back(S);
2846 }
2847
2848 void InitializationSequence::AddCAssignmentStep(QualType T) {
2849   Step S;
2850   S.Kind = SK_CAssignment;
2851   S.Type = T;
2852   Steps.push_back(S);
2853 }
2854
2855 void InitializationSequence::AddStringInitStep(QualType T) {
2856   Step S;
2857   S.Kind = SK_StringInit;
2858   S.Type = T;
2859   Steps.push_back(S);
2860 }
2861
2862 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2863   Step S;
2864   S.Kind = SK_ObjCObjectConversion;
2865   S.Type = T;
2866   Steps.push_back(S);
2867 }
2868
2869 void InitializationSequence::AddArrayInitStep(QualType T) {
2870   Step S;
2871   S.Kind = SK_ArrayInit;
2872   S.Type = T;
2873   Steps.push_back(S);
2874 }
2875
2876 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
2877   Step S;
2878   S.Kind = SK_ParenthesizedArrayInit;
2879   S.Type = T;
2880   Steps.push_back(S);
2881 }
2882
2883 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2884                                                               bool shouldCopy) {
2885   Step s;
2886   s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2887                        : SK_PassByIndirectRestore);
2888   s.Type = type;
2889   Steps.push_back(s);
2890 }
2891
2892 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2893   Step S;
2894   S.Kind = SK_ProduceObjCObject;
2895   S.Type = T;
2896   Steps.push_back(S);
2897 }
2898
2899 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2900   Step S;
2901   S.Kind = SK_StdInitializerList;
2902   S.Type = T;
2903   Steps.push_back(S);
2904 }
2905
2906 void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
2907   Step S;
2908   S.Kind = SK_OCLSamplerInit;
2909   S.Type = T;
2910   Steps.push_back(S);
2911 }
2912
2913 void InitializationSequence::AddOCLZeroEventStep(QualType T) {
2914   Step S;
2915   S.Kind = SK_OCLZeroEvent;
2916   S.Type = T;
2917   Steps.push_back(S);
2918 }
2919
2920 void InitializationSequence::RewrapReferenceInitList(QualType T,
2921                                                      InitListExpr *Syntactic) {
2922   assert(Syntactic->getNumInits() == 1 &&
2923          "Can only rewrap trivial init lists.");
2924   Step S;
2925   S.Kind = SK_UnwrapInitList;
2926   S.Type = Syntactic->getInit(0)->getType();
2927   Steps.insert(Steps.begin(), S);
2928
2929   S.Kind = SK_RewrapInitList;
2930   S.Type = T;
2931   S.WrappingSyntacticList = Syntactic;
2932   Steps.push_back(S);
2933 }
2934
2935 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2936                                                 OverloadingResult Result) {
2937   setSequenceKind(FailedSequence);
2938   this->Failure = Failure;
2939   this->FailedOverloadResult = Result;
2940 }
2941
2942 //===----------------------------------------------------------------------===//
2943 // Attempt initialization
2944 //===----------------------------------------------------------------------===//
2945
2946 static void MaybeProduceObjCObject(Sema &S,
2947                                    InitializationSequence &Sequence,
2948                                    const InitializedEntity &Entity) {
2949   if (!S.getLangOpts().ObjCAutoRefCount) return;
2950
2951   /// When initializing a parameter, produce the value if it's marked
2952   /// __attribute__((ns_consumed)).
2953   if (Entity.isParameterKind()) {
2954     if (!Entity.isParameterConsumed())
2955       return;
2956
2957     assert(Entity.getType()->isObjCRetainableType() &&
2958            "consuming an object of unretainable type?");
2959     Sequence.AddProduceObjCObjectStep(Entity.getType());
2960
2961   /// When initializing a return value, if the return type is a
2962   /// retainable type, then returns need to immediately retain the
2963   /// object.  If an autorelease is required, it will be done at the
2964   /// last instant.
2965   } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2966     if (!Entity.getType()->isObjCRetainableType())
2967       return;
2968
2969     Sequence.AddProduceObjCObjectStep(Entity.getType());
2970   }
2971 }
2972
2973 static void TryListInitialization(Sema &S,
2974                                   const InitializedEntity &Entity,
2975                                   const InitializationKind &Kind,
2976                                   InitListExpr *InitList,
2977                                   InitializationSequence &Sequence);
2978
2979 /// \brief When initializing from init list via constructor, handle
2980 /// initialization of an object of type std::initializer_list<T>.
2981 ///
2982 /// \return true if we have handled initialization of an object of type
2983 /// std::initializer_list<T>, false otherwise.
2984 static bool TryInitializerListConstruction(Sema &S,
2985                                            InitListExpr *List,
2986                                            QualType DestType,
2987                                            InitializationSequence &Sequence) {
2988   QualType E;
2989   if (!S.isStdInitializerList(DestType, &E))
2990     return false;
2991
2992   if (S.RequireCompleteType(List->getExprLoc(), E, 0)) {
2993     Sequence.setIncompleteTypeFailure(E);
2994     return true;
2995   }
2996
2997   // Try initializing a temporary array from the init list.
2998   QualType ArrayType = S.Context.getConstantArrayType(
2999       E.withConst(), llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3000                                  List->getNumInits()),
3001       clang::ArrayType::Normal, 0);
3002   InitializedEntity HiddenArray =
3003       InitializedEntity::InitializeTemporary(ArrayType);
3004   InitializationKind Kind =
3005       InitializationKind::CreateDirectList(List->getExprLoc());
3006   TryListInitialization(S, HiddenArray, Kind, List, Sequence);
3007   if (Sequence)
3008     Sequence.AddStdInitializerListConstructionStep(DestType);
3009   return true;
3010 }
3011
3012 static OverloadingResult
3013 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3014                            MultiExprArg Args,
3015                            OverloadCandidateSet &CandidateSet,
3016                            ArrayRef<NamedDecl *> Ctors,
3017                            OverloadCandidateSet::iterator &Best,
3018                            bool CopyInitializing, bool AllowExplicit,
3019                            bool OnlyListConstructors, bool InitListSyntax) {
3020   CandidateSet.clear();
3021
3022   for (ArrayRef<NamedDecl *>::iterator
3023          Con = Ctors.begin(), ConEnd = Ctors.end(); Con != ConEnd; ++Con) {
3024     NamedDecl *D = *Con;
3025     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3026     bool SuppressUserConversions = false;
3027
3028     // Find the constructor (which may be a template).
3029     CXXConstructorDecl *Constructor = 0;
3030     FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3031     if (ConstructorTmpl)
3032       Constructor = cast<CXXConstructorDecl>(
3033                                            ConstructorTmpl->getTemplatedDecl());
3034     else {
3035       Constructor = cast<CXXConstructorDecl>(D);
3036
3037       // C++11 [over.best.ics]p4:
3038       //   However, when considering the argument of a constructor or
3039       //   user-defined conversion function that is a candidate:
3040       //    -- by 13.3.1.3 when invoked for the copying/moving of a temporary
3041       //       in the second step of a class copy-initialization,
3042       //    -- by 13.3.1.7 when passing the initializer list as a single
3043       //       argument or when the initializer list has exactly one elementand
3044       //       a conversion to some class X or reference to (possibly
3045       //       cv-qualified) X is considered for the first parameter of a
3046       //       constructor of X, or
3047       //    -- by 13.3.1.4, 13.3.1.5, or 13.3.1.6 in all cases,
3048       //   only standard conversion sequences and ellipsis conversion sequences
3049       //   are considered.
3050       if ((CopyInitializing || (InitListSyntax && Args.size() == 1)) &&
3051           Constructor->isCopyOrMoveConstructor())
3052         SuppressUserConversions = true;
3053     }
3054
3055     if (!Constructor->isInvalidDecl() &&
3056         (AllowExplicit || !Constructor->isExplicit()) &&
3057         (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
3058       if (ConstructorTmpl)
3059         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3060                                        /*ExplicitArgs*/ 0, Args,
3061                                        CandidateSet, SuppressUserConversions);
3062       else {
3063         // C++ [over.match.copy]p1:
3064         //   - When initializing a temporary to be bound to the first parameter 
3065         //     of a constructor that takes a reference to possibly cv-qualified 
3066         //     T as its first argument, called with a single argument in the 
3067         //     context of direct-initialization, explicit conversion functions
3068         //     are also considered.
3069         bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 
3070                                  Args.size() == 1 &&
3071                                  Constructor->isCopyOrMoveConstructor();
3072         S.AddOverloadCandidate(Constructor, FoundDecl, Args, CandidateSet,
3073                                SuppressUserConversions,
3074                                /*PartialOverloading=*/false,
3075                                /*AllowExplicit=*/AllowExplicitConv);
3076       }
3077     }
3078   }
3079
3080   // Perform overload resolution and return the result.
3081   return CandidateSet.BestViableFunction(S, DeclLoc, Best);
3082 }
3083
3084 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3085 /// enumerates the constructors of the initialized entity and performs overload
3086 /// resolution to select the best.
3087 /// If InitListSyntax is true, this is list-initialization of a non-aggregate
3088 /// class type.
3089 static void TryConstructorInitialization(Sema &S,
3090                                          const InitializedEntity &Entity,
3091                                          const InitializationKind &Kind,
3092                                          MultiExprArg Args, QualType DestType,
3093                                          InitializationSequence &Sequence,
3094                                          bool InitListSyntax = false) {
3095   assert((!InitListSyntax || (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
3096          "InitListSyntax must come with a single initializer list argument.");
3097
3098   // The type we're constructing needs to be complete.
3099   if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
3100     Sequence.setIncompleteTypeFailure(DestType);
3101     return;
3102   }
3103
3104   const RecordType *DestRecordType = DestType->getAs<RecordType>();
3105   assert(DestRecordType && "Constructor initialization requires record type");
3106   CXXRecordDecl *DestRecordDecl
3107     = cast<CXXRecordDecl>(DestRecordType->getDecl());
3108
3109   // Build the candidate set directly in the initialization sequence
3110   // structure, so that it will persist if we fail.
3111   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3112
3113   // Determine whether we are allowed to call explicit constructors or
3114   // explicit conversion operators.
3115   bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
3116   bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
3117
3118   //   - Otherwise, if T is a class type, constructors are considered. The
3119   //     applicable constructors are enumerated, and the best one is chosen
3120   //     through overload resolution.
3121   DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
3122   // The container holding the constructors can under certain conditions
3123   // be changed while iterating (e.g. because of deserialization).
3124   // To be safe we copy the lookup results to a new container.
3125   SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3126
3127   OverloadingResult Result = OR_No_Viable_Function;
3128   OverloadCandidateSet::iterator Best;
3129   bool AsInitializerList = false;
3130
3131   // C++11 [over.match.list]p1:
3132   //   When objects of non-aggregate type T are list-initialized, overload
3133   //   resolution selects the constructor in two phases:
3134   //   - Initially, the candidate functions are the initializer-list
3135   //     constructors of the class T and the argument list consists of the
3136   //     initializer list as a single argument.
3137   if (InitListSyntax) {
3138     InitListExpr *ILE = cast<InitListExpr>(Args[0]);
3139     AsInitializerList = true;
3140
3141     // If the initializer list has no elements and T has a default constructor,
3142     // the first phase is omitted.
3143     if (ILE->getNumInits() != 0 || !DestRecordDecl->hasDefaultConstructor())
3144       Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3145                                           CandidateSet, Ctors, Best,
3146                                           CopyInitialization, AllowExplicit,
3147                                           /*OnlyListConstructor=*/true,
3148                                           InitListSyntax);
3149
3150     // Time to unwrap the init list.
3151     Args = MultiExprArg(ILE->getInits(), ILE->getNumInits());
3152   }
3153
3154   // C++11 [over.match.list]p1:
3155   //   - If no viable initializer-list constructor is found, overload resolution
3156   //     is performed again, where the candidate functions are all the
3157   //     constructors of the class T and the argument list consists of the
3158   //     elements of the initializer list.
3159   if (Result == OR_No_Viable_Function) {
3160     AsInitializerList = false;
3161     Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
3162                                         CandidateSet, Ctors, Best,
3163                                         CopyInitialization, AllowExplicit,
3164                                         /*OnlyListConstructors=*/false,
3165                                         InitListSyntax);
3166   }
3167   if (Result) {
3168     Sequence.SetOverloadFailure(InitListSyntax ?
3169                       InitializationSequence::FK_ListConstructorOverloadFailed :
3170                       InitializationSequence::FK_ConstructorOverloadFailed,
3171                                 Result);
3172     return;
3173   }
3174
3175   // C++11 [dcl.init]p6:
3176   //   If a program calls for the default initialization of an object
3177   //   of a const-qualified type T, T shall be a class type with a
3178   //   user-provided default constructor.
3179   if (Kind.getKind() == InitializationKind::IK_Default &&
3180       Entity.getType().isConstQualified() &&
3181       !cast<CXXConstructorDecl>(Best->Function)->isUserProvided()) {
3182     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3183     return;
3184   }
3185
3186   // C++11 [over.match.list]p1:
3187   //   In copy-list-initialization, if an explicit constructor is chosen, the
3188   //   initializer is ill-formed.
3189   CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3190   if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
3191     Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
3192     return;
3193   }
3194
3195   // Add the constructor initialization step. Any cv-qualification conversion is
3196   // subsumed by the initialization.
3197   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3198   Sequence.AddConstructorInitializationStep(CtorDecl,
3199                                             Best->FoundDecl.getAccess(),
3200                                             DestType, HadMultipleCandidates,
3201                                             InitListSyntax, AsInitializerList);
3202 }
3203
3204 static bool
3205 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3206                                              Expr *Initializer,
3207                                              QualType &SourceType,
3208                                              QualType &UnqualifiedSourceType,
3209                                              QualType UnqualifiedTargetType,
3210                                              InitializationSequence &Sequence) {
3211   if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3212         S.Context.OverloadTy) {
3213     DeclAccessPair Found;
3214     bool HadMultipleCandidates = false;
3215     if (FunctionDecl *Fn
3216         = S.ResolveAddressOfOverloadedFunction(Initializer,
3217                                                UnqualifiedTargetType,
3218                                                false, Found,
3219                                                &HadMultipleCandidates)) {
3220       Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3221                                                 HadMultipleCandidates);
3222       SourceType = Fn->getType();
3223       UnqualifiedSourceType = SourceType.getUnqualifiedType();
3224     } else if (!UnqualifiedTargetType->isRecordType()) {
3225       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3226       return true;
3227     }
3228   }
3229   return false;
3230 }
3231
3232 static void TryReferenceInitializationCore(Sema &S,
3233                                            const InitializedEntity &Entity,
3234                                            const InitializationKind &Kind,
3235                                            Expr *Initializer,
3236                                            QualType cv1T1, QualType T1,
3237                                            Qualifiers T1Quals,
3238                                            QualType cv2T2, QualType T2,
3239                                            Qualifiers T2Quals,
3240                                            InitializationSequence &Sequence);
3241
3242 static void TryValueInitialization(Sema &S,
3243                                    const InitializedEntity &Entity,
3244                                    const InitializationKind &Kind,
3245                                    InitializationSequence &Sequence,
3246                                    InitListExpr *InitList = 0);
3247
3248 /// \brief Attempt list initialization of a reference.
3249 static void TryReferenceListInitialization(Sema &S,
3250                                            const InitializedEntity &Entity,
3251                                            const InitializationKind &Kind,
3252                                            InitListExpr *InitList,
3253                                            InitializationSequence &Sequence) {
3254   // First, catch C++03 where this isn't possible.
3255   if (!S.getLangOpts().CPlusPlus11) {
3256     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3257     return;
3258   }
3259
3260   QualType DestType = Entity.getType();
3261   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3262   Qualifiers T1Quals;
3263   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3264
3265   // Reference initialization via an initializer list works thus:
3266   // If the initializer list consists of a single element that is
3267   // reference-related to the referenced type, bind directly to that element
3268   // (possibly creating temporaries).
3269   // Otherwise, initialize a temporary with the initializer list and
3270   // bind to that.
3271   if (InitList->getNumInits() == 1) {
3272     Expr *Initializer = InitList->getInit(0);
3273     QualType cv2T2 = Initializer->getType();
3274     Qualifiers T2Quals;
3275     QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3276
3277     // If this fails, creating a temporary wouldn't work either.
3278     if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3279                                                      T1, Sequence))
3280       return;
3281
3282     SourceLocation DeclLoc = Initializer->getLocStart();
3283     bool dummy1, dummy2, dummy3;
3284     Sema::ReferenceCompareResult RefRelationship
3285       = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3286                                        dummy2, dummy3);
3287     if (RefRelationship >= Sema::Ref_Related) {
3288       // Try to bind the reference here.
3289       TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3290                                      T1Quals, cv2T2, T2, T2Quals, Sequence);
3291       if (Sequence)
3292         Sequence.RewrapReferenceInitList(cv1T1, InitList);
3293       return;
3294     }
3295
3296     // Update the initializer if we've resolved an overloaded function.
3297     if (Sequence.step_begin() != Sequence.step_end())
3298       Sequence.RewrapReferenceInitList(cv1T1, InitList);
3299   }
3300
3301   // Not reference-related. Create a temporary and bind to that.
3302   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3303
3304   TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3305   if (Sequence) {
3306     if (DestType->isRValueReferenceType() ||
3307         (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3308       Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3309     else
3310       Sequence.SetFailed(
3311           InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3312   }
3313 }
3314
3315 /// \brief Attempt list initialization (C++0x [dcl.init.list])
3316 static void TryListInitialization(Sema &S,
3317                                   const InitializedEntity &Entity,
3318                                   const InitializationKind &Kind,
3319                                   InitListExpr *InitList,
3320                                   InitializationSequence &Sequence) {
3321   QualType DestType = Entity.getType();
3322
3323   // C++ doesn't allow scalar initialization with more than one argument.
3324   // But C99 complex numbers are scalars and it makes sense there.
3325   if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
3326       !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3327     Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3328     return;
3329   }
3330   if (DestType->isReferenceType()) {
3331     TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
3332     return;
3333   }
3334   if (DestType->isRecordType()) {
3335     if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
3336       Sequence.setIncompleteTypeFailure(DestType);
3337       return;
3338     }
3339
3340     // C++11 [dcl.init.list]p3:
3341     //   - If T is an aggregate, aggregate initialization is performed.
3342     if (!DestType->isAggregateType()) {
3343       if (S.getLangOpts().CPlusPlus11) {
3344         //   - Otherwise, if the initializer list has no elements and T is a
3345         //     class type with a default constructor, the object is
3346         //     value-initialized.
3347         if (InitList->getNumInits() == 0) {
3348           CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
3349           if (RD->hasDefaultConstructor()) {
3350             TryValueInitialization(S, Entity, Kind, Sequence, InitList);
3351             return;
3352           }
3353         }
3354
3355         //   - Otherwise, if T is a specialization of std::initializer_list<E>,
3356         //     an initializer_list object constructed [...]
3357         if (TryInitializerListConstruction(S, InitList, DestType, Sequence))
3358           return;
3359
3360         //   - Otherwise, if T is a class type, constructors are considered.
3361         Expr *InitListAsExpr = InitList;
3362         TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
3363                                      Sequence, /*InitListSyntax*/true);
3364       } else
3365         Sequence.SetFailed(
3366             InitializationSequence::FK_InitListBadDestinationType);
3367       return;
3368     }
3369   }
3370   if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() &&
3371       InitList->getNumInits() == 1 &&
3372       InitList->getInit(0)->getType()->isRecordType()) {
3373     //   - Otherwise, if the initializer list has a single element of type E
3374     //     [...references are handled above...], the object or reference is
3375     //     initialized from that element; if a narrowing conversion is required
3376     //     to convert the element to T, the program is ill-formed.
3377     //
3378     // Per core-24034, this is direct-initialization if we were performing
3379     // direct-list-initialization and copy-initialization otherwise.
3380     // We can't use InitListChecker for this, because it always performs
3381     // copy-initialization. This only matters if we might use an 'explicit'
3382     // conversion operator, so we only need to handle the cases where the source
3383     // is of record type.
3384     InitializationKind SubKind =
3385         Kind.getKind() == InitializationKind::IK_DirectList
3386             ? InitializationKind::CreateDirect(Kind.getLocation(),
3387                                                InitList->getLBraceLoc(),
3388                                                InitList->getRBraceLoc())
3389             : Kind;
3390     Expr *SubInit[1] = { InitList->getInit(0) };
3391     Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
3392                             /*TopLevelOfInitList*/true);
3393     if (Sequence)
3394       Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
3395     return;
3396   }
3397
3398   InitListChecker CheckInitList(S, Entity, InitList,
3399           DestType, /*VerifyOnly=*/true);
3400   if (CheckInitList.HadError()) {
3401     Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3402     return;
3403   }
3404
3405   // Add the list initialization step with the built init list.
3406   Sequence.AddListInitializationStep(DestType);
3407 }
3408
3409 /// \brief Try a reference initialization that involves calling a conversion
3410 /// function.
3411 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3412                                              const InitializedEntity &Entity,
3413                                              const InitializationKind &Kind,
3414                                              Expr *Initializer,
3415                                              bool AllowRValues,
3416                                              InitializationSequence &Sequence) {
3417   QualType DestType = Entity.getType();
3418   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3419   QualType T1 = cv1T1.getUnqualifiedType();
3420   QualType cv2T2 = Initializer->getType();
3421   QualType T2 = cv2T2.getUnqualifiedType();
3422
3423   bool DerivedToBase;
3424   bool ObjCConversion;
3425   bool ObjCLifetimeConversion;
3426   assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
3427                                          T1, T2, DerivedToBase,
3428                                          ObjCConversion,
3429                                          ObjCLifetimeConversion) &&
3430          "Must have incompatible references when binding via conversion");
3431   (void)DerivedToBase;
3432   (void)ObjCConversion;
3433   (void)ObjCLifetimeConversion;
3434   
3435   // Build the candidate set directly in the initialization sequence
3436   // structure, so that it will persist if we fail.
3437   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3438   CandidateSet.clear();
3439
3440   // Determine whether we are allowed to call explicit constructors or
3441   // explicit conversion operators.
3442   bool AllowExplicit = Kind.AllowExplicit();
3443   bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
3444
3445   const RecordType *T1RecordType = 0;
3446   if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3447       !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
3448     // The type we're converting to is a class type. Enumerate its constructors
3449     // to see if there is a suitable conversion.
3450     CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
3451
3452     DeclContext::lookup_result R = S.LookupConstructors(T1RecordDecl);
3453     // The container holding the constructors can under certain conditions
3454     // be changed while iterating (e.g. because of deserialization).
3455     // To be safe we copy the lookup results to a new container.
3456     SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
3457     for (SmallVectorImpl<NamedDecl *>::iterator
3458            CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
3459       NamedDecl *D = *CI;
3460       DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3461
3462       // Find the constructor (which may be a template).
3463       CXXConstructorDecl *Constructor = 0;
3464       FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
3465       if (ConstructorTmpl)
3466         Constructor = cast<CXXConstructorDecl>(
3467                                          ConstructorTmpl->getTemplatedDecl());
3468       else
3469         Constructor = cast<CXXConstructorDecl>(D);
3470
3471       if (!Constructor->isInvalidDecl() &&
3472           Constructor->isConvertingConstructor(AllowExplicit)) {
3473         if (ConstructorTmpl)
3474           S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3475                                          /*ExplicitArgs*/ 0,
3476                                          Initializer, CandidateSet,
3477                                          /*SuppressUserConversions=*/true);
3478         else
3479           S.AddOverloadCandidate(Constructor, FoundDecl,
3480                                  Initializer, CandidateSet,
3481                                  /*SuppressUserConversions=*/true);
3482       }
3483     }
3484   }
3485   if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3486     return OR_No_Viable_Function;
3487
3488   const RecordType *T2RecordType = 0;
3489   if ((T2RecordType = T2->getAs<RecordType>()) &&
3490       !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
3491     // The type we're converting from is a class type, enumerate its conversion
3492     // functions.
3493     CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3494
3495     std::pair<CXXRecordDecl::conversion_iterator,
3496               CXXRecordDecl::conversion_iterator>
3497       Conversions = T2RecordDecl->getVisibleConversionFunctions();
3498     for (CXXRecordDecl::conversion_iterator
3499            I = Conversions.first, E = Conversions.second; I != E; ++I) {
3500       NamedDecl *D = *I;
3501       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3502       if (isa<UsingShadowDecl>(D))
3503         D = cast<UsingShadowDecl>(D)->getTargetDecl();
3504
3505       FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3506       CXXConversionDecl *Conv;
3507       if (ConvTemplate)
3508         Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3509       else
3510         Conv = cast<CXXConversionDecl>(D);
3511
3512       // If the conversion function doesn't return a reference type,
3513       // it can't be considered for this conversion unless we're allowed to
3514       // consider rvalues.
3515       // FIXME: Do we need to make sure that we only consider conversion
3516       // candidates with reference-compatible results? That might be needed to
3517       // break recursion.
3518       if ((AllowExplicitConvs || !Conv->isExplicit()) &&
3519           (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3520         if (ConvTemplate)
3521           S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
3522                                            ActingDC, Initializer,
3523                                            DestType, CandidateSet);
3524         else
3525           S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3526                                    Initializer, DestType, CandidateSet);
3527       }
3528     }
3529   }
3530   if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3531     return OR_No_Viable_Function;
3532
3533   SourceLocation DeclLoc = Initializer->getLocStart();
3534
3535   // Perform overload resolution. If it fails, return the failed result.
3536   OverloadCandidateSet::iterator Best;
3537   if (OverloadingResult Result
3538         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3539     return Result;
3540
3541   FunctionDecl *Function = Best->Function;
3542   // This is the overload that will be used for this initialization step if we
3543   // use this initialization. Mark it as referenced.
3544   Function->setReferenced();
3545
3546   // Compute the returned type of the conversion.
3547   if (isa<CXXConversionDecl>(Function))
3548     T2 = Function->getResultType();
3549   else
3550     T2 = cv1T1;
3551
3552   // Add the user-defined conversion step.
3553   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3554   Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3555                                  T2.getNonLValueExprType(S.Context),
3556                                  HadMultipleCandidates);
3557
3558   // Determine whether we need to perform derived-to-base or
3559   // cv-qualification adjustments.
3560   ExprValueKind VK = VK_RValue;
3561   if (T2->isLValueReferenceType())
3562     VK = VK_LValue;
3563   else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3564     VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3565
3566   bool NewDerivedToBase = false;
3567   bool NewObjCConversion = false;
3568   bool NewObjCLifetimeConversion = false;
3569   Sema::ReferenceCompareResult NewRefRelationship
3570     = S.CompareReferenceRelationship(DeclLoc, T1,
3571                                      T2.getNonLValueExprType(S.Context),
3572                                      NewDerivedToBase, NewObjCConversion,
3573                                      NewObjCLifetimeConversion);
3574   if (NewRefRelationship == Sema::Ref_Incompatible) {
3575     // If the type we've converted to is not reference-related to the
3576     // type we're looking for, then there is another conversion step
3577     // we need to perform to produce a temporary of the right type
3578     // that we'll be binding to.
3579     ImplicitConversionSequence ICS;
3580     ICS.setStandard();
3581     ICS.Standard = Best->FinalConversion;
3582     T2 = ICS.Standard.getToType(2);
3583     Sequence.AddConversionSequenceStep(ICS, T2);
3584   } else if (NewDerivedToBase)
3585     Sequence.AddDerivedToBaseCastStep(
3586                                 S.Context.getQualifiedType(T1,
3587                                   T2.getNonReferenceType().getQualifiers()),
3588                                       VK);
3589   else if (NewObjCConversion)
3590     Sequence.AddObjCObjectConversionStep(
3591                                 S.Context.getQualifiedType(T1,
3592                                   T2.getNonReferenceType().getQualifiers()));
3593
3594   if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3595     Sequence.AddQualificationConversionStep(cv1T1, VK);
3596
3597   Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3598   return OR_Success;
3599 }
3600
3601 static void CheckCXX98CompatAccessibleCopy(Sema &S,
3602                                            const InitializedEntity &Entity,
3603                                            Expr *CurInitExpr);
3604
3605 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3606 static void TryReferenceInitialization(Sema &S,
3607                                        const InitializedEntity &Entity,
3608                                        const InitializationKind &Kind,
3609                                        Expr *Initializer,
3610                                        InitializationSequence &Sequence) {
3611   QualType DestType = Entity.getType();
3612   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3613   Qualifiers T1Quals;
3614   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3615   QualType cv2T2 = Initializer->getType();
3616   Qualifiers T2Quals;
3617   QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3618
3619   // If the initializer is the address of an overloaded function, try
3620   // to resolve the overloaded function. If all goes well, T2 is the
3621   // type of the resulting function.
3622   if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3623                                                    T1, Sequence))
3624     return;
3625
3626   // Delegate everything else to a subfunction.
3627   TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3628                                  T1Quals, cv2T2, T2, T2Quals, Sequence);
3629 }
3630
3631 /// Converts the target of reference initialization so that it has the
3632 /// appropriate qualifiers and value kind.
3633 ///
3634 /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3635 /// \code
3636 ///   int x;
3637 ///   const int &r = x;
3638 /// \endcode
3639 ///
3640 /// In this case the reference is binding to a bitfield lvalue, which isn't
3641 /// valid. Perform a load to create a lifetime-extended temporary instead.
3642 /// \code
3643 ///   const int &r = someStruct.bitfield;
3644 /// \endcode
3645 static ExprValueKind
3646 convertQualifiersAndValueKindIfNecessary(Sema &S,
3647                                          InitializationSequence &Sequence,
3648                                          Expr *Initializer,
3649                                          QualType cv1T1,
3650                                          Qualifiers T1Quals,
3651                                          Qualifiers T2Quals,
3652                                          bool IsLValueRef) {
3653   bool IsNonAddressableType = Initializer->refersToBitField() ||
3654                               Initializer->refersToVectorElement();
3655
3656   if (IsNonAddressableType) {
3657     // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3658     // lvalue reference to a non-volatile const type, or the reference shall be
3659     // an rvalue reference.
3660     //
3661     // If not, we can't make a temporary and bind to that. Give up and allow the
3662     // error to be diagnosed later.
3663     if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3664       assert(Initializer->isGLValue());
3665       return Initializer->getValueKind();
3666     }
3667
3668     // Force a load so we can materialize a temporary.
3669     Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3670     return VK_RValue;
3671   }
3672
3673   if (T1Quals != T2Quals) {
3674     Sequence.AddQualificationConversionStep(cv1T1,
3675                                             Initializer->getValueKind());
3676   }
3677
3678   return Initializer->getValueKind();
3679 }
3680
3681
3682 /// \brief Reference initialization without resolving overloaded functions.
3683 static void TryReferenceInitializationCore(Sema &S,
3684                                            const InitializedEntity &Entity,
3685                                            const InitializationKind &Kind,
3686                                            Expr *Initializer,
3687                                            QualType cv1T1, QualType T1,
3688                                            Qualifiers T1Quals,
3689                                            QualType cv2T2, QualType T2,
3690                                            Qualifiers T2Quals,
3691                                            InitializationSequence &Sequence) {
3692   QualType DestType = Entity.getType();
3693   SourceLocation DeclLoc = Initializer->getLocStart();
3694   // Compute some basic properties of the types and the initializer.
3695   bool isLValueRef = DestType->isLValueReferenceType();
3696   bool isRValueRef = !isLValueRef;
3697   bool DerivedToBase = false;
3698   bool ObjCConversion = false;
3699   bool ObjCLifetimeConversion = false;
3700   Expr::Classification InitCategory = Initializer->Classify(S.Context);
3701   Sema::ReferenceCompareResult RefRelationship
3702     = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3703                                      ObjCConversion, ObjCLifetimeConversion);
3704
3705   // C++0x [dcl.init.ref]p5:
3706   //   A reference to type "cv1 T1" is initialized by an expression of type
3707   //   "cv2 T2" as follows:
3708   //
3709   //     - If the reference is an lvalue reference and the initializer
3710   //       expression
3711   // Note the analogous bullet points for rvalue refs to functions. Because
3712   // there are no function rvalues in C++, rvalue refs to functions are treated
3713   // like lvalue refs.
3714   OverloadingResult ConvOvlResult = OR_Success;
3715   bool T1Function = T1->isFunctionType();
3716   if (isLValueRef || T1Function) {
3717     if (InitCategory.isLValue() &&
3718         (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3719          (Kind.isCStyleOrFunctionalCast() &&
3720           RefRelationship == Sema::Ref_Related))) {
3721       //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3722       //     reference-compatible with "cv2 T2," or
3723       //
3724       // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3725       // bit-field when we're determining whether the reference initialization
3726       // can occur. However, we do pay attention to whether it is a bit-field
3727       // to decide whether we're actually binding to a temporary created from
3728       // the bit-field.
3729       if (DerivedToBase)
3730         Sequence.AddDerivedToBaseCastStep(
3731                          S.Context.getQualifiedType(T1, T2Quals),
3732                          VK_LValue);
3733       else if (ObjCConversion)
3734         Sequence.AddObjCObjectConversionStep(
3735                                      S.Context.getQualifiedType(T1, T2Quals));
3736
3737       ExprValueKind ValueKind =
3738         convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3739                                                  cv1T1, T1Quals, T2Quals,
3740                                                  isLValueRef);
3741       Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3742       return;
3743     }
3744
3745     //     - has a class type (i.e., T2 is a class type), where T1 is not
3746     //       reference-related to T2, and can be implicitly converted to an
3747     //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3748     //       with "cv3 T3" (this conversion is selected by enumerating the
3749     //       applicable conversion functions (13.3.1.6) and choosing the best
3750     //       one through overload resolution (13.3)),
3751     // If we have an rvalue ref to function type here, the rhs must be
3752     // an rvalue. DR1287 removed the "implicitly" here.
3753     if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3754         (isLValueRef || InitCategory.isRValue())) {
3755       ConvOvlResult = TryRefInitWithConversionFunction(
3756           S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
3757       if (ConvOvlResult == OR_Success)
3758         return;
3759       if (ConvOvlResult != OR_No_Viable_Function)
3760         Sequence.SetOverloadFailure(
3761             InitializationSequence::FK_ReferenceInitOverloadFailed,
3762             ConvOvlResult);
3763     }
3764   }
3765
3766   //     - Otherwise, the reference shall be an lvalue reference to a
3767   //       non-volatile const type (i.e., cv1 shall be const), or the reference
3768   //       shall be an rvalue reference.
3769   if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3770     if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3771       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3772     else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3773       Sequence.SetOverloadFailure(
3774                         InitializationSequence::FK_ReferenceInitOverloadFailed,
3775                                   ConvOvlResult);
3776     else
3777       Sequence.SetFailed(InitCategory.isLValue()
3778         ? (RefRelationship == Sema::Ref_Related
3779              ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3780              : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3781         : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3782
3783     return;
3784   }
3785
3786   //    - If the initializer expression
3787   //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3788   //        "cv1 T1" is reference-compatible with "cv2 T2"
3789   // Note: functions are handled below.
3790   if (!T1Function &&
3791       (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3792        (Kind.isCStyleOrFunctionalCast() &&
3793         RefRelationship == Sema::Ref_Related)) &&
3794       (InitCategory.isXValue() ||
3795        (InitCategory.isPRValue() && T2->isRecordType()) ||
3796        (InitCategory.isPRValue() && T2->isArrayType()))) {
3797     ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3798     if (InitCategory.isPRValue() && T2->isRecordType()) {
3799       // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3800       // compiler the freedom to perform a copy here or bind to the
3801       // object, while C++0x requires that we bind directly to the
3802       // object. Hence, we always bind to the object without making an
3803       // extra copy. However, in C++03 requires that we check for the
3804       // presence of a suitable copy constructor:
3805       //
3806       //   The constructor that would be used to make the copy shall
3807       //   be callable whether or not the copy is actually done.
3808       if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
3809         Sequence.AddExtraneousCopyToTemporary(cv2T2);
3810       else if (S.getLangOpts().CPlusPlus11)
3811         CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3812     }
3813
3814     if (DerivedToBase)
3815       Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3816                                         ValueKind);
3817     else if (ObjCConversion)
3818       Sequence.AddObjCObjectConversionStep(
3819                                        S.Context.getQualifiedType(T1, T2Quals));
3820
3821     ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3822                                                          Initializer, cv1T1,
3823                                                          T1Quals, T2Quals,
3824                                                          isLValueRef);
3825
3826     Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3827     return;
3828   }
3829
3830   //       - has a class type (i.e., T2 is a class type), where T1 is not
3831   //         reference-related to T2, and can be implicitly converted to an
3832   //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
3833   //         where "cv1 T1" is reference-compatible with "cv3 T3",
3834   //
3835   // DR1287 removes the "implicitly" here.
3836   if (T2->isRecordType()) {
3837     if (RefRelationship == Sema::Ref_Incompatible) {
3838       ConvOvlResult = TryRefInitWithConversionFunction(
3839           S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
3840       if (ConvOvlResult)
3841         Sequence.SetOverloadFailure(
3842             InitializationSequence::FK_ReferenceInitOverloadFailed,
3843             ConvOvlResult);
3844
3845       return;
3846     }
3847
3848     if ((RefRelationship == Sema::Ref_Compatible ||
3849          RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3850         isRValueRef && InitCategory.isLValue()) {
3851       Sequence.SetFailed(
3852         InitializationSequence::FK_RValueReferenceBindingToLValue);
3853       return;
3854     }
3855
3856     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3857     return;
3858   }
3859
3860   //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
3861   //        from the initializer expression using the rules for a non-reference
3862   //        copy-initialization (8.5). The reference is then bound to the
3863   //        temporary. [...]
3864
3865   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3866
3867   // FIXME: Why do we use an implicit conversion here rather than trying
3868   // copy-initialization?
3869   ImplicitConversionSequence ICS
3870     = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3871                               /*SuppressUserConversions=*/false,
3872                               /*AllowExplicit=*/false,
3873                               /*FIXME:InOverloadResolution=*/false,
3874                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3875                               /*AllowObjCWritebackConversion=*/false);
3876   
3877   if (ICS.isBad()) {
3878     // FIXME: Use the conversion function set stored in ICS to turn
3879     // this into an overloading ambiguity diagnostic. However, we need
3880     // to keep that set as an OverloadCandidateSet rather than as some
3881     // other kind of set.
3882     if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3883       Sequence.SetOverloadFailure(
3884                         InitializationSequence::FK_ReferenceInitOverloadFailed,
3885                                   ConvOvlResult);
3886     else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3887       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3888     else
3889       Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3890     return;
3891   } else {
3892     Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3893   }
3894
3895   //        [...] If T1 is reference-related to T2, cv1 must be the
3896   //        same cv-qualification as, or greater cv-qualification
3897   //        than, cv2; otherwise, the program is ill-formed.
3898   unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3899   unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3900   if (RefRelationship == Sema::Ref_Related &&
3901       (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3902     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3903     return;
3904   }
3905
3906   //   [...] If T1 is reference-related to T2 and the reference is an rvalue
3907   //   reference, the initializer expression shall not be an lvalue.
3908   if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3909       InitCategory.isLValue()) {
3910     Sequence.SetFailed(
3911                     InitializationSequence::FK_RValueReferenceBindingToLValue);
3912     return;
3913   }
3914
3915   Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3916   return;
3917 }
3918
3919 /// \brief Attempt character array initialization from a string literal
3920 /// (C++ [dcl.init.string], C99 6.7.8).
3921 static void TryStringLiteralInitialization(Sema &S,
3922                                            const InitializedEntity &Entity,
3923                                            const InitializationKind &Kind,
3924                                            Expr *Initializer,
3925                                        InitializationSequence &Sequence) {
3926   Sequence.AddStringInitStep(Entity.getType());
3927 }
3928
3929 /// \brief Attempt value initialization (C++ [dcl.init]p7).
3930 static void TryValueInitialization(Sema &S,
3931                                    const InitializedEntity &Entity,
3932                                    const InitializationKind &Kind,
3933                                    InitializationSequence &Sequence,
3934                                    InitListExpr *InitList) {
3935   assert((!InitList || InitList->getNumInits() == 0) &&
3936          "Shouldn't use value-init for non-empty init lists");
3937
3938   // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3939   //
3940   //   To value-initialize an object of type T means:
3941   QualType T = Entity.getType();
3942
3943   //     -- if T is an array type, then each element is value-initialized;
3944   T = S.Context.getBaseElementType(T);
3945
3946   if (const RecordType *RT = T->getAs<RecordType>()) {
3947     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3948       bool NeedZeroInitialization = true;
3949       if (!S.getLangOpts().CPlusPlus11) {
3950         // C++98:
3951         // -- if T is a class type (clause 9) with a user-declared constructor
3952         //    (12.1), then the default constructor for T is called (and the
3953         //    initialization is ill-formed if T has no accessible default
3954         //    constructor);
3955         if (ClassDecl->hasUserDeclaredConstructor())
3956           NeedZeroInitialization = false;
3957       } else {
3958         // C++11:
3959         // -- if T is a class type (clause 9) with either no default constructor
3960         //    (12.1 [class.ctor]) or a default constructor that is user-provided
3961         //    or deleted, then the object is default-initialized;
3962         CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3963         if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3964           NeedZeroInitialization = false;
3965       }
3966
3967       // -- if T is a (possibly cv-qualified) non-union class type without a
3968       //    user-provided or deleted default constructor, then the object is
3969       //    zero-initialized and, if T has a non-trivial default constructor,
3970       //    default-initialized;
3971       // The 'non-union' here was removed by DR1502. The 'non-trivial default
3972       // constructor' part was removed by DR1507.
3973       if (NeedZeroInitialization)
3974         Sequence.AddZeroInitializationStep(Entity.getType());
3975
3976       // C++03:
3977       // -- if T is a non-union class type without a user-declared constructor,
3978       //    then every non-static data member and base class component of T is
3979       //    value-initialized;
3980       // [...] A program that calls for [...] value-initialization of an
3981       // entity of reference type is ill-formed.
3982       //
3983       // C++11 doesn't need this handling, because value-initialization does not
3984       // occur recursively there, and the implicit default constructor is
3985       // defined as deleted in the problematic cases.
3986       if (!S.getLangOpts().CPlusPlus11 &&
3987           ClassDecl->hasUninitializedReferenceMember()) {
3988         Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3989         return;
3990       }
3991
3992       // If this is list-value-initialization, pass the empty init list on when
3993       // building the constructor call. This affects the semantics of a few
3994       // things (such as whether an explicit default constructor can be called).
3995       Expr *InitListAsExpr = InitList;
3996       MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
3997       bool InitListSyntax = InitList;
3998
3999       return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4000                                           InitListSyntax);
4001     }
4002   }
4003
4004   Sequence.AddZeroInitializationStep(Entity.getType());
4005 }
4006
4007 /// \brief Attempt default initialization (C++ [dcl.init]p6).
4008 static void TryDefaultInitialization(Sema &S,
4009                                      const InitializedEntity &Entity,
4010                                      const InitializationKind &Kind,
4011                                      InitializationSequence &Sequence) {
4012   assert(Kind.getKind() == InitializationKind::IK_Default);
4013
4014   // C++ [dcl.init]p6:
4015   //   To default-initialize an object of type T means:
4016   //     - if T is an array type, each element is default-initialized;
4017   QualType DestType = S.Context.getBaseElementType(Entity.getType());
4018          
4019   //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
4020   //       constructor for T is called (and the initialization is ill-formed if
4021   //       T has no accessible default constructor);
4022   if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4023     TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
4024     return;
4025   }
4026
4027   //     - otherwise, no initialization is performed.
4028
4029   //   If a program calls for the default initialization of an object of
4030   //   a const-qualified type T, T shall be a class type with a user-provided
4031   //   default constructor.
4032   if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4033     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4034     return;
4035   }
4036
4037   // If the destination type has a lifetime property, zero-initialize it.
4038   if (DestType.getQualifiers().hasObjCLifetime()) {
4039     Sequence.AddZeroInitializationStep(Entity.getType());
4040     return;
4041   }
4042 }
4043
4044 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4045 /// which enumerates all conversion functions and performs overload resolution
4046 /// to select the best.
4047 static void TryUserDefinedConversion(Sema &S,
4048                                      const InitializedEntity &Entity,
4049                                      const InitializationKind &Kind,
4050                                      Expr *Initializer,
4051                                      InitializationSequence &Sequence,
4052                                      bool TopLevelOfInitList) {
4053   QualType DestType = Entity.getType();
4054   assert(!DestType->isReferenceType() && "References are handled elsewhere");
4055   QualType SourceType = Initializer->getType();
4056   assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4057          "Must have a class type to perform a user-defined conversion");
4058
4059   // Build the candidate set directly in the initialization sequence
4060   // structure, so that it will persist if we fail.
4061   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4062   CandidateSet.clear();
4063
4064   // Determine whether we are allowed to call explicit constructors or
4065   // explicit conversion operators.
4066   bool AllowExplicit = Kind.AllowExplicit();
4067
4068   if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4069     // The type we're converting to is a class type. Enumerate its constructors
4070     // to see if there is a suitable conversion.
4071     CXXRecordDecl *DestRecordDecl
4072       = cast<CXXRecordDecl>(DestRecordType->getDecl());
4073
4074     // Try to complete the type we're converting to.
4075     if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
4076       DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
4077       // The container holding the constructors can under certain conditions
4078       // be changed while iterating. To be safe we copy the lookup results
4079       // to a new container.
4080       SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
4081       for (SmallVectorImpl<NamedDecl *>::iterator
4082              Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
4083            Con != ConEnd; ++Con) {
4084         NamedDecl *D = *Con;
4085         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
4086
4087         // Find the constructor (which may be a template).
4088         CXXConstructorDecl *Constructor = 0;
4089         FunctionTemplateDecl *ConstructorTmpl
4090           = dyn_cast<FunctionTemplateDecl>(D);
4091         if (ConstructorTmpl)
4092           Constructor = cast<CXXConstructorDecl>(
4093                                            ConstructorTmpl->getTemplatedDecl());
4094         else
4095           Constructor = cast<CXXConstructorDecl>(D);
4096
4097         if (!Constructor->isInvalidDecl() &&
4098             Constructor->isConvertingConstructor(AllowExplicit)) {
4099           if (ConstructorTmpl)
4100             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4101                                            /*ExplicitArgs*/ 0,
4102                                            Initializer, CandidateSet,
4103                                            /*SuppressUserConversions=*/true);
4104           else
4105             S.AddOverloadCandidate(Constructor, FoundDecl,
4106                                    Initializer, CandidateSet,
4107                                    /*SuppressUserConversions=*/true);
4108         }
4109       }
4110     }
4111   }
4112
4113   SourceLocation DeclLoc = Initializer->getLocStart();
4114
4115   if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4116     // The type we're converting from is a class type, enumerate its conversion
4117     // functions.
4118
4119     // We can only enumerate the conversion functions for a complete type; if
4120     // the type isn't complete, simply skip this step.
4121     if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4122       CXXRecordDecl *SourceRecordDecl
4123         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4124
4125       std::pair<CXXRecordDecl::conversion_iterator,
4126                 CXXRecordDecl::conversion_iterator>
4127         Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4128       for (CXXRecordDecl::conversion_iterator
4129              I = Conversions.first, E = Conversions.second; I != E; ++I) {
4130         NamedDecl *D = *I;
4131         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4132         if (isa<UsingShadowDecl>(D))
4133           D = cast<UsingShadowDecl>(D)->getTargetDecl();
4134
4135         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4136         CXXConversionDecl *Conv;
4137         if (ConvTemplate)
4138           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4139         else
4140           Conv = cast<CXXConversionDecl>(D);
4141
4142         if (AllowExplicit || !Conv->isExplicit()) {
4143           if (ConvTemplate)
4144             S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4145                                              ActingDC, Initializer, DestType,
4146                                              CandidateSet);
4147           else
4148             S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4149                                      Initializer, DestType, CandidateSet);
4150         }
4151       }
4152     }
4153   }
4154
4155   // Perform overload resolution. If it fails, return the failed result.
4156   OverloadCandidateSet::iterator Best;
4157   if (OverloadingResult Result
4158         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4159     Sequence.SetOverloadFailure(
4160                         InitializationSequence::FK_UserConversionOverloadFailed,
4161                                 Result);
4162     return;
4163   }
4164
4165   FunctionDecl *Function = Best->Function;
4166   Function->setReferenced();
4167   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4168
4169   if (isa<CXXConstructorDecl>(Function)) {
4170     // Add the user-defined conversion step. Any cv-qualification conversion is
4171     // subsumed by the initialization. Per DR5, the created temporary is of the
4172     // cv-unqualified type of the destination.
4173     Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4174                                    DestType.getUnqualifiedType(),
4175                                    HadMultipleCandidates);
4176     return;
4177   }
4178
4179   // Add the user-defined conversion step that calls the conversion function.
4180   QualType ConvType = Function->getCallResultType();
4181   if (ConvType->getAs<RecordType>()) {
4182     // If we're converting to a class type, there may be an copy of
4183     // the resulting temporary object (possible to create an object of
4184     // a base class type). That copy is not a separate conversion, so
4185     // we just make a note of the actual destination type (possibly a
4186     // base class of the type returned by the conversion function) and
4187     // let the user-defined conversion step handle the conversion.
4188     Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4189                                    HadMultipleCandidates);
4190     return;
4191   }
4192
4193   Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4194                                  HadMultipleCandidates);
4195
4196   // If the conversion following the call to the conversion function
4197   // is interesting, add it as a separate step.
4198   if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4199       Best->FinalConversion.Third) {
4200     ImplicitConversionSequence ICS;
4201     ICS.setStandard();
4202     ICS.Standard = Best->FinalConversion;
4203     Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4204   }
4205 }
4206
4207 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4208 /// a function with a pointer return type contains a 'return false;' statement.
4209 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
4210 /// code using that header.
4211 ///
4212 /// Work around this by treating 'return false;' as zero-initializing the result
4213 /// if it's used in a pointer-returning function in a system header.
4214 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4215                                               const InitializedEntity &Entity,
4216                                               const Expr *Init) {
4217   return S.getLangOpts().CPlusPlus11 &&
4218          Entity.getKind() == InitializedEntity::EK_Result &&
4219          Entity.getType()->isPointerType() &&
4220          isa<CXXBoolLiteralExpr>(Init) &&
4221          !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4222          S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4223 }
4224
4225 /// The non-zero enum values here are indexes into diagnostic alternatives.
4226 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4227
4228 /// Determines whether this expression is an acceptable ICR source.
4229 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4230                                          bool isAddressOf, bool &isWeakAccess) {
4231   // Skip parens.
4232   e = e->IgnoreParens();
4233
4234   // Skip address-of nodes.
4235   if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4236     if (op->getOpcode() == UO_AddrOf)
4237       return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4238                                 isWeakAccess);
4239
4240   // Skip certain casts.
4241   } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4242     switch (ce->getCastKind()) {
4243     case CK_Dependent:
4244     case CK_BitCast:
4245     case CK_LValueBitCast:
4246     case CK_NoOp:
4247       return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4248
4249     case CK_ArrayToPointerDecay:
4250       return IIK_nonscalar;
4251
4252     case CK_NullToPointer:
4253       return IIK_okay;
4254
4255     default:
4256       break;
4257     }
4258
4259   // If we have a declaration reference, it had better be a local variable.
4260   } else if (isa<DeclRefExpr>(e)) {
4261     // set isWeakAccess to true, to mean that there will be an implicit 
4262     // load which requires a cleanup.
4263     if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4264       isWeakAccess = true;
4265     
4266     if (!isAddressOf) return IIK_nonlocal;
4267
4268     VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4269     if (!var) return IIK_nonlocal;
4270
4271     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4272
4273   // If we have a conditional operator, check both sides.
4274   } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4275     if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4276                                                 isWeakAccess))
4277       return iik;
4278
4279     return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4280
4281   // These are never scalar.
4282   } else if (isa<ArraySubscriptExpr>(e)) {
4283     return IIK_nonscalar;
4284
4285   // Otherwise, it needs to be a null pointer constant.
4286   } else {
4287     return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4288             ? IIK_okay : IIK_nonlocal);
4289   }
4290
4291   return IIK_nonlocal;
4292 }
4293
4294 /// Check whether the given expression is a valid operand for an
4295 /// indirect copy/restore.
4296 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4297   assert(src->isRValue());
4298   bool isWeakAccess = false;
4299   InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4300   // If isWeakAccess to true, there will be an implicit 
4301   // load which requires a cleanup.
4302   if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4303     S.ExprNeedsCleanups = true;
4304   
4305   if (iik == IIK_okay) return;
4306
4307   S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4308     << ((unsigned) iik - 1)  // shift index into diagnostic explanations
4309     << src->getSourceRange();
4310 }
4311
4312 /// \brief Determine whether we have compatible array types for the
4313 /// purposes of GNU by-copy array initialization.
4314 static bool hasCompatibleArrayTypes(ASTContext &Context,
4315                                     const ArrayType *Dest, 
4316                                     const ArrayType *Source) {
4317   // If the source and destination array types are equivalent, we're
4318   // done.
4319   if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4320     return true;
4321
4322   // Make sure that the element types are the same.
4323   if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4324     return false;
4325
4326   // The only mismatch we allow is when the destination is an
4327   // incomplete array type and the source is a constant array type.
4328   return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4329 }
4330
4331 static bool tryObjCWritebackConversion(Sema &S,
4332                                        InitializationSequence &Sequence,
4333                                        const InitializedEntity &Entity,
4334                                        Expr *Initializer) {
4335   bool ArrayDecay = false;
4336   QualType ArgType = Initializer->getType();
4337   QualType ArgPointee;
4338   if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4339     ArrayDecay = true;
4340     ArgPointee = ArgArrayType->getElementType();
4341     ArgType = S.Context.getPointerType(ArgPointee);
4342   }
4343       
4344   // Handle write-back conversion.
4345   QualType ConvertedArgType;
4346   if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4347                                    ConvertedArgType))
4348     return false;
4349
4350   // We should copy unless we're passing to an argument explicitly
4351   // marked 'out'.
4352   bool ShouldCopy = true;
4353   if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4354     ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4355
4356   // Do we need an lvalue conversion?
4357   if (ArrayDecay || Initializer->isGLValue()) {
4358     ImplicitConversionSequence ICS;
4359     ICS.setStandard();
4360     ICS.Standard.setAsIdentityConversion();
4361
4362     QualType ResultType;
4363     if (ArrayDecay) {
4364       ICS.Standard.First = ICK_Array_To_Pointer;
4365       ResultType = S.Context.getPointerType(ArgPointee);
4366     } else {
4367       ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4368       ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4369     }
4370           
4371     Sequence.AddConversionSequenceStep(ICS, ResultType);
4372   }
4373         
4374   Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4375   return true;
4376 }
4377
4378 static bool TryOCLSamplerInitialization(Sema &S,
4379                                         InitializationSequence &Sequence,
4380                                         QualType DestType,
4381                                         Expr *Initializer) {
4382   if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4383     !Initializer->isIntegerConstantExpr(S.getASTContext()))
4384     return false;
4385
4386   Sequence.AddOCLSamplerInitStep(DestType);
4387   return true;
4388 }
4389
4390 //
4391 // OpenCL 1.2 spec, s6.12.10
4392 //
4393 // The event argument can also be used to associate the
4394 // async_work_group_copy with a previous async copy allowing
4395 // an event to be shared by multiple async copies; otherwise
4396 // event should be zero.
4397 //
4398 static bool TryOCLZeroEventInitialization(Sema &S,
4399                                           InitializationSequence &Sequence,
4400                                           QualType DestType,
4401                                           Expr *Initializer) {
4402   if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4403       !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4404       (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4405     return false;
4406
4407   Sequence.AddOCLZeroEventStep(DestType);
4408   return true;
4409 }
4410
4411 InitializationSequence::InitializationSequence(Sema &S,
4412                                                const InitializedEntity &Entity,
4413                                                const InitializationKind &Kind,
4414                                                MultiExprArg Args,
4415                                                bool TopLevelOfInitList)
4416     : FailedCandidateSet(Kind.getLocation()) {
4417   InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4418 }
4419
4420 void InitializationSequence::InitializeFrom(Sema &S,
4421                                             const InitializedEntity &Entity,
4422                                             const InitializationKind &Kind,
4423                                             MultiExprArg Args,
4424                                             bool TopLevelOfInitList) {
4425   ASTContext &Context = S.Context;
4426
4427   // Eliminate non-overload placeholder types in the arguments.  We
4428   // need to do this before checking whether types are dependent
4429   // because lowering a pseudo-object expression might well give us
4430   // something of dependent type.
4431   for (unsigned I = 0, E = Args.size(); I != E; ++I)
4432     if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4433       // FIXME: should we be doing this here?
4434       ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4435       if (result.isInvalid()) {
4436         SetFailed(FK_PlaceholderType);
4437         return;
4438       }
4439       Args[I] = result.take();
4440     }
4441
4442   // C++0x [dcl.init]p16:
4443   //   The semantics of initializers are as follows. The destination type is
4444   //   the type of the object or reference being initialized and the source
4445   //   type is the type of the initializer expression. The source type is not
4446   //   defined when the initializer is a braced-init-list or when it is a
4447   //   parenthesized list of expressions.
4448   QualType DestType = Entity.getType();
4449
4450   if (DestType->isDependentType() ||
4451       Expr::hasAnyTypeDependentArguments(Args)) {
4452     SequenceKind = DependentSequence;
4453     return;
4454   }
4455
4456   // Almost everything is a normal sequence.
4457   setSequenceKind(NormalSequence);
4458
4459   QualType SourceType;
4460   Expr *Initializer = 0;
4461   if (Args.size() == 1) {
4462     Initializer = Args[0];
4463     if (!isa<InitListExpr>(Initializer))
4464       SourceType = Initializer->getType();
4465   }
4466
4467   //     - If the initializer is a (non-parenthesized) braced-init-list, the
4468   //       object is list-initialized (8.5.4).
4469   if (Kind.getKind() != InitializationKind::IK_Direct) {
4470     if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4471       TryListInitialization(S, Entity, Kind, InitList, *this);
4472       return;
4473     }
4474   }
4475
4476   //     - If the destination type is a reference type, see 8.5.3.
4477   if (DestType->isReferenceType()) {
4478     // C++0x [dcl.init.ref]p1:
4479     //   A variable declared to be a T& or T&&, that is, "reference to type T"
4480     //   (8.3.2), shall be initialized by an object, or function, of type T or
4481     //   by an object that can be converted into a T.
4482     // (Therefore, multiple arguments are not permitted.)
4483     if (Args.size() != 1)
4484       SetFailed(FK_TooManyInitsForReference);
4485     else
4486       TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4487     return;
4488   }
4489
4490   //     - If the initializer is (), the object is value-initialized.
4491   if (Kind.getKind() == InitializationKind::IK_Value ||
4492       (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
4493     TryValueInitialization(S, Entity, Kind, *this);
4494     return;
4495   }
4496
4497   // Handle default initialization.
4498   if (Kind.getKind() == InitializationKind::IK_Default) {
4499     TryDefaultInitialization(S, Entity, Kind, *this);
4500     return;
4501   }
4502
4503   //     - If the destination type is an array of characters, an array of
4504   //       char16_t, an array of char32_t, or an array of wchar_t, and the
4505   //       initializer is a string literal, see 8.5.2.
4506   //     - Otherwise, if the destination type is an array, the program is
4507   //       ill-formed.
4508   if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4509     if (Initializer && isa<VariableArrayType>(DestAT)) {
4510       SetFailed(FK_VariableLengthArrayHasInitializer);
4511       return;
4512     }
4513
4514     if (Initializer) {
4515       switch (IsStringInit(Initializer, DestAT, Context)) {
4516       case SIF_None:
4517         TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4518         return;
4519       case SIF_NarrowStringIntoWideChar:
4520         SetFailed(FK_NarrowStringIntoWideCharArray);
4521         return;
4522       case SIF_WideStringIntoChar:
4523         SetFailed(FK_WideStringIntoCharArray);
4524         return;
4525       case SIF_IncompatWideStringIntoWideChar:
4526         SetFailed(FK_IncompatWideStringIntoWideChar);
4527         return;
4528       case SIF_Other:
4529         break;
4530       }
4531     }
4532
4533     // Note: as an GNU C extension, we allow initialization of an
4534     // array from a compound literal that creates an array of the same
4535     // type, so long as the initializer has no side effects.
4536     if (!S.getLangOpts().CPlusPlus && Initializer &&
4537         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4538         Initializer->getType()->isArrayType()) {
4539       const ArrayType *SourceAT
4540         = Context.getAsArrayType(Initializer->getType());
4541       if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4542         SetFailed(FK_ArrayTypeMismatch);
4543       else if (Initializer->HasSideEffects(S.Context))
4544         SetFailed(FK_NonConstantArrayInit);
4545       else {
4546         AddArrayInitStep(DestType);
4547       }
4548     }
4549     // Note: as a GNU C++ extension, we allow list-initialization of a
4550     // class member of array type from a parenthesized initializer list.
4551     else if (S.getLangOpts().CPlusPlus &&
4552              Entity.getKind() == InitializedEntity::EK_Member &&
4553              Initializer && isa<InitListExpr>(Initializer)) {
4554       TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4555                             *this);
4556       AddParenthesizedArrayInitStep(DestType);
4557     } else if (DestAT->getElementType()->isCharType())
4558       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4559     else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4560       SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
4561     else
4562       SetFailed(FK_ArrayNeedsInitList);
4563
4564     return;
4565   }
4566
4567   // Determine whether we should consider writeback conversions for 
4568   // Objective-C ARC.
4569   bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4570          Entity.isParameterKind();
4571
4572   // We're at the end of the line for C: it's either a write-back conversion
4573   // or it's a C assignment. There's no need to check anything else.
4574   if (!S.getLangOpts().CPlusPlus) {
4575     // If allowed, check whether this is an Objective-C writeback conversion.
4576     if (allowObjCWritebackConversion &&
4577         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4578       return;
4579     }
4580
4581     if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4582       return;
4583
4584     if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4585       return;
4586
4587     // Handle initialization in C
4588     AddCAssignmentStep(DestType);
4589     MaybeProduceObjCObject(S, *this, Entity);
4590     return;
4591   }
4592
4593   assert(S.getLangOpts().CPlusPlus);
4594       
4595   //     - If the destination type is a (possibly cv-qualified) class type:
4596   if (DestType->isRecordType()) {
4597     //     - If the initialization is direct-initialization, or if it is
4598     //       copy-initialization where the cv-unqualified version of the
4599     //       source type is the same class as, or a derived class of, the
4600     //       class of the destination, constructors are considered. [...]
4601     if (Kind.getKind() == InitializationKind::IK_Direct ||
4602         (Kind.getKind() == InitializationKind::IK_Copy &&
4603          (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4604           S.IsDerivedFrom(SourceType, DestType))))
4605       TryConstructorInitialization(S, Entity, Kind, Args,
4606                                    Entity.getType(), *this);
4607     //     - Otherwise (i.e., for the remaining copy-initialization cases),
4608     //       user-defined conversion sequences that can convert from the source
4609     //       type to the destination type or (when a conversion function is
4610     //       used) to a derived class thereof are enumerated as described in
4611     //       13.3.1.4, and the best one is chosen through overload resolution
4612     //       (13.3).
4613     else
4614       TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4615                                TopLevelOfInitList);
4616     return;
4617   }
4618
4619   if (Args.size() > 1) {
4620     SetFailed(FK_TooManyInitsForScalar);
4621     return;
4622   }
4623   assert(Args.size() == 1 && "Zero-argument case handled above");
4624
4625   //    - Otherwise, if the source type is a (possibly cv-qualified) class
4626   //      type, conversion functions are considered.
4627   if (!SourceType.isNull() && SourceType->isRecordType()) {
4628     TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4629                              TopLevelOfInitList);
4630     MaybeProduceObjCObject(S, *this, Entity);
4631     return;
4632   }
4633
4634   //    - Otherwise, the initial value of the object being initialized is the
4635   //      (possibly converted) value of the initializer expression. Standard
4636   //      conversions (Clause 4) will be used, if necessary, to convert the
4637   //      initializer expression to the cv-unqualified version of the
4638   //      destination type; no user-defined conversions are considered.
4639       
4640   ImplicitConversionSequence ICS
4641     = S.TryImplicitConversion(Initializer, Entity.getType(),
4642                               /*SuppressUserConversions*/true,
4643                               /*AllowExplicitConversions*/ false,
4644                               /*InOverloadResolution*/ false,
4645                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4646                               allowObjCWritebackConversion);
4647       
4648   if (ICS.isStandard() && 
4649       ICS.Standard.Second == ICK_Writeback_Conversion) {
4650     // Objective-C ARC writeback conversion.
4651     
4652     // We should copy unless we're passing to an argument explicitly
4653     // marked 'out'.
4654     bool ShouldCopy = true;
4655     if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4656       ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4657     
4658     // If there was an lvalue adjustment, add it as a separate conversion.
4659     if (ICS.Standard.First == ICK_Array_To_Pointer ||
4660         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4661       ImplicitConversionSequence LvalueICS;
4662       LvalueICS.setStandard();
4663       LvalueICS.Standard.setAsIdentityConversion();
4664       LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4665       LvalueICS.Standard.First = ICS.Standard.First;
4666       AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4667     }
4668     
4669     AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4670   } else if (ICS.isBad()) {
4671     DeclAccessPair dap;
4672     if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4673       AddZeroInitializationStep(Entity.getType());
4674     } else if (Initializer->getType() == Context.OverloadTy &&
4675                !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4676                                                      false, dap))
4677       SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4678     else
4679       SetFailed(InitializationSequence::FK_ConversionFailed);
4680   } else {
4681     AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
4682
4683     MaybeProduceObjCObject(S, *this, Entity);
4684   }
4685 }
4686
4687 InitializationSequence::~InitializationSequence() {
4688   for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4689                                           StepEnd = Steps.end();
4690        Step != StepEnd; ++Step)
4691     Step->Destroy();
4692 }
4693
4694 //===----------------------------------------------------------------------===//
4695 // Perform initialization
4696 //===----------------------------------------------------------------------===//
4697 static Sema::AssignmentAction
4698 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
4699   switch(Entity.getKind()) {
4700   case InitializedEntity::EK_Variable:
4701   case InitializedEntity::EK_New:
4702   case InitializedEntity::EK_Exception:
4703   case InitializedEntity::EK_Base:
4704   case InitializedEntity::EK_Delegating:
4705     return Sema::AA_Initializing;
4706
4707   case InitializedEntity::EK_Parameter:
4708     if (Entity.getDecl() &&
4709         isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4710       return Sema::AA_Sending;
4711
4712     return Sema::AA_Passing;
4713
4714   case InitializedEntity::EK_Parameter_CF_Audited:
4715     if (Entity.getDecl() &&
4716       isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4717       return Sema::AA_Sending;
4718       
4719     return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4720       
4721   case InitializedEntity::EK_Result:
4722     return Sema::AA_Returning;
4723
4724   case InitializedEntity::EK_Temporary:
4725   case InitializedEntity::EK_RelatedResult:
4726     // FIXME: Can we tell apart casting vs. converting?
4727     return Sema::AA_Casting;
4728
4729   case InitializedEntity::EK_Member:
4730   case InitializedEntity::EK_ArrayElement:
4731   case InitializedEntity::EK_VectorElement:
4732   case InitializedEntity::EK_ComplexElement:
4733   case InitializedEntity::EK_BlockElement:
4734   case InitializedEntity::EK_LambdaCapture:
4735   case InitializedEntity::EK_CompoundLiteralInit:
4736     return Sema::AA_Initializing;
4737   }
4738
4739   llvm_unreachable("Invalid EntityKind!");
4740 }
4741
4742 /// \brief Whether we should bind a created object as a temporary when
4743 /// initializing the given entity.
4744 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4745   switch (Entity.getKind()) {
4746   case InitializedEntity::EK_ArrayElement:
4747   case InitializedEntity::EK_Member:
4748   case InitializedEntity::EK_Result:
4749   case InitializedEntity::EK_New:
4750   case InitializedEntity::EK_Variable:
4751   case InitializedEntity::EK_Base:
4752   case InitializedEntity::EK_Delegating:
4753   case InitializedEntity::EK_VectorElement:
4754   case InitializedEntity::EK_ComplexElement:
4755   case InitializedEntity::EK_Exception:
4756   case InitializedEntity::EK_BlockElement:
4757   case InitializedEntity::EK_LambdaCapture:
4758   case InitializedEntity::EK_CompoundLiteralInit:
4759     return false;
4760
4761   case InitializedEntity::EK_Parameter:
4762   case InitializedEntity::EK_Parameter_CF_Audited:
4763   case InitializedEntity::EK_Temporary:
4764   case InitializedEntity::EK_RelatedResult:
4765     return true;
4766   }
4767
4768   llvm_unreachable("missed an InitializedEntity kind?");
4769 }
4770
4771 /// \brief Whether the given entity, when initialized with an object
4772 /// created for that initialization, requires destruction.
4773 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4774   switch (Entity.getKind()) {
4775     case InitializedEntity::EK_Result:
4776     case InitializedEntity::EK_New:
4777     case InitializedEntity::EK_Base:
4778     case InitializedEntity::EK_Delegating:
4779     case InitializedEntity::EK_VectorElement:
4780     case InitializedEntity::EK_ComplexElement:
4781     case InitializedEntity::EK_BlockElement:
4782     case InitializedEntity::EK_LambdaCapture:
4783       return false;
4784
4785     case InitializedEntity::EK_Member:
4786     case InitializedEntity::EK_Variable:
4787     case InitializedEntity::EK_Parameter:
4788     case InitializedEntity::EK_Parameter_CF_Audited:
4789     case InitializedEntity::EK_Temporary:
4790     case InitializedEntity::EK_ArrayElement:
4791     case InitializedEntity::EK_Exception:
4792     case InitializedEntity::EK_CompoundLiteralInit:
4793     case InitializedEntity::EK_RelatedResult:
4794       return true;
4795   }
4796
4797   llvm_unreachable("missed an InitializedEntity kind?");
4798 }
4799
4800 /// \brief Look for copy and move constructors and constructor templates, for
4801 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4802 static void LookupCopyAndMoveConstructors(Sema &S,
4803                                           OverloadCandidateSet &CandidateSet,
4804                                           CXXRecordDecl *Class,
4805                                           Expr *CurInitExpr) {
4806   DeclContext::lookup_result R = S.LookupConstructors(Class);
4807   // The container holding the constructors can under certain conditions
4808   // be changed while iterating (e.g. because of deserialization).
4809   // To be safe we copy the lookup results to a new container.
4810   SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
4811   for (SmallVectorImpl<NamedDecl *>::iterator
4812          CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4813     NamedDecl *D = *CI;
4814     CXXConstructorDecl *Constructor = 0;
4815
4816     if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
4817       // Handle copy/moveconstructors, only.
4818       if (!Constructor || Constructor->isInvalidDecl() ||
4819           !Constructor->isCopyOrMoveConstructor() ||
4820           !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4821         continue;
4822
4823       DeclAccessPair FoundDecl
4824         = DeclAccessPair::make(Constructor, Constructor->getAccess());
4825       S.AddOverloadCandidate(Constructor, FoundDecl,
4826                              CurInitExpr, CandidateSet);
4827       continue;
4828     }
4829
4830     // Handle constructor templates.
4831     FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
4832     if (ConstructorTmpl->isInvalidDecl())
4833       continue;
4834
4835     Constructor = cast<CXXConstructorDecl>(
4836                                          ConstructorTmpl->getTemplatedDecl());
4837     if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4838       continue;
4839
4840     // FIXME: Do we need to limit this to copy-constructor-like
4841     // candidates?
4842     DeclAccessPair FoundDecl
4843       = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4844     S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4845                                    CurInitExpr, CandidateSet, true);
4846   }
4847 }
4848
4849 /// \brief Get the location at which initialization diagnostics should appear.
4850 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4851                                            Expr *Initializer) {
4852   switch (Entity.getKind()) {
4853   case InitializedEntity::EK_Result:
4854     return Entity.getReturnLoc();
4855
4856   case InitializedEntity::EK_Exception:
4857     return Entity.getThrowLoc();
4858
4859   case InitializedEntity::EK_Variable:
4860     return Entity.getDecl()->getLocation();
4861
4862   case InitializedEntity::EK_LambdaCapture:
4863     return Entity.getCaptureLoc();
4864       
4865   case InitializedEntity::EK_ArrayElement:
4866   case InitializedEntity::EK_Member:
4867   case InitializedEntity::EK_Parameter:
4868   case InitializedEntity::EK_Parameter_CF_Audited:
4869   case InitializedEntity::EK_Temporary:
4870   case InitializedEntity::EK_New:
4871   case InitializedEntity::EK_Base:
4872   case InitializedEntity::EK_Delegating:
4873   case InitializedEntity::EK_VectorElement:
4874   case InitializedEntity::EK_ComplexElement:
4875   case InitializedEntity::EK_BlockElement:
4876   case InitializedEntity::EK_CompoundLiteralInit:
4877   case InitializedEntity::EK_RelatedResult:
4878     return Initializer->getLocStart();
4879   }
4880   llvm_unreachable("missed an InitializedEntity kind?");
4881 }
4882
4883 /// \brief Make a (potentially elidable) temporary copy of the object
4884 /// provided by the given initializer by calling the appropriate copy
4885 /// constructor.
4886 ///
4887 /// \param S The Sema object used for type-checking.
4888 ///
4889 /// \param T The type of the temporary object, which must either be
4890 /// the type of the initializer expression or a superclass thereof.
4891 ///
4892 /// \param Entity The entity being initialized.
4893 ///
4894 /// \param CurInit The initializer expression.
4895 ///
4896 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4897 /// is permitted in C++03 (but not C++0x) when binding a reference to
4898 /// an rvalue.
4899 ///
4900 /// \returns An expression that copies the initializer expression into
4901 /// a temporary object, or an error expression if a copy could not be
4902 /// created.
4903 static ExprResult CopyObject(Sema &S,
4904                              QualType T,
4905                              const InitializedEntity &Entity,
4906                              ExprResult CurInit,
4907                              bool IsExtraneousCopy) {
4908   // Determine which class type we're copying to.
4909   Expr *CurInitExpr = (Expr *)CurInit.get();
4910   CXXRecordDecl *Class = 0;
4911   if (const RecordType *Record = T->getAs<RecordType>())
4912     Class = cast<CXXRecordDecl>(Record->getDecl());
4913   if (!Class)
4914     return CurInit;
4915
4916   // C++0x [class.copy]p32:
4917   //   When certain criteria are met, an implementation is allowed to
4918   //   omit the copy/move construction of a class object, even if the
4919   //   copy/move constructor and/or destructor for the object have
4920   //   side effects. [...]
4921   //     - when a temporary class object that has not been bound to a
4922   //       reference (12.2) would be copied/moved to a class object
4923   //       with the same cv-unqualified type, the copy/move operation
4924   //       can be omitted by constructing the temporary object
4925   //       directly into the target of the omitted copy/move
4926   //
4927   // Note that the other three bullets are handled elsewhere. Copy
4928   // elision for return statements and throw expressions are handled as part
4929   // of constructor initialization, while copy elision for exception handlers
4930   // is handled by the run-time.
4931   bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4932   SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4933
4934   // Make sure that the type we are copying is complete.
4935   if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
4936     return CurInit;
4937
4938   // Perform overload resolution using the class's copy/move constructors.
4939   // Only consider constructors and constructor templates. Per
4940   // C++0x [dcl.init]p16, second bullet to class types, this initialization
4941   // is direct-initialization.
4942   OverloadCandidateSet CandidateSet(Loc);
4943   LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4944
4945   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4946
4947   OverloadCandidateSet::iterator Best;
4948   switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4949   case OR_Success:
4950     break;
4951
4952   case OR_No_Viable_Function:
4953     S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4954            ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4955            : diag::err_temp_copy_no_viable)
4956       << (int)Entity.getKind() << CurInitExpr->getType()
4957       << CurInitExpr->getSourceRange();
4958     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4959     if (!IsExtraneousCopy || S.isSFINAEContext())
4960       return ExprError();
4961     return CurInit;
4962
4963   case OR_Ambiguous:
4964     S.Diag(Loc, diag::err_temp_copy_ambiguous)
4965       << (int)Entity.getKind() << CurInitExpr->getType()
4966       << CurInitExpr->getSourceRange();
4967     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4968     return ExprError();
4969
4970   case OR_Deleted:
4971     S.Diag(Loc, diag::err_temp_copy_deleted)
4972       << (int)Entity.getKind() << CurInitExpr->getType()
4973       << CurInitExpr->getSourceRange();
4974     S.NoteDeletedFunction(Best->Function);
4975     return ExprError();
4976   }
4977
4978   CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4979   SmallVector<Expr*, 8> ConstructorArgs;
4980   CurInit.release(); // Ownership transferred into MultiExprArg, below.
4981
4982   S.CheckConstructorAccess(Loc, Constructor, Entity,
4983                            Best->FoundDecl.getAccess(), IsExtraneousCopy);
4984
4985   if (IsExtraneousCopy) {
4986     // If this is a totally extraneous copy for C++03 reference
4987     // binding purposes, just return the original initialization
4988     // expression. We don't generate an (elided) copy operation here
4989     // because doing so would require us to pass down a flag to avoid
4990     // infinite recursion, where each step adds another extraneous,
4991     // elidable copy.
4992
4993     // Instantiate the default arguments of any extra parameters in
4994     // the selected copy constructor, as if we were going to create a
4995     // proper call to the copy constructor.
4996     for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4997       ParmVarDecl *Parm = Constructor->getParamDecl(I);
4998       if (S.RequireCompleteType(Loc, Parm->getType(),
4999                                 diag::err_call_incomplete_argument))
5000         break;
5001
5002       // Build the default argument expression; we don't actually care
5003       // if this succeeds or not, because this routine will complain
5004       // if there was a problem.
5005       S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5006     }
5007
5008     return S.Owned(CurInitExpr);
5009   }
5010
5011   // Determine the arguments required to actually perform the
5012   // constructor call (we might have derived-to-base conversions, or
5013   // the copy constructor may have default arguments).
5014   if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5015     return ExprError();
5016
5017   // Actually perform the constructor call.
5018   CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
5019                                     ConstructorArgs,
5020                                     HadMultipleCandidates,
5021                                     /*ListInit*/ false,
5022                                     /*ZeroInit*/ false,
5023                                     CXXConstructExpr::CK_Complete,
5024                                     SourceRange());
5025
5026   // If we're supposed to bind temporaries, do so.
5027   if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5028     CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5029   return CurInit;
5030 }
5031
5032 /// \brief Check whether elidable copy construction for binding a reference to
5033 /// a temporary would have succeeded if we were building in C++98 mode, for
5034 /// -Wc++98-compat.
5035 static void CheckCXX98CompatAccessibleCopy(Sema &S,
5036                                            const InitializedEntity &Entity,
5037                                            Expr *CurInitExpr) {
5038   assert(S.getLangOpts().CPlusPlus11);
5039
5040   const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5041   if (!Record)
5042     return;
5043
5044   SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5045   if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
5046         == DiagnosticsEngine::Ignored)
5047     return;
5048
5049   // Find constructors which would have been considered.
5050   OverloadCandidateSet CandidateSet(Loc);
5051   LookupCopyAndMoveConstructors(
5052       S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5053
5054   // Perform overload resolution.
5055   OverloadCandidateSet::iterator Best;
5056   OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5057
5058   PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5059     << OR << (int)Entity.getKind() << CurInitExpr->getType()
5060     << CurInitExpr->getSourceRange();
5061
5062   switch (OR) {
5063   case OR_Success:
5064     S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5065                              Entity, Best->FoundDecl.getAccess(), Diag);
5066     // FIXME: Check default arguments as far as that's possible.
5067     break;
5068
5069   case OR_No_Viable_Function:
5070     S.Diag(Loc, Diag);
5071     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5072     break;
5073
5074   case OR_Ambiguous:
5075     S.Diag(Loc, Diag);
5076     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5077     break;
5078
5079   case OR_Deleted:
5080     S.Diag(Loc, Diag);
5081     S.NoteDeletedFunction(Best->Function);
5082     break;
5083   }
5084 }
5085
5086 void InitializationSequence::PrintInitLocationNote(Sema &S,
5087                                               const InitializedEntity &Entity) {
5088   if (Entity.isParameterKind() && Entity.getDecl()) {
5089     if (Entity.getDecl()->getLocation().isInvalid())
5090       return;
5091
5092     if (Entity.getDecl()->getDeclName())
5093       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5094         << Entity.getDecl()->getDeclName();
5095     else
5096       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5097   }
5098   else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5099            Entity.getMethodDecl())
5100     S.Diag(Entity.getMethodDecl()->getLocation(),
5101            diag::note_method_return_type_change)
5102       << Entity.getMethodDecl()->getDeclName();
5103 }
5104
5105 static bool isReferenceBinding(const InitializationSequence::Step &s) {
5106   return s.Kind == InitializationSequence::SK_BindReference ||
5107          s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5108 }
5109
5110 /// Returns true if the parameters describe a constructor initialization of
5111 /// an explicit temporary object, e.g. "Point(x, y)".
5112 static bool isExplicitTemporary(const InitializedEntity &Entity,
5113                                 const InitializationKind &Kind,
5114                                 unsigned NumArgs) {
5115   switch (Entity.getKind()) {
5116   case InitializedEntity::EK_Temporary:
5117   case InitializedEntity::EK_CompoundLiteralInit:
5118   case InitializedEntity::EK_RelatedResult:
5119     break;
5120   default:
5121     return false;
5122   }
5123
5124   switch (Kind.getKind()) {
5125   case InitializationKind::IK_DirectList:
5126     return true;
5127   // FIXME: Hack to work around cast weirdness.
5128   case InitializationKind::IK_Direct:
5129   case InitializationKind::IK_Value:
5130     return NumArgs != 1;
5131   default:
5132     return false;
5133   }
5134 }
5135
5136 static ExprResult
5137 PerformConstructorInitialization(Sema &S,
5138                                  const InitializedEntity &Entity,
5139                                  const InitializationKind &Kind,
5140                                  MultiExprArg Args,
5141                                  const InitializationSequence::Step& Step,
5142                                  bool &ConstructorInitRequiresZeroInit,
5143                                  bool IsListInitialization,
5144                                  SourceLocation LBraceLoc,
5145                                  SourceLocation RBraceLoc) {
5146   unsigned NumArgs = Args.size();
5147   CXXConstructorDecl *Constructor
5148     = cast<CXXConstructorDecl>(Step.Function.Function);
5149   bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5150
5151   // Build a call to the selected constructor.
5152   SmallVector<Expr*, 8> ConstructorArgs;
5153   SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5154                          ? Kind.getEqualLoc()
5155                          : Kind.getLocation();
5156
5157   if (Kind.getKind() == InitializationKind::IK_Default) {
5158     // Force even a trivial, implicit default constructor to be
5159     // semantically checked. We do this explicitly because we don't build
5160     // the definition for completely trivial constructors.
5161     assert(Constructor->getParent() && "No parent class for constructor.");
5162     if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5163         Constructor->isTrivial() && !Constructor->isUsed(false))
5164       S.DefineImplicitDefaultConstructor(Loc, Constructor);
5165   }
5166
5167   ExprResult CurInit = S.Owned((Expr *)0);
5168
5169   // C++ [over.match.copy]p1:
5170   //   - When initializing a temporary to be bound to the first parameter 
5171   //     of a constructor that takes a reference to possibly cv-qualified 
5172   //     T as its first argument, called with a single argument in the 
5173   //     context of direct-initialization, explicit conversion functions
5174   //     are also considered.
5175   bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5176                            Args.size() == 1 && 
5177                            Constructor->isCopyOrMoveConstructor();
5178
5179   // Determine the arguments required to actually perform the constructor
5180   // call.
5181   if (S.CompleteConstructorCall(Constructor, Args,
5182                                 Loc, ConstructorArgs,
5183                                 AllowExplicitConv,
5184                                 IsListInitialization))
5185     return ExprError();
5186
5187
5188   if (isExplicitTemporary(Entity, Kind, NumArgs)) {
5189     // An explicitly-constructed temporary, e.g., X(1, 2).
5190     S.MarkFunctionReferenced(Loc, Constructor);
5191     if (S.DiagnoseUseOfDecl(Constructor, Loc))
5192       return ExprError();
5193
5194     TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5195     if (!TSInfo)
5196       TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
5197     SourceRange ParenOrBraceRange =
5198       (Kind.getKind() == InitializationKind::IK_DirectList)
5199       ? SourceRange(LBraceLoc, RBraceLoc)
5200       : Kind.getParenRange();
5201
5202     CurInit = S.Owned(
5203       new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5204                                              TSInfo, ConstructorArgs,
5205                                              ParenOrBraceRange,
5206                                              HadMultipleCandidates,
5207                                              IsListInitialization,
5208                                              ConstructorInitRequiresZeroInit));
5209   } else {
5210     CXXConstructExpr::ConstructionKind ConstructKind =
5211       CXXConstructExpr::CK_Complete;
5212
5213     if (Entity.getKind() == InitializedEntity::EK_Base) {
5214       ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5215         CXXConstructExpr::CK_VirtualBase :
5216         CXXConstructExpr::CK_NonVirtualBase;
5217     } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5218       ConstructKind = CXXConstructExpr::CK_Delegating;
5219     }
5220
5221     // Only get the parenthesis range if it is a direct construction.
5222     SourceRange parenRange =
5223         Kind.getKind() == InitializationKind::IK_Direct ?
5224         Kind.getParenRange() : SourceRange();
5225
5226     // If the entity allows NRVO, mark the construction as elidable
5227     // unconditionally.
5228     if (Entity.allowsNRVO())
5229       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5230                                         Constructor, /*Elidable=*/true,
5231                                         ConstructorArgs,
5232                                         HadMultipleCandidates,
5233                                         IsListInitialization,
5234                                         ConstructorInitRequiresZeroInit,
5235                                         ConstructKind,
5236                                         parenRange);
5237     else
5238       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5239                                         Constructor,
5240                                         ConstructorArgs,
5241                                         HadMultipleCandidates,
5242                                         IsListInitialization,
5243                                         ConstructorInitRequiresZeroInit,
5244                                         ConstructKind,
5245                                         parenRange);
5246   }
5247   if (CurInit.isInvalid())
5248     return ExprError();
5249
5250   // Only check access if all of that succeeded.
5251   S.CheckConstructorAccess(Loc, Constructor, Entity,
5252                            Step.Function.FoundDecl.getAccess());
5253   if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5254     return ExprError();
5255
5256   if (shouldBindAsTemporary(Entity))
5257     CurInit = S.MaybeBindToTemporary(CurInit.take());
5258
5259   return CurInit;
5260 }
5261
5262 /// Determine whether the specified InitializedEntity definitely has a lifetime
5263 /// longer than the current full-expression. Conservatively returns false if
5264 /// it's unclear.
5265 static bool
5266 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5267   const InitializedEntity *Top = &Entity;
5268   while (Top->getParent())
5269     Top = Top->getParent();
5270
5271   switch (Top->getKind()) {
5272   case InitializedEntity::EK_Variable:
5273   case InitializedEntity::EK_Result:
5274   case InitializedEntity::EK_Exception:
5275   case InitializedEntity::EK_Member:
5276   case InitializedEntity::EK_New:
5277   case InitializedEntity::EK_Base:
5278   case InitializedEntity::EK_Delegating:
5279     return true;
5280
5281   case InitializedEntity::EK_ArrayElement:
5282   case InitializedEntity::EK_VectorElement:
5283   case InitializedEntity::EK_BlockElement:
5284   case InitializedEntity::EK_ComplexElement:
5285     // Could not determine what the full initialization is. Assume it might not
5286     // outlive the full-expression.
5287     return false;
5288
5289   case InitializedEntity::EK_Parameter:
5290   case InitializedEntity::EK_Parameter_CF_Audited:
5291   case InitializedEntity::EK_Temporary:
5292   case InitializedEntity::EK_LambdaCapture:
5293   case InitializedEntity::EK_CompoundLiteralInit:
5294   case InitializedEntity::EK_RelatedResult:
5295     // The entity being initialized might not outlive the full-expression.
5296     return false;
5297   }
5298
5299   llvm_unreachable("unknown entity kind");
5300 }
5301
5302 /// Determine the declaration which an initialized entity ultimately refers to,
5303 /// for the purpose of lifetime-extending a temporary bound to a reference in
5304 /// the initialization of \p Entity.
5305 static const ValueDecl *
5306 getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5307                                      const ValueDecl *FallbackDecl = 0) {
5308   // C++11 [class.temporary]p5:
5309   switch (Entity.getKind()) {
5310   case InitializedEntity::EK_Variable:
5311     //   The temporary [...] persists for the lifetime of the reference
5312     return Entity.getDecl();
5313
5314   case InitializedEntity::EK_Member:
5315     // For subobjects, we look at the complete object.
5316     if (Entity.getParent())
5317       return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5318                                                   Entity.getDecl());
5319
5320     //   except:
5321     //   -- A temporary bound to a reference member in a constructor's
5322     //      ctor-initializer persists until the constructor exits.
5323     return Entity.getDecl();
5324
5325   case InitializedEntity::EK_Parameter:
5326   case InitializedEntity::EK_Parameter_CF_Audited:
5327     //   -- A temporary bound to a reference parameter in a function call
5328     //      persists until the completion of the full-expression containing
5329     //      the call.
5330   case InitializedEntity::EK_Result:
5331     //   -- The lifetime of a temporary bound to the returned value in a
5332     //      function return statement is not extended; the temporary is
5333     //      destroyed at the end of the full-expression in the return statement.
5334   case InitializedEntity::EK_New:
5335     //   -- A temporary bound to a reference in a new-initializer persists
5336     //      until the completion of the full-expression containing the
5337     //      new-initializer.
5338     return 0;
5339
5340   case InitializedEntity::EK_Temporary:
5341   case InitializedEntity::EK_CompoundLiteralInit:
5342   case InitializedEntity::EK_RelatedResult:
5343     // We don't yet know the storage duration of the surrounding temporary.
5344     // Assume it's got full-expression duration for now, it will patch up our
5345     // storage duration if that's not correct.
5346     return 0;
5347
5348   case InitializedEntity::EK_ArrayElement:
5349     // For subobjects, we look at the complete object.
5350     return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5351                                                 FallbackDecl);
5352
5353   case InitializedEntity::EK_Base:
5354   case InitializedEntity::EK_Delegating:
5355     // We can reach this case for aggregate initialization in a constructor:
5356     //   struct A { int &&r; };
5357     //   struct B : A { B() : A{0} {} };
5358     // In this case, use the innermost field decl as the context.
5359     return FallbackDecl;
5360
5361   case InitializedEntity::EK_BlockElement:
5362   case InitializedEntity::EK_LambdaCapture:
5363   case InitializedEntity::EK_Exception:
5364   case InitializedEntity::EK_VectorElement:
5365   case InitializedEntity::EK_ComplexElement:
5366     return 0;
5367   }
5368   llvm_unreachable("unknown entity kind");
5369 }
5370
5371 static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5372
5373 /// Update a glvalue expression that is used as the initializer of a reference
5374 /// to note that its lifetime is extended.
5375 /// \return \c true if any temporary had its lifetime extended.
5376 static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
5377   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5378     if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5379       // This is just redundant braces around an initializer. Step over it.
5380       Init = ILE->getInit(0);
5381     }
5382   }
5383
5384   // Walk past any constructs which we can lifetime-extend across.
5385   Expr *Old;
5386   do {
5387     Old = Init;
5388
5389     // Step over any subobject adjustments; we may have a materialized
5390     // temporary inside them.
5391     SmallVector<const Expr *, 2> CommaLHSs;
5392     SmallVector<SubobjectAdjustment, 2> Adjustments;
5393     Init = const_cast<Expr *>(
5394         Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5395
5396     // Per current approach for DR1376, look through casts to reference type
5397     // when performing lifetime extension.
5398     if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5399       if (CE->getSubExpr()->isGLValue())
5400         Init = CE->getSubExpr();
5401
5402     // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5403     // It's unclear if binding a reference to that xvalue extends the array
5404     // temporary.
5405   } while (Init != Old);
5406
5407   if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5408     // Update the storage duration of the materialized temporary.
5409     // FIXME: Rebuild the expression instead of mutating it.
5410     ME->setExtendingDecl(ExtendingD);
5411     performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
5412     return true;
5413   }
5414
5415   return false;
5416 }
5417
5418 /// Update a prvalue expression that is going to be materialized as a
5419 /// lifetime-extended temporary.
5420 static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5421   // Dig out the expression which constructs the extended temporary.
5422   SmallVector<const Expr *, 2> CommaLHSs;
5423   SmallVector<SubobjectAdjustment, 2> Adjustments;
5424   Init = const_cast<Expr *>(
5425       Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5426
5427   if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5428     Init = BTE->getSubExpr();
5429
5430   if (CXXStdInitializerListExpr *ILE =
5431           dyn_cast<CXXStdInitializerListExpr>(Init)) {
5432     performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5433     return;
5434   }
5435
5436   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5437     if (ILE->getType()->isArrayType()) {
5438       for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5439         performLifetimeExtension(ILE->getInit(I), ExtendingD);
5440       return;
5441     }
5442
5443     if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
5444       assert(RD->isAggregate() && "aggregate init on non-aggregate");
5445
5446       // If we lifetime-extend a braced initializer which is initializing an
5447       // aggregate, and that aggregate contains reference members which are
5448       // bound to temporaries, those temporaries are also lifetime-extended.
5449       if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5450           ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5451         performReferenceExtension(ILE->getInit(0), ExtendingD);
5452       else {
5453         unsigned Index = 0;
5454         for (RecordDecl::field_iterator I = RD->field_begin(),
5455                                         E = RD->field_end();
5456              I != E; ++I) {
5457           if (Index >= ILE->getNumInits())
5458             break;
5459           if (I->isUnnamedBitfield())
5460             continue;
5461           Expr *SubInit = ILE->getInit(Index);
5462           if (I->getType()->isReferenceType())
5463             performReferenceExtension(SubInit, ExtendingD);
5464           else if (isa<InitListExpr>(SubInit) ||
5465                    isa<CXXStdInitializerListExpr>(SubInit))
5466             // This may be either aggregate-initialization of a member or
5467             // initialization of a std::initializer_list object. Either way,
5468             // we should recursively lifetime-extend that initializer.
5469             performLifetimeExtension(SubInit, ExtendingD);
5470           ++Index;
5471         }
5472       }
5473     }
5474   }
5475 }
5476
5477 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5478                                     const Expr *Init, bool IsInitializerList,
5479                                     const ValueDecl *ExtendingDecl) {
5480   // Warn if a field lifetime-extends a temporary.
5481   if (isa<FieldDecl>(ExtendingDecl)) {
5482     if (IsInitializerList) {
5483       S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5484         << /*at end of constructor*/true;
5485       return;
5486     }
5487
5488     bool IsSubobjectMember = false;
5489     for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5490          Ent = Ent->getParent()) {
5491       if (Ent->getKind() != InitializedEntity::EK_Base) {
5492         IsSubobjectMember = true;
5493         break;
5494       }
5495     }
5496     S.Diag(Init->getExprLoc(),
5497            diag::warn_bind_ref_member_to_temporary)
5498       << ExtendingDecl << Init->getSourceRange()
5499       << IsSubobjectMember << IsInitializerList;
5500     if (IsSubobjectMember)
5501       S.Diag(ExtendingDecl->getLocation(),
5502              diag::note_ref_subobject_of_member_declared_here);
5503     else
5504       S.Diag(ExtendingDecl->getLocation(),
5505              diag::note_ref_or_ptr_member_declared_here)
5506         << /*is pointer*/false;
5507   }
5508 }
5509
5510 static void DiagnoseNarrowingInInitList(Sema &S,
5511                                         const ImplicitConversionSequence &ICS,
5512                                         QualType PreNarrowingType,
5513                                         QualType EntityType,
5514                                         const Expr *PostInit);
5515
5516 ExprResult
5517 InitializationSequence::Perform(Sema &S,
5518                                 const InitializedEntity &Entity,
5519                                 const InitializationKind &Kind,
5520                                 MultiExprArg Args,
5521                                 QualType *ResultType) {
5522   if (Failed()) {
5523     Diagnose(S, Entity, Kind, Args);
5524     return ExprError();
5525   }
5526
5527   if (getKind() == DependentSequence) {
5528     // If the declaration is a non-dependent, incomplete array type
5529     // that has an initializer, then its type will be completed once
5530     // the initializer is instantiated.
5531     if (ResultType && !Entity.getType()->isDependentType() &&
5532         Args.size() == 1) {
5533       QualType DeclType = Entity.getType();
5534       if (const IncompleteArrayType *ArrayT
5535                            = S.Context.getAsIncompleteArrayType(DeclType)) {
5536         // FIXME: We don't currently have the ability to accurately
5537         // compute the length of an initializer list without
5538         // performing full type-checking of the initializer list
5539         // (since we have to determine where braces are implicitly
5540         // introduced and such).  So, we fall back to making the array
5541         // type a dependently-sized array type with no specified
5542         // bound.
5543         if (isa<InitListExpr>((Expr *)Args[0])) {
5544           SourceRange Brackets;
5545
5546           // Scavange the location of the brackets from the entity, if we can.
5547           if (DeclaratorDecl *DD = Entity.getDecl()) {
5548             if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5549               TypeLoc TL = TInfo->getTypeLoc();
5550               if (IncompleteArrayTypeLoc ArrayLoc =
5551                       TL.getAs<IncompleteArrayTypeLoc>())
5552                 Brackets = ArrayLoc.getBracketsRange();
5553             }
5554           }
5555
5556           *ResultType
5557             = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5558                                                    /*NumElts=*/0,
5559                                                    ArrayT->getSizeModifier(),
5560                                        ArrayT->getIndexTypeCVRQualifiers(),
5561                                                    Brackets);
5562         }
5563
5564       }
5565     }
5566     if (Kind.getKind() == InitializationKind::IK_Direct &&
5567         !Kind.isExplicitCast()) {
5568       // Rebuild the ParenListExpr.
5569       SourceRange ParenRange = Kind.getParenRange();
5570       return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
5571                                   Args);
5572     }
5573     assert(Kind.getKind() == InitializationKind::IK_Copy ||
5574            Kind.isExplicitCast() || 
5575            Kind.getKind() == InitializationKind::IK_DirectList);
5576     return ExprResult(Args[0]);
5577   }
5578
5579   // No steps means no initialization.
5580   if (Steps.empty())
5581     return S.Owned((Expr *)0);
5582
5583   if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
5584       Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
5585       !Entity.isParameterKind()) {
5586     // Produce a C++98 compatibility warning if we are initializing a reference
5587     // from an initializer list. For parameters, we produce a better warning
5588     // elsewhere.
5589     Expr *Init = Args[0];
5590     S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5591       << Init->getSourceRange();
5592   }
5593
5594   // Diagnose cases where we initialize a pointer to an array temporary, and the
5595   // pointer obviously outlives the temporary.
5596   if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
5597       Entity.getType()->isPointerType() &&
5598       InitializedEntityOutlivesFullExpression(Entity)) {
5599     Expr *Init = Args[0];
5600     Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5601     if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5602       S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5603         << Init->getSourceRange();
5604   }
5605
5606   QualType DestType = Entity.getType().getNonReferenceType();
5607   // FIXME: Ugly hack around the fact that Entity.getType() is not
5608   // the same as Entity.getDecl()->getType() in cases involving type merging,
5609   //  and we want latter when it makes sense.
5610   if (ResultType)
5611     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
5612                                      Entity.getType();
5613
5614   ExprResult CurInit = S.Owned((Expr *)0);
5615
5616   // For initialization steps that start with a single initializer,
5617   // grab the only argument out the Args and place it into the "current"
5618   // initializer.
5619   switch (Steps.front().Kind) {
5620   case SK_ResolveAddressOfOverloadedFunction:
5621   case SK_CastDerivedToBaseRValue:
5622   case SK_CastDerivedToBaseXValue:
5623   case SK_CastDerivedToBaseLValue:
5624   case SK_BindReference:
5625   case SK_BindReferenceToTemporary:
5626   case SK_ExtraneousCopyToTemporary:
5627   case SK_UserConversion:
5628   case SK_QualificationConversionLValue:
5629   case SK_QualificationConversionXValue:
5630   case SK_QualificationConversionRValue:
5631   case SK_LValueToRValue:
5632   case SK_ConversionSequence:
5633   case SK_ConversionSequenceNoNarrowing:
5634   case SK_ListInitialization:
5635   case SK_UnwrapInitList:
5636   case SK_RewrapInitList:
5637   case SK_CAssignment:
5638   case SK_StringInit:
5639   case SK_ObjCObjectConversion:
5640   case SK_ArrayInit:
5641   case SK_ParenthesizedArrayInit:
5642   case SK_PassByIndirectCopyRestore:
5643   case SK_PassByIndirectRestore:
5644   case SK_ProduceObjCObject:
5645   case SK_StdInitializerList:
5646   case SK_OCLSamplerInit:
5647   case SK_OCLZeroEvent: {
5648     assert(Args.size() == 1);
5649     CurInit = Args[0];
5650     if (!CurInit.get()) return ExprError();
5651     break;
5652   }
5653
5654   case SK_ConstructorInitialization:
5655   case SK_ListConstructorCall:
5656   case SK_ZeroInitialization:
5657     break;
5658   }
5659
5660   // Walk through the computed steps for the initialization sequence,
5661   // performing the specified conversions along the way.
5662   bool ConstructorInitRequiresZeroInit = false;
5663   for (step_iterator Step = step_begin(), StepEnd = step_end();
5664        Step != StepEnd; ++Step) {
5665     if (CurInit.isInvalid())
5666       return ExprError();
5667
5668     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
5669
5670     switch (Step->Kind) {
5671     case SK_ResolveAddressOfOverloadedFunction:
5672       // Overload resolution determined which function invoke; update the
5673       // initializer to reflect that choice.
5674       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
5675       if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5676         return ExprError();
5677       CurInit = S.FixOverloadedFunctionReference(CurInit,
5678                                                  Step->Function.FoundDecl,
5679                                                  Step->Function.Function);
5680       break;
5681
5682     case SK_CastDerivedToBaseRValue:
5683     case SK_CastDerivedToBaseXValue:
5684     case SK_CastDerivedToBaseLValue: {
5685       // We have a derived-to-base cast that produces either an rvalue or an
5686       // lvalue. Perform that cast.
5687
5688       CXXCastPath BasePath;
5689
5690       // Casts to inaccessible base classes are allowed with C-style casts.
5691       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5692       if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
5693                                          CurInit.get()->getLocStart(),
5694                                          CurInit.get()->getSourceRange(),
5695                                          &BasePath, IgnoreBaseAccess))
5696         return ExprError();
5697
5698       if (S.BasePathInvolvesVirtualBase(BasePath)) {
5699         QualType T = SourceType;
5700         if (const PointerType *Pointer = T->getAs<PointerType>())
5701           T = Pointer->getPointeeType();
5702         if (const RecordType *RecordTy = T->getAs<RecordType>())
5703           S.MarkVTableUsed(CurInit.get()->getLocStart(),
5704                            cast<CXXRecordDecl>(RecordTy->getDecl()));
5705       }
5706
5707       ExprValueKind VK =
5708           Step->Kind == SK_CastDerivedToBaseLValue ?
5709               VK_LValue :
5710               (Step->Kind == SK_CastDerivedToBaseXValue ?
5711                    VK_XValue :
5712                    VK_RValue);
5713       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5714                                                  Step->Type,
5715                                                  CK_DerivedToBase,
5716                                                  CurInit.get(),
5717                                                  &BasePath, VK));
5718       break;
5719     }
5720
5721     case SK_BindReference:
5722       // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5723       if (CurInit.get()->refersToBitField()) {
5724         // We don't necessarily have an unambiguous source bit-field.
5725         FieldDecl *BitField = CurInit.get()->getSourceBitField();
5726         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
5727           << Entity.getType().isVolatileQualified()
5728           << (BitField ? BitField->getDeclName() : DeclarationName())
5729           << (BitField != NULL)
5730           << CurInit.get()->getSourceRange();
5731         if (BitField)
5732           S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5733
5734         return ExprError();
5735       }
5736
5737       if (CurInit.get()->refersToVectorElement()) {
5738         // References cannot bind to vector elements.
5739         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5740           << Entity.getType().isVolatileQualified()
5741           << CurInit.get()->getSourceRange();
5742         PrintInitLocationNote(S, Entity);
5743         return ExprError();
5744       }
5745
5746       // Reference binding does not have any corresponding ASTs.
5747
5748       // Check exception specifications
5749       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5750         return ExprError();
5751
5752       // Even though we didn't materialize a temporary, the binding may still
5753       // extend the lifetime of a temporary. This happens if we bind a reference
5754       // to the result of a cast to reference type.
5755       if (const ValueDecl *ExtendingDecl =
5756               getDeclForTemporaryLifetimeExtension(Entity)) {
5757         if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5758           warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5759                                   ExtendingDecl);
5760       }
5761
5762       break;
5763
5764     case SK_BindReferenceToTemporary: {
5765       // Make sure the "temporary" is actually an rvalue.
5766       assert(CurInit.get()->isRValue() && "not a temporary");
5767
5768       // Check exception specifications
5769       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5770         return ExprError();
5771
5772       // Maybe lifetime-extend the temporary's subobjects to match the
5773       // entity's lifetime.
5774       const ValueDecl *ExtendingDecl =
5775           getDeclForTemporaryLifetimeExtension(Entity);
5776       if (ExtendingDecl) {
5777         performLifetimeExtension(CurInit.get(), ExtendingDecl);
5778         warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
5779       }
5780
5781       // Materialize the temporary into memory.
5782       MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
5783           Entity.getType().getNonReferenceType(), CurInit.get(),
5784           Entity.getType()->isLValueReferenceType(), ExtendingDecl);
5785
5786       // If we're binding to an Objective-C object that has lifetime, we
5787       // need cleanups. Likewise if we're extending this temporary to automatic
5788       // storage duration -- we need to register its cleanup during the
5789       // full-expression's cleanups.
5790       if ((S.getLangOpts().ObjCAutoRefCount &&
5791            MTE->getType()->isObjCLifetimeType()) ||
5792           (MTE->getStorageDuration() == SD_Automatic &&
5793            MTE->getType().isDestructedType()))
5794         S.ExprNeedsCleanups = true;
5795
5796       CurInit = S.Owned(MTE);
5797       break;
5798     }
5799
5800     case SK_ExtraneousCopyToTemporary:
5801       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
5802                            /*IsExtraneousCopy=*/true);
5803       break;
5804
5805     case SK_UserConversion: {
5806       // We have a user-defined conversion that invokes either a constructor
5807       // or a conversion function.
5808       CastKind CastKind;
5809       bool IsCopy = false;
5810       FunctionDecl *Fn = Step->Function.Function;
5811       DeclAccessPair FoundFn = Step->Function.FoundDecl;
5812       bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
5813       bool CreatedObject = false;
5814       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
5815         // Build a call to the selected constructor.
5816         SmallVector<Expr*, 8> ConstructorArgs;
5817         SourceLocation Loc = CurInit.get()->getLocStart();
5818         CurInit.release(); // Ownership transferred into MultiExprArg, below.
5819
5820         // Determine the arguments required to actually perform the constructor
5821         // call.
5822         Expr *Arg = CurInit.get();
5823         if (S.CompleteConstructorCall(Constructor,
5824                                       MultiExprArg(&Arg, 1),
5825                                       Loc, ConstructorArgs))
5826           return ExprError();
5827
5828         // Build an expression that constructs a temporary.
5829         CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5830                                           ConstructorArgs,
5831                                           HadMultipleCandidates,
5832                                           /*ListInit*/ false,
5833                                           /*ZeroInit*/ false,
5834                                           CXXConstructExpr::CK_Complete,
5835                                           SourceRange());
5836         if (CurInit.isInvalid())
5837           return ExprError();
5838
5839         S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
5840                                  FoundFn.getAccess());
5841         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5842           return ExprError();
5843
5844         CastKind = CK_ConstructorConversion;
5845         QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5846         if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5847             S.IsDerivedFrom(SourceType, Class))
5848           IsCopy = true;
5849
5850         CreatedObject = true;
5851       } else {
5852         // Build a call to the conversion function.
5853         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
5854         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
5855                                     FoundFn);
5856         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5857           return ExprError();
5858
5859         // FIXME: Should we move this initialization into a separate
5860         // derived-to-base conversion? I believe the answer is "no", because
5861         // we don't want to turn off access control here for c-style casts.
5862         ExprResult CurInitExprRes =
5863           S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5864                                                 FoundFn, Conversion);
5865         if(CurInitExprRes.isInvalid())
5866           return ExprError();
5867         CurInit = CurInitExprRes;
5868
5869         // Build the actual call to the conversion function.
5870         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5871                                            HadMultipleCandidates);
5872         if (CurInit.isInvalid() || !CurInit.get())
5873           return ExprError();
5874
5875         CastKind = CK_UserDefinedConversion;
5876
5877         CreatedObject = Conversion->getResultType()->isRecordType();
5878       }
5879
5880       bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
5881       bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5882
5883       if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
5884         QualType T = CurInit.get()->getType();
5885         if (const RecordType *Record = T->getAs<RecordType>()) {
5886           CXXDestructorDecl *Destructor
5887             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
5888           S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
5889                                   S.PDiag(diag::err_access_dtor_temp) << T);
5890           S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
5891           if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5892             return ExprError();
5893         }
5894       }
5895
5896       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5897                                                  CurInit.get()->getType(),
5898                                                  CastKind, CurInit.get(), 0,
5899                                                 CurInit.get()->getValueKind()));
5900       if (MaybeBindToTemp)
5901         CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5902       if (RequiresCopy)
5903         CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5904                              CurInit, /*IsExtraneousCopy=*/false);
5905       break;
5906     }
5907
5908     case SK_QualificationConversionLValue:
5909     case SK_QualificationConversionXValue:
5910     case SK_QualificationConversionRValue: {
5911       // Perform a qualification conversion; these can never go wrong.
5912       ExprValueKind VK =
5913           Step->Kind == SK_QualificationConversionLValue ?
5914               VK_LValue :
5915               (Step->Kind == SK_QualificationConversionXValue ?
5916                    VK_XValue :
5917                    VK_RValue);
5918       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5919       break;
5920     }
5921
5922     case SK_LValueToRValue: {
5923       assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5924       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5925                                                  CK_LValueToRValue,
5926                                                  CurInit.take(),
5927                                                  /*BasePath=*/0,
5928                                                  VK_RValue));
5929       break;
5930     }
5931
5932     case SK_ConversionSequence:
5933     case SK_ConversionSequenceNoNarrowing: {
5934       Sema::CheckedConversionKind CCK
5935         = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5936         : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5937         : Kind.isExplicitCast()? Sema::CCK_OtherCast
5938         : Sema::CCK_ImplicitConversion;
5939       ExprResult CurInitExprRes =
5940         S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5941                                     getAssignmentAction(Entity), CCK);
5942       if (CurInitExprRes.isInvalid())
5943         return ExprError();
5944       CurInit = CurInitExprRes;
5945
5946       if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5947           S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5948         DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5949                                     CurInit.get());
5950       break;
5951     }
5952
5953     case SK_ListInitialization: {
5954       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5955       // If we're not initializing the top-level entity, we need to create an
5956       // InitializeTemporary entity for our target type.
5957       QualType Ty = Step->Type;
5958       bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
5959       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5960       InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5961       InitListChecker PerformInitList(S, InitEntity,
5962           InitList, Ty, /*VerifyOnly=*/false);
5963       if (PerformInitList.HadError())
5964         return ExprError();
5965
5966       // Hack: We must update *ResultType if available in order to set the
5967       // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5968       // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5969       if (ResultType &&
5970           ResultType->getNonReferenceType()->isIncompleteArrayType()) {
5971         if ((*ResultType)->isRValueReferenceType())
5972           Ty = S.Context.getRValueReferenceType(Ty);
5973         else if ((*ResultType)->isLValueReferenceType())
5974           Ty = S.Context.getLValueReferenceType(Ty,
5975             (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5976         *ResultType = Ty;
5977       }
5978
5979       InitListExpr *StructuredInitList =
5980           PerformInitList.getFullyStructuredList();
5981       CurInit.release();
5982       CurInit = shouldBindAsTemporary(InitEntity)
5983           ? S.MaybeBindToTemporary(StructuredInitList)
5984           : S.Owned(StructuredInitList);
5985       break;
5986     }
5987
5988     case SK_ListConstructorCall: {
5989       // When an initializer list is passed for a parameter of type "reference
5990       // to object", we don't get an EK_Temporary entity, but instead an
5991       // EK_Parameter entity with reference type.
5992       // FIXME: This is a hack. What we really should do is create a user
5993       // conversion step for this case, but this makes it considerably more
5994       // complicated. For now, this will do.
5995       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
5996                                         Entity.getType().getNonReferenceType());
5997       bool UseTemporary = Entity.getType()->isReferenceType();
5998       assert(Args.size() == 1 && "expected a single argument for list init");
5999       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6000       S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6001         << InitList->getSourceRange();
6002       MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
6003       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6004                                                                    Entity,
6005                                                  Kind, Arg, *Step,
6006                                                ConstructorInitRequiresZeroInit,
6007                                                /*IsListInitialization*/ true,
6008                                                InitList->getLBraceLoc(),
6009                                                InitList->getRBraceLoc());
6010       break;
6011     }
6012
6013     case SK_UnwrapInitList:
6014       CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
6015       break;
6016
6017     case SK_RewrapInitList: {
6018       Expr *E = CurInit.take();
6019       InitListExpr *Syntactic = Step->WrappingSyntacticList;
6020       InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
6021           Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
6022       ILE->setSyntacticForm(Syntactic);
6023       ILE->setType(E->getType());
6024       ILE->setValueKind(E->getValueKind());
6025       CurInit = S.Owned(ILE);
6026       break;
6027     }
6028
6029     case SK_ConstructorInitialization: {
6030       // When an initializer list is passed for a parameter of type "reference
6031       // to object", we don't get an EK_Temporary entity, but instead an
6032       // EK_Parameter entity with reference type.
6033       // FIXME: This is a hack. What we really should do is create a user
6034       // conversion step for this case, but this makes it considerably more
6035       // complicated. For now, this will do.
6036       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6037                                         Entity.getType().getNonReferenceType());
6038       bool UseTemporary = Entity.getType()->isReferenceType();
6039       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6040                                                                  : Entity,
6041                                                  Kind, Args, *Step,
6042                                                ConstructorInitRequiresZeroInit,
6043                                                /*IsListInitialization*/ false,
6044                                                /*LBraceLoc*/ SourceLocation(),
6045                                                /*RBraceLoc*/ SourceLocation());
6046       break;
6047     }
6048
6049     case SK_ZeroInitialization: {
6050       step_iterator NextStep = Step;
6051       ++NextStep;
6052       if (NextStep != StepEnd &&
6053           (NextStep->Kind == SK_ConstructorInitialization ||
6054            NextStep->Kind == SK_ListConstructorCall)) {
6055         // The need for zero-initialization is recorded directly into
6056         // the call to the object's constructor within the next step.
6057         ConstructorInitRequiresZeroInit = true;
6058       } else if (Kind.getKind() == InitializationKind::IK_Value &&
6059                  S.getLangOpts().CPlusPlus &&
6060                  !Kind.isImplicitValueInit()) {
6061         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6062         if (!TSInfo)
6063           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
6064                                                     Kind.getRange().getBegin());
6065
6066         CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
6067                               TSInfo->getType().getNonLValueExprType(S.Context),
6068                                                                  TSInfo,
6069                                                     Kind.getRange().getEnd()));
6070       } else {
6071         CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
6072       }
6073       break;
6074     }
6075
6076     case SK_CAssignment: {
6077       QualType SourceType = CurInit.get()->getType();
6078       ExprResult Result = CurInit;
6079       Sema::AssignConvertType ConvTy =
6080         S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6081             Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
6082       if (Result.isInvalid())
6083         return ExprError();
6084       CurInit = Result;
6085
6086       // If this is a call, allow conversion to a transparent union.
6087       ExprResult CurInitExprRes = CurInit;
6088       if (ConvTy != Sema::Compatible &&
6089           Entity.isParameterKind() &&
6090           S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
6091             == Sema::Compatible)
6092         ConvTy = Sema::Compatible;
6093       if (CurInitExprRes.isInvalid())
6094         return ExprError();
6095       CurInit = CurInitExprRes;
6096
6097       bool Complained;
6098       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6099                                      Step->Type, SourceType,
6100                                      CurInit.get(),
6101                                      getAssignmentAction(Entity, true),
6102                                      &Complained)) {
6103         PrintInitLocationNote(S, Entity);
6104         return ExprError();
6105       } else if (Complained)
6106         PrintInitLocationNote(S, Entity);
6107       break;
6108     }
6109
6110     case SK_StringInit: {
6111       QualType Ty = Step->Type;
6112       CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
6113                       S.Context.getAsArrayType(Ty), S);
6114       break;
6115     }
6116
6117     case SK_ObjCObjectConversion:
6118       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6119                           CK_ObjCObjectLValueCast,
6120                           CurInit.get()->getValueKind());
6121       break;
6122
6123     case SK_ArrayInit:
6124       // Okay: we checked everything before creating this step. Note that
6125       // this is a GNU extension.
6126       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
6127         << Step->Type << CurInit.get()->getType()
6128         << CurInit.get()->getSourceRange();
6129
6130       // If the destination type is an incomplete array type, update the
6131       // type accordingly.
6132       if (ResultType) {
6133         if (const IncompleteArrayType *IncompleteDest
6134                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
6135           if (const ConstantArrayType *ConstantSource
6136                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
6137             *ResultType = S.Context.getConstantArrayType(
6138                                              IncompleteDest->getElementType(),
6139                                              ConstantSource->getSize(),
6140                                              ArrayType::Normal, 0);
6141           }
6142         }
6143       }
6144       break;
6145
6146     case SK_ParenthesizedArrayInit:
6147       // Okay: we checked everything before creating this step. Note that
6148       // this is a GNU extension.
6149       S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6150         << CurInit.get()->getSourceRange();
6151       break;
6152
6153     case SK_PassByIndirectCopyRestore:
6154     case SK_PassByIndirectRestore:
6155       checkIndirectCopyRestoreSource(S, CurInit.get());
6156       CurInit = S.Owned(new (S.Context)
6157                         ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6158                                 Step->Kind == SK_PassByIndirectCopyRestore));
6159       break;
6160
6161     case SK_ProduceObjCObject:
6162       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
6163                                                  CK_ARCProduceObject,
6164                                                  CurInit.take(), 0, VK_RValue));
6165       break;
6166
6167     case SK_StdInitializerList: {
6168       S.Diag(CurInit.get()->getExprLoc(),
6169              diag::warn_cxx98_compat_initializer_list_init)
6170         << CurInit.get()->getSourceRange();
6171
6172       // Maybe lifetime-extend the array temporary's subobjects to match the
6173       // entity's lifetime.
6174       const ValueDecl *ExtendingDecl =
6175           getDeclForTemporaryLifetimeExtension(Entity);
6176       if (ExtendingDecl) {
6177         performLifetimeExtension(CurInit.get(), ExtendingDecl);
6178         warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
6179       }
6180
6181       // Materialize the temporary into memory.
6182       MaterializeTemporaryExpr *MTE = new (S.Context)
6183           MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6184                                    /*lvalue reference*/ false, ExtendingDecl);
6185
6186       // Wrap it in a construction of a std::initializer_list<T>.
6187       CurInit = S.Owned(
6188           new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6189
6190       // Bind the result, in case the library has given initializer_list a
6191       // non-trivial destructor.
6192       if (shouldBindAsTemporary(Entity))
6193         CurInit = S.MaybeBindToTemporary(CurInit.take());
6194       break;
6195     }
6196
6197     case SK_OCLSamplerInit: {
6198       assert(Step->Type->isSamplerT() && 
6199              "Sampler initialization on non sampler type.");
6200
6201       QualType SourceType = CurInit.get()->getType();
6202
6203       if (Entity.isParameterKind()) {
6204         if (!SourceType->isSamplerT())
6205           S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6206             << SourceType;
6207       } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
6208         llvm_unreachable("Invalid EntityKind!");
6209       }
6210
6211       break;
6212     }
6213     case SK_OCLZeroEvent: {
6214       assert(Step->Type->isEventT() && 
6215              "Event initialization on non event type.");
6216
6217       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6218                                     CK_ZeroToOCLEvent,
6219                                     CurInit.get()->getValueKind());
6220       break;
6221     }
6222     }
6223   }
6224
6225   // Diagnose non-fatal problems with the completed initialization.
6226   if (Entity.getKind() == InitializedEntity::EK_Member &&
6227       cast<FieldDecl>(Entity.getDecl())->isBitField())
6228     S.CheckBitFieldInitialization(Kind.getLocation(),
6229                                   cast<FieldDecl>(Entity.getDecl()),
6230                                   CurInit.get());
6231
6232   return CurInit;
6233 }
6234
6235 /// Somewhere within T there is an uninitialized reference subobject.
6236 /// Dig it out and diagnose it.
6237 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6238                                            QualType T) {
6239   if (T->isReferenceType()) {
6240     S.Diag(Loc, diag::err_reference_without_init)
6241       << T.getNonReferenceType();
6242     return true;
6243   }
6244
6245   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6246   if (!RD || !RD->hasUninitializedReferenceMember())
6247     return false;
6248
6249   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6250                                      FE = RD->field_end(); FI != FE; ++FI) {
6251     if (FI->isUnnamedBitfield())
6252       continue;
6253
6254     if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6255       S.Diag(Loc, diag::note_value_initialization_here) << RD;
6256       return true;
6257     }
6258   }
6259
6260   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6261                                           BE = RD->bases_end();
6262        BI != BE; ++BI) {
6263     if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6264       S.Diag(Loc, diag::note_value_initialization_here) << RD;
6265       return true;
6266     }
6267   }
6268
6269   return false;
6270 }
6271
6272
6273 //===----------------------------------------------------------------------===//
6274 // Diagnose initialization failures
6275 //===----------------------------------------------------------------------===//
6276
6277 /// Emit notes associated with an initialization that failed due to a
6278 /// "simple" conversion failure.
6279 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6280                                    Expr *op) {
6281   QualType destType = entity.getType();
6282   if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6283       op->getType()->isObjCObjectPointerType()) {
6284
6285     // Emit a possible note about the conversion failing because the
6286     // operand is a message send with a related result type.
6287     S.EmitRelatedResultTypeNote(op);
6288
6289     // Emit a possible note about a return failing because we're
6290     // expecting a related result type.
6291     if (entity.getKind() == InitializedEntity::EK_Result)
6292       S.EmitRelatedResultTypeNoteForReturn(destType);
6293   }
6294 }
6295
6296 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6297                              InitListExpr *InitList) {
6298   QualType DestType = Entity.getType();
6299
6300   QualType E;
6301   if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6302     QualType ArrayType = S.Context.getConstantArrayType(
6303         E.withConst(),
6304         llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6305                     InitList->getNumInits()),
6306         clang::ArrayType::Normal, 0);
6307     InitializedEntity HiddenArray =
6308         InitializedEntity::InitializeTemporary(ArrayType);
6309     return diagnoseListInit(S, HiddenArray, InitList);
6310   }
6311
6312   InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6313                                    /*VerifyOnly=*/false);
6314   assert(DiagnoseInitList.HadError() &&
6315          "Inconsistent init list check result.");
6316 }
6317
6318 bool InitializationSequence::Diagnose(Sema &S,
6319                                       const InitializedEntity &Entity,
6320                                       const InitializationKind &Kind,
6321                                       ArrayRef<Expr *> Args) {
6322   if (!Failed())
6323     return false;
6324
6325   QualType DestType = Entity.getType();
6326   switch (Failure) {
6327   case FK_TooManyInitsForReference:
6328     // FIXME: Customize for the initialized entity?
6329     if (Args.empty()) {
6330       // Dig out the reference subobject which is uninitialized and diagnose it.
6331       // If this is value-initialization, this could be nested some way within
6332       // the target type.
6333       assert(Kind.getKind() == InitializationKind::IK_Value ||
6334              DestType->isReferenceType());
6335       bool Diagnosed =
6336         DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6337       assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6338       (void)Diagnosed;
6339     } else  // FIXME: diagnostic below could be better!
6340       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
6341         << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
6342     break;
6343
6344   case FK_ArrayNeedsInitList:
6345     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
6346     break;
6347   case FK_ArrayNeedsInitListOrStringLiteral:
6348     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6349     break;
6350   case FK_ArrayNeedsInitListOrWideStringLiteral:
6351     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6352     break;
6353   case FK_NarrowStringIntoWideCharArray:
6354     S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6355     break;
6356   case FK_WideStringIntoCharArray:
6357     S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6358     break;
6359   case FK_IncompatWideStringIntoWideChar:
6360     S.Diag(Kind.getLocation(),
6361            diag::err_array_init_incompat_wide_string_into_wchar);
6362     break;
6363   case FK_ArrayTypeMismatch:
6364   case FK_NonConstantArrayInit:
6365     S.Diag(Kind.getLocation(),
6366            (Failure == FK_ArrayTypeMismatch
6367               ? diag::err_array_init_different_type
6368               : diag::err_array_init_non_constant_array))
6369       << DestType.getNonReferenceType()
6370       << Args[0]->getType()
6371       << Args[0]->getSourceRange();
6372     break;
6373
6374   case FK_VariableLengthArrayHasInitializer:
6375     S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6376       << Args[0]->getSourceRange();
6377     break;
6378
6379   case FK_AddressOfOverloadFailed: {
6380     DeclAccessPair Found;
6381     S.ResolveAddressOfOverloadedFunction(Args[0],
6382                                          DestType.getNonReferenceType(),
6383                                          true,
6384                                          Found);
6385     break;
6386   }
6387
6388   case FK_ReferenceInitOverloadFailed:
6389   case FK_UserConversionOverloadFailed:
6390     switch (FailedOverloadResult) {
6391     case OR_Ambiguous:
6392       if (Failure == FK_UserConversionOverloadFailed)
6393         S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6394           << Args[0]->getType() << DestType
6395           << Args[0]->getSourceRange();
6396       else
6397         S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6398           << DestType << Args[0]->getType()
6399           << Args[0]->getSourceRange();
6400
6401       FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6402       break;
6403
6404     case OR_No_Viable_Function:
6405       if (!S.RequireCompleteType(Kind.getLocation(),
6406                                  DestType.getNonReferenceType(),
6407                           diag::err_typecheck_nonviable_condition_incomplete,
6408                                Args[0]->getType(), Args[0]->getSourceRange()))
6409         S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6410           << Args[0]->getType() << Args[0]->getSourceRange()
6411           << DestType.getNonReferenceType();
6412
6413       FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6414       break;
6415
6416     case OR_Deleted: {
6417       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6418         << Args[0]->getType() << DestType.getNonReferenceType()
6419         << Args[0]->getSourceRange();
6420       OverloadCandidateSet::iterator Best;
6421       OverloadingResult Ovl
6422         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6423                                                 true);
6424       if (Ovl == OR_Deleted) {
6425         S.NoteDeletedFunction(Best->Function);
6426       } else {
6427         llvm_unreachable("Inconsistent overload resolution?");
6428       }
6429       break;
6430     }
6431
6432     case OR_Success:
6433       llvm_unreachable("Conversion did not fail!");
6434     }
6435     break;
6436
6437   case FK_NonConstLValueReferenceBindingToTemporary:
6438     if (isa<InitListExpr>(Args[0])) {
6439       S.Diag(Kind.getLocation(),
6440              diag::err_lvalue_reference_bind_to_initlist)
6441       << DestType.getNonReferenceType().isVolatileQualified()
6442       << DestType.getNonReferenceType()
6443       << Args[0]->getSourceRange();
6444       break;
6445     }
6446     // Intentional fallthrough
6447
6448   case FK_NonConstLValueReferenceBindingToUnrelated:
6449     S.Diag(Kind.getLocation(),
6450            Failure == FK_NonConstLValueReferenceBindingToTemporary
6451              ? diag::err_lvalue_reference_bind_to_temporary
6452              : diag::err_lvalue_reference_bind_to_unrelated)
6453       << DestType.getNonReferenceType().isVolatileQualified()
6454       << DestType.getNonReferenceType()
6455       << Args[0]->getType()
6456       << Args[0]->getSourceRange();
6457     break;
6458
6459   case FK_RValueReferenceBindingToLValue:
6460     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
6461       << DestType.getNonReferenceType() << Args[0]->getType()
6462       << Args[0]->getSourceRange();
6463     break;
6464
6465   case FK_ReferenceInitDropsQualifiers:
6466     S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6467       << DestType.getNonReferenceType()
6468       << Args[0]->getType()
6469       << Args[0]->getSourceRange();
6470     break;
6471
6472   case FK_ReferenceInitFailed:
6473     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6474       << DestType.getNonReferenceType()
6475       << Args[0]->isLValue()
6476       << Args[0]->getType()
6477       << Args[0]->getSourceRange();
6478     emitBadConversionNotes(S, Entity, Args[0]);
6479     break;
6480
6481   case FK_ConversionFailed: {
6482     QualType FromType = Args[0]->getType();
6483     PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
6484       << (int)Entity.getKind()
6485       << DestType
6486       << Args[0]->isLValue()
6487       << FromType
6488       << Args[0]->getSourceRange();
6489     S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6490     S.Diag(Kind.getLocation(), PDiag);
6491     emitBadConversionNotes(S, Entity, Args[0]);
6492     break;
6493   }
6494
6495   case FK_ConversionFromPropertyFailed:
6496     // No-op. This error has already been reported.
6497     break;
6498
6499   case FK_TooManyInitsForScalar: {
6500     SourceRange R;
6501
6502     if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
6503       R = SourceRange(InitList->getInit(0)->getLocEnd(),
6504                       InitList->getLocEnd());
6505     else
6506       R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
6507
6508     R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6509     if (Kind.isCStyleOrFunctionalCast())
6510       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6511         << R;
6512     else
6513       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6514         << /*scalar=*/2 << R;
6515     break;
6516   }
6517
6518   case FK_ReferenceBindingToInitList:
6519     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6520       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6521     break;
6522
6523   case FK_InitListBadDestinationType:
6524     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6525       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6526     break;
6527
6528   case FK_ListConstructorOverloadFailed:
6529   case FK_ConstructorOverloadFailed: {
6530     SourceRange ArgsRange;
6531     if (Args.size())
6532       ArgsRange = SourceRange(Args.front()->getLocStart(),
6533                               Args.back()->getLocEnd());
6534
6535     if (Failure == FK_ListConstructorOverloadFailed) {
6536       assert(Args.size() == 1 && "List construction from other than 1 argument.");
6537       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6538       Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
6539     }
6540
6541     // FIXME: Using "DestType" for the entity we're printing is probably
6542     // bad.
6543     switch (FailedOverloadResult) {
6544       case OR_Ambiguous:
6545         S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6546           << DestType << ArgsRange;
6547         FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6548         break;
6549
6550       case OR_No_Viable_Function:
6551         if (Kind.getKind() == InitializationKind::IK_Default &&
6552             (Entity.getKind() == InitializedEntity::EK_Base ||
6553              Entity.getKind() == InitializedEntity::EK_Member) &&
6554             isa<CXXConstructorDecl>(S.CurContext)) {
6555           // This is implicit default initialization of a member or
6556           // base within a constructor. If no viable function was
6557           // found, notify the user that she needs to explicitly
6558           // initialize this base/member.
6559           CXXConstructorDecl *Constructor
6560             = cast<CXXConstructorDecl>(S.CurContext);
6561           if (Entity.getKind() == InitializedEntity::EK_Base) {
6562             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6563               << (Constructor->getInheritedConstructor() ? 2 :
6564                   Constructor->isImplicit() ? 1 : 0)
6565               << S.Context.getTypeDeclType(Constructor->getParent())
6566               << /*base=*/0
6567               << Entity.getType();
6568
6569             RecordDecl *BaseDecl
6570               = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6571                                                                   ->getDecl();
6572             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6573               << S.Context.getTagDeclType(BaseDecl);
6574           } else {
6575             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6576               << (Constructor->getInheritedConstructor() ? 2 :
6577                   Constructor->isImplicit() ? 1 : 0)
6578               << S.Context.getTypeDeclType(Constructor->getParent())
6579               << /*member=*/1
6580               << Entity.getName();
6581             S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6582
6583             if (const RecordType *Record
6584                                  = Entity.getType()->getAs<RecordType>())
6585               S.Diag(Record->getDecl()->getLocation(),
6586                      diag::note_previous_decl)
6587                 << S.Context.getTagDeclType(Record->getDecl());
6588           }
6589           break;
6590         }
6591
6592         S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6593           << DestType << ArgsRange;
6594         FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6595         break;
6596
6597       case OR_Deleted: {
6598         OverloadCandidateSet::iterator Best;
6599         OverloadingResult Ovl
6600           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6601         if (Ovl != OR_Deleted) {
6602           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6603             << true << DestType << ArgsRange;
6604           llvm_unreachable("Inconsistent overload resolution?");
6605           break;
6606         }
6607        
6608         // If this is a defaulted or implicitly-declared function, then
6609         // it was implicitly deleted. Make it clear that the deletion was
6610         // implicit.
6611         if (S.isImplicitlyDeleted(Best->Function))
6612           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
6613             << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
6614             << DestType << ArgsRange;
6615         else
6616           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6617             << true << DestType << ArgsRange;
6618
6619         S.NoteDeletedFunction(Best->Function);
6620         break;
6621       }
6622
6623       case OR_Success:
6624         llvm_unreachable("Conversion did not fail!");
6625     }
6626   }
6627   break;
6628
6629   case FK_DefaultInitOfConst:
6630     if (Entity.getKind() == InitializedEntity::EK_Member &&
6631         isa<CXXConstructorDecl>(S.CurContext)) {
6632       // This is implicit default-initialization of a const member in
6633       // a constructor. Complain that it needs to be explicitly
6634       // initialized.
6635       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6636       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
6637         << (Constructor->getInheritedConstructor() ? 2 :
6638             Constructor->isImplicit() ? 1 : 0)
6639         << S.Context.getTypeDeclType(Constructor->getParent())
6640         << /*const=*/1
6641         << Entity.getName();
6642       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6643         << Entity.getName();
6644     } else {
6645       S.Diag(Kind.getLocation(), diag::err_default_init_const)
6646         << DestType << (bool)DestType->getAs<RecordType>();
6647     }
6648     break;
6649
6650   case FK_Incomplete:
6651     S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
6652                           diag::err_init_incomplete_type);
6653     break;
6654
6655   case FK_ListInitializationFailed: {
6656     // Run the init list checker again to emit diagnostics.
6657     InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6658     diagnoseListInit(S, Entity, InitList);
6659     break;
6660   }
6661
6662   case FK_PlaceholderType: {
6663     // FIXME: Already diagnosed!
6664     break;
6665   }
6666
6667   case FK_ExplicitConstructor: {
6668     S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6669       << Args[0]->getSourceRange();
6670     OverloadCandidateSet::iterator Best;
6671     OverloadingResult Ovl
6672       = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6673     (void)Ovl;
6674     assert(Ovl == OR_Success && "Inconsistent overload resolution");
6675     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6676     S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6677     break;
6678   }
6679   }
6680
6681   PrintInitLocationNote(S, Entity);
6682   return true;
6683 }
6684
6685 void InitializationSequence::dump(raw_ostream &OS) const {
6686   switch (SequenceKind) {
6687   case FailedSequence: {
6688     OS << "Failed sequence: ";
6689     switch (Failure) {
6690     case FK_TooManyInitsForReference:
6691       OS << "too many initializers for reference";
6692       break;
6693
6694     case FK_ArrayNeedsInitList:
6695       OS << "array requires initializer list";
6696       break;
6697
6698     case FK_ArrayNeedsInitListOrStringLiteral:
6699       OS << "array requires initializer list or string literal";
6700       break;
6701
6702     case FK_ArrayNeedsInitListOrWideStringLiteral:
6703       OS << "array requires initializer list or wide string literal";
6704       break;
6705
6706     case FK_NarrowStringIntoWideCharArray:
6707       OS << "narrow string into wide char array";
6708       break;
6709
6710     case FK_WideStringIntoCharArray:
6711       OS << "wide string into char array";
6712       break;
6713
6714     case FK_IncompatWideStringIntoWideChar:
6715       OS << "incompatible wide string into wide char array";
6716       break;
6717
6718     case FK_ArrayTypeMismatch:
6719       OS << "array type mismatch";
6720       break;
6721
6722     case FK_NonConstantArrayInit:
6723       OS << "non-constant array initializer";
6724       break;
6725
6726     case FK_AddressOfOverloadFailed:
6727       OS << "address of overloaded function failed";
6728       break;
6729
6730     case FK_ReferenceInitOverloadFailed:
6731       OS << "overload resolution for reference initialization failed";
6732       break;
6733
6734     case FK_NonConstLValueReferenceBindingToTemporary:
6735       OS << "non-const lvalue reference bound to temporary";
6736       break;
6737
6738     case FK_NonConstLValueReferenceBindingToUnrelated:
6739       OS << "non-const lvalue reference bound to unrelated type";
6740       break;
6741
6742     case FK_RValueReferenceBindingToLValue:
6743       OS << "rvalue reference bound to an lvalue";
6744       break;
6745
6746     case FK_ReferenceInitDropsQualifiers:
6747       OS << "reference initialization drops qualifiers";
6748       break;
6749
6750     case FK_ReferenceInitFailed:
6751       OS << "reference initialization failed";
6752       break;
6753
6754     case FK_ConversionFailed:
6755       OS << "conversion failed";
6756       break;
6757
6758     case FK_ConversionFromPropertyFailed:
6759       OS << "conversion from property failed";
6760       break;
6761
6762     case FK_TooManyInitsForScalar:
6763       OS << "too many initializers for scalar";
6764       break;
6765
6766     case FK_ReferenceBindingToInitList:
6767       OS << "referencing binding to initializer list";
6768       break;
6769
6770     case FK_InitListBadDestinationType:
6771       OS << "initializer list for non-aggregate, non-scalar type";
6772       break;
6773
6774     case FK_UserConversionOverloadFailed:
6775       OS << "overloading failed for user-defined conversion";
6776       break;
6777
6778     case FK_ConstructorOverloadFailed:
6779       OS << "constructor overloading failed";
6780       break;
6781
6782     case FK_DefaultInitOfConst:
6783       OS << "default initialization of a const variable";
6784       break;
6785
6786     case FK_Incomplete:
6787       OS << "initialization of incomplete type";
6788       break;
6789
6790     case FK_ListInitializationFailed:
6791       OS << "list initialization checker failure";
6792       break;
6793
6794     case FK_VariableLengthArrayHasInitializer:
6795       OS << "variable length array has an initializer";
6796       break;
6797
6798     case FK_PlaceholderType:
6799       OS << "initializer expression isn't contextually valid";
6800       break;
6801
6802     case FK_ListConstructorOverloadFailed:
6803       OS << "list constructor overloading failed";
6804       break;
6805
6806     case FK_ExplicitConstructor:
6807       OS << "list copy initialization chose explicit constructor";
6808       break;
6809     }
6810     OS << '\n';
6811     return;
6812   }
6813
6814   case DependentSequence:
6815     OS << "Dependent sequence\n";
6816     return;
6817
6818   case NormalSequence:
6819     OS << "Normal sequence: ";
6820     break;
6821   }
6822
6823   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6824     if (S != step_begin()) {
6825       OS << " -> ";
6826     }
6827
6828     switch (S->Kind) {
6829     case SK_ResolveAddressOfOverloadedFunction:
6830       OS << "resolve address of overloaded function";
6831       break;
6832
6833     case SK_CastDerivedToBaseRValue:
6834       OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6835       break;
6836
6837     case SK_CastDerivedToBaseXValue:
6838       OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6839       break;
6840
6841     case SK_CastDerivedToBaseLValue:
6842       OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6843       break;
6844
6845     case SK_BindReference:
6846       OS << "bind reference to lvalue";
6847       break;
6848
6849     case SK_BindReferenceToTemporary:
6850       OS << "bind reference to a temporary";
6851       break;
6852
6853     case SK_ExtraneousCopyToTemporary:
6854       OS << "extraneous C++03 copy to temporary";
6855       break;
6856
6857     case SK_UserConversion:
6858       OS << "user-defined conversion via " << *S->Function.Function;
6859       break;
6860
6861     case SK_QualificationConversionRValue:
6862       OS << "qualification conversion (rvalue)";
6863       break;
6864
6865     case SK_QualificationConversionXValue:
6866       OS << "qualification conversion (xvalue)";
6867       break;
6868
6869     case SK_QualificationConversionLValue:
6870       OS << "qualification conversion (lvalue)";
6871       break;
6872
6873     case SK_LValueToRValue:
6874       OS << "load (lvalue to rvalue)";
6875       break;
6876
6877     case SK_ConversionSequence:
6878       OS << "implicit conversion sequence (";
6879       S->ICS->dump(); // FIXME: use OS
6880       OS << ")";
6881       break;
6882
6883     case SK_ConversionSequenceNoNarrowing:
6884       OS << "implicit conversion sequence with narrowing prohibited (";
6885       S->ICS->dump(); // FIXME: use OS
6886       OS << ")";
6887       break;
6888
6889     case SK_ListInitialization:
6890       OS << "list aggregate initialization";
6891       break;
6892
6893     case SK_ListConstructorCall:
6894       OS << "list initialization via constructor";
6895       break;
6896
6897     case SK_UnwrapInitList:
6898       OS << "unwrap reference initializer list";
6899       break;
6900
6901     case SK_RewrapInitList:
6902       OS << "rewrap reference initializer list";
6903       break;
6904
6905     case SK_ConstructorInitialization:
6906       OS << "constructor initialization";
6907       break;
6908
6909     case SK_ZeroInitialization:
6910       OS << "zero initialization";
6911       break;
6912
6913     case SK_CAssignment:
6914       OS << "C assignment";
6915       break;
6916
6917     case SK_StringInit:
6918       OS << "string initialization";
6919       break;
6920
6921     case SK_ObjCObjectConversion:
6922       OS << "Objective-C object conversion";
6923       break;
6924
6925     case SK_ArrayInit:
6926       OS << "array initialization";
6927       break;
6928
6929     case SK_ParenthesizedArrayInit:
6930       OS << "parenthesized array initialization";
6931       break;
6932
6933     case SK_PassByIndirectCopyRestore:
6934       OS << "pass by indirect copy and restore";
6935       break;
6936
6937     case SK_PassByIndirectRestore:
6938       OS << "pass by indirect restore";
6939       break;
6940
6941     case SK_ProduceObjCObject:
6942       OS << "Objective-C object retension";
6943       break;
6944
6945     case SK_StdInitializerList:
6946       OS << "std::initializer_list from initializer list";
6947       break;
6948
6949     case SK_OCLSamplerInit:
6950       OS << "OpenCL sampler_t from integer constant";
6951       break;
6952
6953     case SK_OCLZeroEvent:
6954       OS << "OpenCL event_t from zero";
6955       break;
6956     }
6957
6958     OS << " [" << S->Type.getAsString() << ']';
6959   }
6960
6961   OS << '\n';
6962 }
6963
6964 void InitializationSequence::dump() const {
6965   dump(llvm::errs());
6966 }
6967
6968 static void DiagnoseNarrowingInInitList(Sema &S,
6969                                         const ImplicitConversionSequence &ICS,
6970                                         QualType PreNarrowingType,
6971                                         QualType EntityType,
6972                                         const Expr *PostInit) {
6973   const StandardConversionSequence *SCS = 0;
6974   switch (ICS.getKind()) {
6975   case ImplicitConversionSequence::StandardConversion:
6976     SCS = &ICS.Standard;
6977     break;
6978   case ImplicitConversionSequence::UserDefinedConversion:
6979     SCS = &ICS.UserDefined.After;
6980     break;
6981   case ImplicitConversionSequence::AmbiguousConversion:
6982   case ImplicitConversionSequence::EllipsisConversion:
6983   case ImplicitConversionSequence::BadConversion:
6984     return;
6985   }
6986
6987   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
6988   APValue ConstantValue;
6989   QualType ConstantType;
6990   switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
6991                                 ConstantType)) {
6992   case NK_Not_Narrowing:
6993     // No narrowing occurred.
6994     return;
6995
6996   case NK_Type_Narrowing:
6997     // This was a floating-to-integer conversion, which is always considered a
6998     // narrowing conversion even if the value is a constant and can be
6999     // represented exactly as an integer.
7000     S.Diag(PostInit->getLocStart(),
7001            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7002                ? diag::warn_init_list_type_narrowing
7003                : diag::ext_init_list_type_narrowing)
7004       << PostInit->getSourceRange()
7005       << PreNarrowingType.getLocalUnqualifiedType()
7006       << EntityType.getLocalUnqualifiedType();
7007     break;
7008
7009   case NK_Constant_Narrowing:
7010     // A constant value was narrowed.
7011     S.Diag(PostInit->getLocStart(),
7012            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7013                ? diag::warn_init_list_constant_narrowing
7014                : diag::ext_init_list_constant_narrowing)
7015       << PostInit->getSourceRange()
7016       << ConstantValue.getAsString(S.getASTContext(), ConstantType)
7017       << EntityType.getLocalUnqualifiedType();
7018     break;
7019
7020   case NK_Variable_Narrowing:
7021     // A variable's value may have been narrowed.
7022     S.Diag(PostInit->getLocStart(),
7023            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7024                ? diag::warn_init_list_variable_narrowing
7025                : diag::ext_init_list_variable_narrowing)
7026       << PostInit->getSourceRange()
7027       << PreNarrowingType.getLocalUnqualifiedType()
7028       << EntityType.getLocalUnqualifiedType();
7029     break;
7030   }
7031
7032   SmallString<128> StaticCast;
7033   llvm::raw_svector_ostream OS(StaticCast);
7034   OS << "static_cast<";
7035   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7036     // It's important to use the typedef's name if there is one so that the
7037     // fixit doesn't break code using types like int64_t.
7038     //
7039     // FIXME: This will break if the typedef requires qualification.  But
7040     // getQualifiedNameAsString() includes non-machine-parsable components.
7041     OS << *TT->getDecl();
7042   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
7043     OS << BT->getName(S.getLangOpts());
7044   else {
7045     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
7046     // with a broken cast.
7047     return;
7048   }
7049   OS << ">(";
7050   S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
7051     << PostInit->getSourceRange()
7052     << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7053     << FixItHint::CreateInsertion(
7054       S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
7055 }
7056
7057 //===----------------------------------------------------------------------===//
7058 // Initialization helper functions
7059 //===----------------------------------------------------------------------===//
7060 bool
7061 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7062                                    ExprResult Init) {
7063   if (Init.isInvalid())
7064     return false;
7065
7066   Expr *InitE = Init.get();
7067   assert(InitE && "No initialization expression");
7068
7069   InitializationKind Kind
7070     = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
7071   InitializationSequence Seq(*this, Entity, Kind, InitE);
7072   return !Seq.Failed();
7073 }
7074
7075 ExprResult
7076 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7077                                 SourceLocation EqualLoc,
7078                                 ExprResult Init,
7079                                 bool TopLevelOfInitList,
7080                                 bool AllowExplicit) {
7081   if (Init.isInvalid())
7082     return ExprError();
7083
7084   Expr *InitE = Init.get();
7085   assert(InitE && "No initialization expression?");
7086
7087   if (EqualLoc.isInvalid())
7088     EqualLoc = InitE->getLocStart();
7089
7090   InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
7091                                                            EqualLoc,
7092                                                            AllowExplicit);
7093   InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
7094   Init.release();
7095
7096   ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
7097
7098   return Result;
7099 }