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