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;
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 DeclarationName(Capture.VarID);
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     OS << DeclarationName(Capture.VarID);
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                                            /*AllowObjCConversionOnExplicit=*/
3527                                              false);
3528         else
3529           S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
3530                                    Initializer, DestType, CandidateSet,
3531                                    /*AllowObjCConversionOnExplicit=*/false);
3532       }
3533     }
3534   }
3535   if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3536     return OR_No_Viable_Function;
3537 
3538   SourceLocation DeclLoc = Initializer->getLocStart();
3539 
3540   // Perform overload resolution. If it fails, return the failed result.
3541   OverloadCandidateSet::iterator Best;
3542   if (OverloadingResult Result
3543         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
3544     return Result;
3545 
3546   FunctionDecl *Function = Best->Function;
3547   // This is the overload that will be used for this initialization step if we
3548   // use this initialization. Mark it as referenced.
3549   Function->setReferenced();
3550 
3551   // Compute the returned type of the conversion.
3552   if (isa<CXXConversionDecl>(Function))
3553     T2 = Function->getReturnType();
3554   else
3555     T2 = cv1T1;
3556 
3557   // Add the user-defined conversion step.
3558   bool HadMultipleCandidates = (CandidateSet.size() > 1);
3559   Sequence.AddUserConversionStep(Function, Best->FoundDecl,
3560                                  T2.getNonLValueExprType(S.Context),
3561                                  HadMultipleCandidates);
3562 
3563   // Determine whether we need to perform derived-to-base or
3564   // cv-qualification adjustments.
3565   ExprValueKind VK = VK_RValue;
3566   if (T2->isLValueReferenceType())
3567     VK = VK_LValue;
3568   else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
3569     VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
3570 
3571   bool NewDerivedToBase = false;
3572   bool NewObjCConversion = false;
3573   bool NewObjCLifetimeConversion = false;
3574   Sema::ReferenceCompareResult NewRefRelationship
3575     = S.CompareReferenceRelationship(DeclLoc, T1,
3576                                      T2.getNonLValueExprType(S.Context),
3577                                      NewDerivedToBase, NewObjCConversion,
3578                                      NewObjCLifetimeConversion);
3579   if (NewRefRelationship == Sema::Ref_Incompatible) {
3580     // If the type we've converted to is not reference-related to the
3581     // type we're looking for, then there is another conversion step
3582     // we need to perform to produce a temporary of the right type
3583     // that we'll be binding to.
3584     ImplicitConversionSequence ICS;
3585     ICS.setStandard();
3586     ICS.Standard = Best->FinalConversion;
3587     T2 = ICS.Standard.getToType(2);
3588     Sequence.AddConversionSequenceStep(ICS, T2);
3589   } else if (NewDerivedToBase)
3590     Sequence.AddDerivedToBaseCastStep(
3591                                 S.Context.getQualifiedType(T1,
3592                                   T2.getNonReferenceType().getQualifiers()),
3593                                       VK);
3594   else if (NewObjCConversion)
3595     Sequence.AddObjCObjectConversionStep(
3596                                 S.Context.getQualifiedType(T1,
3597                                   T2.getNonReferenceType().getQualifiers()));
3598 
3599   if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
3600     Sequence.AddQualificationConversionStep(cv1T1, VK);
3601 
3602   Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3603   return OR_Success;
3604 }
3605 
3606 static void CheckCXX98CompatAccessibleCopy(Sema &S,
3607                                            const InitializedEntity &Entity,
3608                                            Expr *CurInitExpr);
3609 
3610 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3611 static void TryReferenceInitialization(Sema &S,
3612                                        const InitializedEntity &Entity,
3613                                        const InitializationKind &Kind,
3614                                        Expr *Initializer,
3615                                        InitializationSequence &Sequence) {
3616   QualType DestType = Entity.getType();
3617   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3618   Qualifiers T1Quals;
3619   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3620   QualType cv2T2 = Initializer->getType();
3621   Qualifiers T2Quals;
3622   QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3623 
3624   // If the initializer is the address of an overloaded function, try
3625   // to resolve the overloaded function. If all goes well, T2 is the
3626   // type of the resulting function.
3627   if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3628                                                    T1, Sequence))
3629     return;
3630 
3631   // Delegate everything else to a subfunction.
3632   TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3633                                  T1Quals, cv2T2, T2, T2Quals, Sequence);
3634 }
3635 
3636 /// Converts the target of reference initialization so that it has the
3637 /// appropriate qualifiers and value kind.
3638 ///
3639 /// In this case, 'x' is an 'int' lvalue, but it needs to be 'const int'.
3640 /// \code
3641 ///   int x;
3642 ///   const int &r = x;
3643 /// \endcode
3644 ///
3645 /// In this case the reference is binding to a bitfield lvalue, which isn't
3646 /// valid. Perform a load to create a lifetime-extended temporary instead.
3647 /// \code
3648 ///   const int &r = someStruct.bitfield;
3649 /// \endcode
3650 static ExprValueKind
3651 convertQualifiersAndValueKindIfNecessary(Sema &S,
3652                                          InitializationSequence &Sequence,
3653                                          Expr *Initializer,
3654                                          QualType cv1T1,
3655                                          Qualifiers T1Quals,
3656                                          Qualifiers T2Quals,
3657                                          bool IsLValueRef) {
3658   bool IsNonAddressableType = Initializer->refersToBitField() ||
3659                               Initializer->refersToVectorElement();
3660 
3661   if (IsNonAddressableType) {
3662     // C++11 [dcl.init.ref]p5: [...] Otherwise, the reference shall be an
3663     // lvalue reference to a non-volatile const type, or the reference shall be
3664     // an rvalue reference.
3665     //
3666     // If not, we can't make a temporary and bind to that. Give up and allow the
3667     // error to be diagnosed later.
3668     if (IsLValueRef && (!T1Quals.hasConst() || T1Quals.hasVolatile())) {
3669       assert(Initializer->isGLValue());
3670       return Initializer->getValueKind();
3671     }
3672 
3673     // Force a load so we can materialize a temporary.
3674     Sequence.AddLValueToRValueStep(cv1T1.getUnqualifiedType());
3675     return VK_RValue;
3676   }
3677 
3678   if (T1Quals != T2Quals) {
3679     Sequence.AddQualificationConversionStep(cv1T1,
3680                                             Initializer->getValueKind());
3681   }
3682 
3683   return Initializer->getValueKind();
3684 }
3685 
3686 
3687 /// \brief Reference initialization without resolving overloaded functions.
3688 static void TryReferenceInitializationCore(Sema &S,
3689                                            const InitializedEntity &Entity,
3690                                            const InitializationKind &Kind,
3691                                            Expr *Initializer,
3692                                            QualType cv1T1, QualType T1,
3693                                            Qualifiers T1Quals,
3694                                            QualType cv2T2, QualType T2,
3695                                            Qualifiers T2Quals,
3696                                            InitializationSequence &Sequence) {
3697   QualType DestType = Entity.getType();
3698   SourceLocation DeclLoc = Initializer->getLocStart();
3699   // Compute some basic properties of the types and the initializer.
3700   bool isLValueRef = DestType->isLValueReferenceType();
3701   bool isRValueRef = !isLValueRef;
3702   bool DerivedToBase = false;
3703   bool ObjCConversion = false;
3704   bool ObjCLifetimeConversion = false;
3705   Expr::Classification InitCategory = Initializer->Classify(S.Context);
3706   Sema::ReferenceCompareResult RefRelationship
3707     = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
3708                                      ObjCConversion, ObjCLifetimeConversion);
3709 
3710   // C++0x [dcl.init.ref]p5:
3711   //   A reference to type "cv1 T1" is initialized by an expression of type
3712   //   "cv2 T2" as follows:
3713   //
3714   //     - If the reference is an lvalue reference and the initializer
3715   //       expression
3716   // Note the analogous bullet points for rvalue refs to functions. Because
3717   // there are no function rvalues in C++, rvalue refs to functions are treated
3718   // like lvalue refs.
3719   OverloadingResult ConvOvlResult = OR_Success;
3720   bool T1Function = T1->isFunctionType();
3721   if (isLValueRef || T1Function) {
3722     if (InitCategory.isLValue() &&
3723         (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3724          (Kind.isCStyleOrFunctionalCast() &&
3725           RefRelationship == Sema::Ref_Related))) {
3726       //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
3727       //     reference-compatible with "cv2 T2," or
3728       //
3729       // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
3730       // bit-field when we're determining whether the reference initialization
3731       // can occur. However, we do pay attention to whether it is a bit-field
3732       // to decide whether we're actually binding to a temporary created from
3733       // the bit-field.
3734       if (DerivedToBase)
3735         Sequence.AddDerivedToBaseCastStep(
3736                          S.Context.getQualifiedType(T1, T2Quals),
3737                          VK_LValue);
3738       else if (ObjCConversion)
3739         Sequence.AddObjCObjectConversionStep(
3740                                      S.Context.getQualifiedType(T1, T2Quals));
3741 
3742       ExprValueKind ValueKind =
3743         convertQualifiersAndValueKindIfNecessary(S, Sequence, Initializer,
3744                                                  cv1T1, T1Quals, T2Quals,
3745                                                  isLValueRef);
3746       Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3747       return;
3748     }
3749 
3750     //     - has a class type (i.e., T2 is a class type), where T1 is not
3751     //       reference-related to T2, and can be implicitly converted to an
3752     //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3753     //       with "cv3 T3" (this conversion is selected by enumerating the
3754     //       applicable conversion functions (13.3.1.6) and choosing the best
3755     //       one through overload resolution (13.3)),
3756     // If we have an rvalue ref to function type here, the rhs must be
3757     // an rvalue. DR1287 removed the "implicitly" here.
3758     if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3759         (isLValueRef || InitCategory.isRValue())) {
3760       ConvOvlResult = TryRefInitWithConversionFunction(
3761           S, Entity, Kind, Initializer, /*AllowRValues*/isRValueRef, Sequence);
3762       if (ConvOvlResult == OR_Success)
3763         return;
3764       if (ConvOvlResult != OR_No_Viable_Function)
3765         Sequence.SetOverloadFailure(
3766             InitializationSequence::FK_ReferenceInitOverloadFailed,
3767             ConvOvlResult);
3768     }
3769   }
3770 
3771   //     - Otherwise, the reference shall be an lvalue reference to a
3772   //       non-volatile const type (i.e., cv1 shall be const), or the reference
3773   //       shall be an rvalue reference.
3774   if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
3775     if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3776       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3777     else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3778       Sequence.SetOverloadFailure(
3779                         InitializationSequence::FK_ReferenceInitOverloadFailed,
3780                                   ConvOvlResult);
3781     else
3782       Sequence.SetFailed(InitCategory.isLValue()
3783         ? (RefRelationship == Sema::Ref_Related
3784              ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3785              : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3786         : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3787 
3788     return;
3789   }
3790 
3791   //    - If the initializer expression
3792   //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
3793   //        "cv1 T1" is reference-compatible with "cv2 T2"
3794   // Note: functions are handled below.
3795   if (!T1Function &&
3796       (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
3797        (Kind.isCStyleOrFunctionalCast() &&
3798         RefRelationship == Sema::Ref_Related)) &&
3799       (InitCategory.isXValue() ||
3800        (InitCategory.isPRValue() && T2->isRecordType()) ||
3801        (InitCategory.isPRValue() && T2->isArrayType()))) {
3802     ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3803     if (InitCategory.isPRValue() && T2->isRecordType()) {
3804       // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3805       // compiler the freedom to perform a copy here or bind to the
3806       // object, while C++0x requires that we bind directly to the
3807       // object. Hence, we always bind to the object without making an
3808       // extra copy. However, in C++03 requires that we check for the
3809       // presence of a suitable copy constructor:
3810       //
3811       //   The constructor that would be used to make the copy shall
3812       //   be callable whether or not the copy is actually done.
3813       if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt)
3814         Sequence.AddExtraneousCopyToTemporary(cv2T2);
3815       else if (S.getLangOpts().CPlusPlus11)
3816         CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
3817     }
3818 
3819     if (DerivedToBase)
3820       Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3821                                         ValueKind);
3822     else if (ObjCConversion)
3823       Sequence.AddObjCObjectConversionStep(
3824                                        S.Context.getQualifiedType(T1, T2Quals));
3825 
3826     ValueKind = convertQualifiersAndValueKindIfNecessary(S, Sequence,
3827                                                          Initializer, cv1T1,
3828                                                          T1Quals, T2Quals,
3829                                                          isLValueRef);
3830 
3831     Sequence.AddReferenceBindingStep(cv1T1, ValueKind == VK_RValue);
3832     return;
3833   }
3834 
3835   //       - has a class type (i.e., T2 is a class type), where T1 is not
3836   //         reference-related to T2, and can be implicitly converted to an
3837   //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
3838   //         where "cv1 T1" is reference-compatible with "cv3 T3",
3839   //
3840   // DR1287 removes the "implicitly" here.
3841   if (T2->isRecordType()) {
3842     if (RefRelationship == Sema::Ref_Incompatible) {
3843       ConvOvlResult = TryRefInitWithConversionFunction(
3844           S, Entity, Kind, Initializer, /*AllowRValues*/true, Sequence);
3845       if (ConvOvlResult)
3846         Sequence.SetOverloadFailure(
3847             InitializationSequence::FK_ReferenceInitOverloadFailed,
3848             ConvOvlResult);
3849 
3850       return;
3851     }
3852 
3853     if ((RefRelationship == Sema::Ref_Compatible ||
3854          RefRelationship == Sema::Ref_Compatible_With_Added_Qualification) &&
3855         isRValueRef && InitCategory.isLValue()) {
3856       Sequence.SetFailed(
3857         InitializationSequence::FK_RValueReferenceBindingToLValue);
3858       return;
3859     }
3860 
3861     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3862     return;
3863   }
3864 
3865   //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
3866   //        from the initializer expression using the rules for a non-reference
3867   //        copy-initialization (8.5). The reference is then bound to the
3868   //        temporary. [...]
3869 
3870   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3871 
3872   // FIXME: Why do we use an implicit conversion here rather than trying
3873   // copy-initialization?
3874   ImplicitConversionSequence ICS
3875     = S.TryImplicitConversion(Initializer, TempEntity.getType(),
3876                               /*SuppressUserConversions=*/false,
3877                               /*AllowExplicit=*/false,
3878                               /*FIXME:InOverloadResolution=*/false,
3879                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3880                               /*AllowObjCWritebackConversion=*/false);
3881 
3882   if (ICS.isBad()) {
3883     // FIXME: Use the conversion function set stored in ICS to turn
3884     // this into an overloading ambiguity diagnostic. However, we need
3885     // to keep that set as an OverloadCandidateSet rather than as some
3886     // other kind of set.
3887     if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3888       Sequence.SetOverloadFailure(
3889                         InitializationSequence::FK_ReferenceInitOverloadFailed,
3890                                   ConvOvlResult);
3891     else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3892       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3893     else
3894       Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
3895     return;
3896   } else {
3897     Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
3898   }
3899 
3900   //        [...] If T1 is reference-related to T2, cv1 must be the
3901   //        same cv-qualification as, or greater cv-qualification
3902   //        than, cv2; otherwise, the program is ill-formed.
3903   unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3904   unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
3905   if (RefRelationship == Sema::Ref_Related &&
3906       (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
3907     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3908     return;
3909   }
3910 
3911   //   [...] If T1 is reference-related to T2 and the reference is an rvalue
3912   //   reference, the initializer expression shall not be an lvalue.
3913   if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
3914       InitCategory.isLValue()) {
3915     Sequence.SetFailed(
3916                     InitializationSequence::FK_RValueReferenceBindingToLValue);
3917     return;
3918   }
3919 
3920   Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3921   return;
3922 }
3923 
3924 /// \brief Attempt character array initialization from a string literal
3925 /// (C++ [dcl.init.string], C99 6.7.8).
3926 static void TryStringLiteralInitialization(Sema &S,
3927                                            const InitializedEntity &Entity,
3928                                            const InitializationKind &Kind,
3929                                            Expr *Initializer,
3930                                        InitializationSequence &Sequence) {
3931   Sequence.AddStringInitStep(Entity.getType());
3932 }
3933 
3934 /// \brief Attempt value initialization (C++ [dcl.init]p7).
3935 static void TryValueInitialization(Sema &S,
3936                                    const InitializedEntity &Entity,
3937                                    const InitializationKind &Kind,
3938                                    InitializationSequence &Sequence,
3939                                    InitListExpr *InitList) {
3940   assert((!InitList || InitList->getNumInits() == 0) &&
3941          "Shouldn't use value-init for non-empty init lists");
3942 
3943   // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
3944   //
3945   //   To value-initialize an object of type T means:
3946   QualType T = Entity.getType();
3947 
3948   //     -- if T is an array type, then each element is value-initialized;
3949   T = S.Context.getBaseElementType(T);
3950 
3951   if (const RecordType *RT = T->getAs<RecordType>()) {
3952     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3953       bool NeedZeroInitialization = true;
3954       if (!S.getLangOpts().CPlusPlus11) {
3955         // C++98:
3956         // -- if T is a class type (clause 9) with a user-declared constructor
3957         //    (12.1), then the default constructor for T is called (and the
3958         //    initialization is ill-formed if T has no accessible default
3959         //    constructor);
3960         if (ClassDecl->hasUserDeclaredConstructor())
3961           NeedZeroInitialization = false;
3962       } else {
3963         // C++11:
3964         // -- if T is a class type (clause 9) with either no default constructor
3965         //    (12.1 [class.ctor]) or a default constructor that is user-provided
3966         //    or deleted, then the object is default-initialized;
3967         CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
3968         if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
3969           NeedZeroInitialization = false;
3970       }
3971 
3972       // -- if T is a (possibly cv-qualified) non-union class type without a
3973       //    user-provided or deleted default constructor, then the object is
3974       //    zero-initialized and, if T has a non-trivial default constructor,
3975       //    default-initialized;
3976       // The 'non-union' here was removed by DR1502. The 'non-trivial default
3977       // constructor' part was removed by DR1507.
3978       if (NeedZeroInitialization)
3979         Sequence.AddZeroInitializationStep(Entity.getType());
3980 
3981       // C++03:
3982       // -- if T is a non-union class type without a user-declared constructor,
3983       //    then every non-static data member and base class component of T is
3984       //    value-initialized;
3985       // [...] A program that calls for [...] value-initialization of an
3986       // entity of reference type is ill-formed.
3987       //
3988       // C++11 doesn't need this handling, because value-initialization does not
3989       // occur recursively there, and the implicit default constructor is
3990       // defined as deleted in the problematic cases.
3991       if (!S.getLangOpts().CPlusPlus11 &&
3992           ClassDecl->hasUninitializedReferenceMember()) {
3993         Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference);
3994         return;
3995       }
3996 
3997       // If this is list-value-initialization, pass the empty init list on when
3998       // building the constructor call. This affects the semantics of a few
3999       // things (such as whether an explicit default constructor can be called).
4000       Expr *InitListAsExpr = InitList;
4001       MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0);
4002       bool InitListSyntax = InitList;
4003 
4004       return TryConstructorInitialization(S, Entity, Kind, Args, T, Sequence,
4005                                           InitListSyntax);
4006     }
4007   }
4008 
4009   Sequence.AddZeroInitializationStep(Entity.getType());
4010 }
4011 
4012 /// \brief Attempt default initialization (C++ [dcl.init]p6).
4013 static void TryDefaultInitialization(Sema &S,
4014                                      const InitializedEntity &Entity,
4015                                      const InitializationKind &Kind,
4016                                      InitializationSequence &Sequence) {
4017   assert(Kind.getKind() == InitializationKind::IK_Default);
4018 
4019   // C++ [dcl.init]p6:
4020   //   To default-initialize an object of type T means:
4021   //     - if T is an array type, each element is default-initialized;
4022   QualType DestType = S.Context.getBaseElementType(Entity.getType());
4023 
4024   //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
4025   //       constructor for T is called (and the initialization is ill-formed if
4026   //       T has no accessible default constructor);
4027   if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
4028     TryConstructorInitialization(S, Entity, Kind, None, DestType, Sequence);
4029     return;
4030   }
4031 
4032   //     - otherwise, no initialization is performed.
4033 
4034   //   If a program calls for the default initialization of an object of
4035   //   a const-qualified type T, T shall be a class type with a user-provided
4036   //   default constructor.
4037   if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
4038     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4039     return;
4040   }
4041 
4042   // If the destination type has a lifetime property, zero-initialize it.
4043   if (DestType.getQualifiers().hasObjCLifetime()) {
4044     Sequence.AddZeroInitializationStep(Entity.getType());
4045     return;
4046   }
4047 }
4048 
4049 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
4050 /// which enumerates all conversion functions and performs overload resolution
4051 /// to select the best.
4052 static void TryUserDefinedConversion(Sema &S,
4053                                      const InitializedEntity &Entity,
4054                                      const InitializationKind &Kind,
4055                                      Expr *Initializer,
4056                                      InitializationSequence &Sequence,
4057                                      bool TopLevelOfInitList) {
4058   QualType DestType = Entity.getType();
4059   assert(!DestType->isReferenceType() && "References are handled elsewhere");
4060   QualType SourceType = Initializer->getType();
4061   assert((DestType->isRecordType() || SourceType->isRecordType()) &&
4062          "Must have a class type to perform a user-defined conversion");
4063 
4064   // Build the candidate set directly in the initialization sequence
4065   // structure, so that it will persist if we fail.
4066   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4067   CandidateSet.clear();
4068 
4069   // Determine whether we are allowed to call explicit constructors or
4070   // explicit conversion operators.
4071   bool AllowExplicit = Kind.AllowExplicit();
4072 
4073   if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
4074     // The type we're converting to is a class type. Enumerate its constructors
4075     // to see if there is a suitable conversion.
4076     CXXRecordDecl *DestRecordDecl
4077       = cast<CXXRecordDecl>(DestRecordType->getDecl());
4078 
4079     // Try to complete the type we're converting to.
4080     if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
4081       DeclContext::lookup_result R = S.LookupConstructors(DestRecordDecl);
4082       // The container holding the constructors can under certain conditions
4083       // be changed while iterating. To be safe we copy the lookup results
4084       // to a new container.
4085       SmallVector<NamedDecl*, 8> CopyOfCon(R.begin(), R.end());
4086       for (SmallVectorImpl<NamedDecl *>::iterator
4087              Con = CopyOfCon.begin(), ConEnd = CopyOfCon.end();
4088            Con != ConEnd; ++Con) {
4089         NamedDecl *D = *Con;
4090         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
4091 
4092         // Find the constructor (which may be a template).
4093         CXXConstructorDecl *Constructor = 0;
4094         FunctionTemplateDecl *ConstructorTmpl
4095           = dyn_cast<FunctionTemplateDecl>(D);
4096         if (ConstructorTmpl)
4097           Constructor = cast<CXXConstructorDecl>(
4098                                            ConstructorTmpl->getTemplatedDecl());
4099         else
4100           Constructor = cast<CXXConstructorDecl>(D);
4101 
4102         if (!Constructor->isInvalidDecl() &&
4103             Constructor->isConvertingConstructor(AllowExplicit)) {
4104           if (ConstructorTmpl)
4105             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
4106                                            /*ExplicitArgs*/ 0,
4107                                            Initializer, CandidateSet,
4108                                            /*SuppressUserConversions=*/true);
4109           else
4110             S.AddOverloadCandidate(Constructor, FoundDecl,
4111                                    Initializer, CandidateSet,
4112                                    /*SuppressUserConversions=*/true);
4113         }
4114       }
4115     }
4116   }
4117 
4118   SourceLocation DeclLoc = Initializer->getLocStart();
4119 
4120   if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
4121     // The type we're converting from is a class type, enumerate its conversion
4122     // functions.
4123 
4124     // We can only enumerate the conversion functions for a complete type; if
4125     // the type isn't complete, simply skip this step.
4126     if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
4127       CXXRecordDecl *SourceRecordDecl
4128         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
4129 
4130       std::pair<CXXRecordDecl::conversion_iterator,
4131                 CXXRecordDecl::conversion_iterator>
4132         Conversions = SourceRecordDecl->getVisibleConversionFunctions();
4133       for (CXXRecordDecl::conversion_iterator
4134              I = Conversions.first, E = Conversions.second; I != E; ++I) {
4135         NamedDecl *D = *I;
4136         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4137         if (isa<UsingShadowDecl>(D))
4138           D = cast<UsingShadowDecl>(D)->getTargetDecl();
4139 
4140         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4141         CXXConversionDecl *Conv;
4142         if (ConvTemplate)
4143           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4144         else
4145           Conv = cast<CXXConversionDecl>(D);
4146 
4147         if (AllowExplicit || !Conv->isExplicit()) {
4148           if (ConvTemplate)
4149             S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
4150                                              ActingDC, Initializer, DestType,
4151                                              CandidateSet, AllowExplicit);
4152           else
4153             S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
4154                                      Initializer, DestType, CandidateSet,
4155                                      AllowExplicit);
4156         }
4157       }
4158     }
4159   }
4160 
4161   // Perform overload resolution. If it fails, return the failed result.
4162   OverloadCandidateSet::iterator Best;
4163   if (OverloadingResult Result
4164         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4165     Sequence.SetOverloadFailure(
4166                         InitializationSequence::FK_UserConversionOverloadFailed,
4167                                 Result);
4168     return;
4169   }
4170 
4171   FunctionDecl *Function = Best->Function;
4172   Function->setReferenced();
4173   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4174 
4175   if (isa<CXXConstructorDecl>(Function)) {
4176     // Add the user-defined conversion step. Any cv-qualification conversion is
4177     // subsumed by the initialization. Per DR5, the created temporary is of the
4178     // cv-unqualified type of the destination.
4179     Sequence.AddUserConversionStep(Function, Best->FoundDecl,
4180                                    DestType.getUnqualifiedType(),
4181                                    HadMultipleCandidates);
4182     return;
4183   }
4184 
4185   // Add the user-defined conversion step that calls the conversion function.
4186   QualType ConvType = Function->getCallResultType();
4187   if (ConvType->getAs<RecordType>()) {
4188     // If we're converting to a class type, there may be an copy of
4189     // the resulting temporary object (possible to create an object of
4190     // a base class type). That copy is not a separate conversion, so
4191     // we just make a note of the actual destination type (possibly a
4192     // base class of the type returned by the conversion function) and
4193     // let the user-defined conversion step handle the conversion.
4194     Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
4195                                    HadMultipleCandidates);
4196     return;
4197   }
4198 
4199   Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
4200                                  HadMultipleCandidates);
4201 
4202   // If the conversion following the call to the conversion function
4203   // is interesting, add it as a separate step.
4204   if (Best->FinalConversion.First || Best->FinalConversion.Second ||
4205       Best->FinalConversion.Third) {
4206     ImplicitConversionSequence ICS;
4207     ICS.setStandard();
4208     ICS.Standard = Best->FinalConversion;
4209     Sequence.AddConversionSequenceStep(ICS, DestType, TopLevelOfInitList);
4210   }
4211 }
4212 
4213 /// An egregious hack for compatibility with libstdc++-4.2: in <tr1/hashtable>,
4214 /// a function with a pointer return type contains a 'return false;' statement.
4215 /// In C++11, 'false' is not a null pointer, so this breaks the build of any
4216 /// code using that header.
4217 ///
4218 /// Work around this by treating 'return false;' as zero-initializing the result
4219 /// if it's used in a pointer-returning function in a system header.
4220 static bool isLibstdcxxPointerReturnFalseHack(Sema &S,
4221                                               const InitializedEntity &Entity,
4222                                               const Expr *Init) {
4223   return S.getLangOpts().CPlusPlus11 &&
4224          Entity.getKind() == InitializedEntity::EK_Result &&
4225          Entity.getType()->isPointerType() &&
4226          isa<CXXBoolLiteralExpr>(Init) &&
4227          !cast<CXXBoolLiteralExpr>(Init)->getValue() &&
4228          S.getSourceManager().isInSystemHeader(Init->getExprLoc());
4229 }
4230 
4231 /// The non-zero enum values here are indexes into diagnostic alternatives.
4232 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
4233 
4234 /// Determines whether this expression is an acceptable ICR source.
4235 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
4236                                          bool isAddressOf, bool &isWeakAccess) {
4237   // Skip parens.
4238   e = e->IgnoreParens();
4239 
4240   // Skip address-of nodes.
4241   if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
4242     if (op->getOpcode() == UO_AddrOf)
4243       return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true,
4244                                 isWeakAccess);
4245 
4246   // Skip certain casts.
4247   } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
4248     switch (ce->getCastKind()) {
4249     case CK_Dependent:
4250     case CK_BitCast:
4251     case CK_LValueBitCast:
4252     case CK_NoOp:
4253       return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf, isWeakAccess);
4254 
4255     case CK_ArrayToPointerDecay:
4256       return IIK_nonscalar;
4257 
4258     case CK_NullToPointer:
4259       return IIK_okay;
4260 
4261     default:
4262       break;
4263     }
4264 
4265   // If we have a declaration reference, it had better be a local variable.
4266   } else if (isa<DeclRefExpr>(e)) {
4267     // set isWeakAccess to true, to mean that there will be an implicit
4268     // load which requires a cleanup.
4269     if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
4270       isWeakAccess = true;
4271 
4272     if (!isAddressOf) return IIK_nonlocal;
4273 
4274     VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
4275     if (!var) return IIK_nonlocal;
4276 
4277     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
4278 
4279   // If we have a conditional operator, check both sides.
4280   } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
4281     if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf,
4282                                                 isWeakAccess))
4283       return iik;
4284 
4285     return isInvalidICRSource(C, cond->getRHS(), isAddressOf, isWeakAccess);
4286 
4287   // These are never scalar.
4288   } else if (isa<ArraySubscriptExpr>(e)) {
4289     return IIK_nonscalar;
4290 
4291   // Otherwise, it needs to be a null pointer constant.
4292   } else {
4293     return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
4294             ? IIK_okay : IIK_nonlocal);
4295   }
4296 
4297   return IIK_nonlocal;
4298 }
4299 
4300 /// Check whether the given expression is a valid operand for an
4301 /// indirect copy/restore.
4302 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
4303   assert(src->isRValue());
4304   bool isWeakAccess = false;
4305   InvalidICRKind iik = isInvalidICRSource(S.Context, src, false, isWeakAccess);
4306   // If isWeakAccess to true, there will be an implicit
4307   // load which requires a cleanup.
4308   if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess)
4309     S.ExprNeedsCleanups = true;
4310 
4311   if (iik == IIK_okay) return;
4312 
4313   S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
4314     << ((unsigned) iik - 1)  // shift index into diagnostic explanations
4315     << src->getSourceRange();
4316 }
4317 
4318 /// \brief Determine whether we have compatible array types for the
4319 /// purposes of GNU by-copy array initialization.
4320 static bool hasCompatibleArrayTypes(ASTContext &Context,
4321                                     const ArrayType *Dest,
4322                                     const ArrayType *Source) {
4323   // If the source and destination array types are equivalent, we're
4324   // done.
4325   if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
4326     return true;
4327 
4328   // Make sure that the element types are the same.
4329   if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
4330     return false;
4331 
4332   // The only mismatch we allow is when the destination is an
4333   // incomplete array type and the source is a constant array type.
4334   return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
4335 }
4336 
4337 static bool tryObjCWritebackConversion(Sema &S,
4338                                        InitializationSequence &Sequence,
4339                                        const InitializedEntity &Entity,
4340                                        Expr *Initializer) {
4341   bool ArrayDecay = false;
4342   QualType ArgType = Initializer->getType();
4343   QualType ArgPointee;
4344   if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
4345     ArrayDecay = true;
4346     ArgPointee = ArgArrayType->getElementType();
4347     ArgType = S.Context.getPointerType(ArgPointee);
4348   }
4349 
4350   // Handle write-back conversion.
4351   QualType ConvertedArgType;
4352   if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
4353                                    ConvertedArgType))
4354     return false;
4355 
4356   // We should copy unless we're passing to an argument explicitly
4357   // marked 'out'.
4358   bool ShouldCopy = true;
4359   if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4360     ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4361 
4362   // Do we need an lvalue conversion?
4363   if (ArrayDecay || Initializer->isGLValue()) {
4364     ImplicitConversionSequence ICS;
4365     ICS.setStandard();
4366     ICS.Standard.setAsIdentityConversion();
4367 
4368     QualType ResultType;
4369     if (ArrayDecay) {
4370       ICS.Standard.First = ICK_Array_To_Pointer;
4371       ResultType = S.Context.getPointerType(ArgPointee);
4372     } else {
4373       ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4374       ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4375     }
4376 
4377     Sequence.AddConversionSequenceStep(ICS, ResultType);
4378   }
4379 
4380   Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4381   return true;
4382 }
4383 
4384 static bool TryOCLSamplerInitialization(Sema &S,
4385                                         InitializationSequence &Sequence,
4386                                         QualType DestType,
4387                                         Expr *Initializer) {
4388   if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() ||
4389     !Initializer->isIntegerConstantExpr(S.getASTContext()))
4390     return false;
4391 
4392   Sequence.AddOCLSamplerInitStep(DestType);
4393   return true;
4394 }
4395 
4396 //
4397 // OpenCL 1.2 spec, s6.12.10
4398 //
4399 // The event argument can also be used to associate the
4400 // async_work_group_copy with a previous async copy allowing
4401 // an event to be shared by multiple async copies; otherwise
4402 // event should be zero.
4403 //
4404 static bool TryOCLZeroEventInitialization(Sema &S,
4405                                           InitializationSequence &Sequence,
4406                                           QualType DestType,
4407                                           Expr *Initializer) {
4408   if (!S.getLangOpts().OpenCL || !DestType->isEventT() ||
4409       !Initializer->isIntegerConstantExpr(S.getASTContext()) ||
4410       (Initializer->EvaluateKnownConstInt(S.getASTContext()) != 0))
4411     return false;
4412 
4413   Sequence.AddOCLZeroEventStep(DestType);
4414   return true;
4415 }
4416 
4417 InitializationSequence::InitializationSequence(Sema &S,
4418                                                const InitializedEntity &Entity,
4419                                                const InitializationKind &Kind,
4420                                                MultiExprArg Args,
4421                                                bool TopLevelOfInitList)
4422     : FailedCandidateSet(Kind.getLocation()) {
4423   InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList);
4424 }
4425 
4426 void InitializationSequence::InitializeFrom(Sema &S,
4427                                             const InitializedEntity &Entity,
4428                                             const InitializationKind &Kind,
4429                                             MultiExprArg Args,
4430                                             bool TopLevelOfInitList) {
4431   ASTContext &Context = S.Context;
4432 
4433   // Eliminate non-overload placeholder types in the arguments.  We
4434   // need to do this before checking whether types are dependent
4435   // because lowering a pseudo-object expression might well give us
4436   // something of dependent type.
4437   for (unsigned I = 0, E = Args.size(); I != E; ++I)
4438     if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
4439       // FIXME: should we be doing this here?
4440       ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4441       if (result.isInvalid()) {
4442         SetFailed(FK_PlaceholderType);
4443         return;
4444       }
4445       Args[I] = result.take();
4446     }
4447 
4448   // C++0x [dcl.init]p16:
4449   //   The semantics of initializers are as follows. The destination type is
4450   //   the type of the object or reference being initialized and the source
4451   //   type is the type of the initializer expression. The source type is not
4452   //   defined when the initializer is a braced-init-list or when it is a
4453   //   parenthesized list of expressions.
4454   QualType DestType = Entity.getType();
4455 
4456   if (DestType->isDependentType() ||
4457       Expr::hasAnyTypeDependentArguments(Args)) {
4458     SequenceKind = DependentSequence;
4459     return;
4460   }
4461 
4462   // Almost everything is a normal sequence.
4463   setSequenceKind(NormalSequence);
4464 
4465   QualType SourceType;
4466   Expr *Initializer = 0;
4467   if (Args.size() == 1) {
4468     Initializer = Args[0];
4469     if (S.getLangOpts().ObjC1) {
4470       if (S.CheckObjCBridgeRelatedConversions(Initializer->getLocStart(),
4471                                               DestType, Initializer->getType(),
4472                                               Initializer) ||
4473           S.ConversionToObjCStringLiteralCheck(DestType, Initializer))
4474         Args[0] = Initializer;
4475 
4476     }
4477     if (!isa<InitListExpr>(Initializer))
4478       SourceType = Initializer->getType();
4479   }
4480 
4481   //     - If the initializer is a (non-parenthesized) braced-init-list, the
4482   //       object is list-initialized (8.5.4).
4483   if (Kind.getKind() != InitializationKind::IK_Direct) {
4484     if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
4485       TryListInitialization(S, Entity, Kind, InitList, *this);
4486       return;
4487     }
4488   }
4489 
4490   //     - If the destination type is a reference type, see 8.5.3.
4491   if (DestType->isReferenceType()) {
4492     // C++0x [dcl.init.ref]p1:
4493     //   A variable declared to be a T& or T&&, that is, "reference to type T"
4494     //   (8.3.2), shall be initialized by an object, or function, of type T or
4495     //   by an object that can be converted into a T.
4496     // (Therefore, multiple arguments are not permitted.)
4497     if (Args.size() != 1)
4498       SetFailed(FK_TooManyInitsForReference);
4499     else
4500       TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
4501     return;
4502   }
4503 
4504   //     - If the initializer is (), the object is value-initialized.
4505   if (Kind.getKind() == InitializationKind::IK_Value ||
4506       (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) {
4507     TryValueInitialization(S, Entity, Kind, *this);
4508     return;
4509   }
4510 
4511   // Handle default initialization.
4512   if (Kind.getKind() == InitializationKind::IK_Default) {
4513     TryDefaultInitialization(S, Entity, Kind, *this);
4514     return;
4515   }
4516 
4517   //     - If the destination type is an array of characters, an array of
4518   //       char16_t, an array of char32_t, or an array of wchar_t, and the
4519   //       initializer is a string literal, see 8.5.2.
4520   //     - Otherwise, if the destination type is an array, the program is
4521   //       ill-formed.
4522   if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
4523     if (Initializer && isa<VariableArrayType>(DestAT)) {
4524       SetFailed(FK_VariableLengthArrayHasInitializer);
4525       return;
4526     }
4527 
4528     if (Initializer) {
4529       switch (IsStringInit(Initializer, DestAT, Context)) {
4530       case SIF_None:
4531         TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
4532         return;
4533       case SIF_NarrowStringIntoWideChar:
4534         SetFailed(FK_NarrowStringIntoWideCharArray);
4535         return;
4536       case SIF_WideStringIntoChar:
4537         SetFailed(FK_WideStringIntoCharArray);
4538         return;
4539       case SIF_IncompatWideStringIntoWideChar:
4540         SetFailed(FK_IncompatWideStringIntoWideChar);
4541         return;
4542       case SIF_Other:
4543         break;
4544       }
4545     }
4546 
4547     // Note: as an GNU C extension, we allow initialization of an
4548     // array from a compound literal that creates an array of the same
4549     // type, so long as the initializer has no side effects.
4550     if (!S.getLangOpts().CPlusPlus && Initializer &&
4551         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4552         Initializer->getType()->isArrayType()) {
4553       const ArrayType *SourceAT
4554         = Context.getAsArrayType(Initializer->getType());
4555       if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
4556         SetFailed(FK_ArrayTypeMismatch);
4557       else if (Initializer->HasSideEffects(S.Context))
4558         SetFailed(FK_NonConstantArrayInit);
4559       else {
4560         AddArrayInitStep(DestType);
4561       }
4562     }
4563     // Note: as a GNU C++ extension, we allow list-initialization of a
4564     // class member of array type from a parenthesized initializer list.
4565     else if (S.getLangOpts().CPlusPlus &&
4566              Entity.getKind() == InitializedEntity::EK_Member &&
4567              Initializer && isa<InitListExpr>(Initializer)) {
4568       TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
4569                             *this);
4570       AddParenthesizedArrayInitStep(DestType);
4571     } else if (DestAT->getElementType()->isCharType())
4572       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
4573     else if (IsWideCharCompatible(DestAT->getElementType(), Context))
4574       SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral);
4575     else
4576       SetFailed(FK_ArrayNeedsInitList);
4577 
4578     return;
4579   }
4580 
4581   // Determine whether we should consider writeback conversions for
4582   // Objective-C ARC.
4583   bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
4584          Entity.isParameterKind();
4585 
4586   // We're at the end of the line for C: it's either a write-back conversion
4587   // or it's a C assignment. There's no need to check anything else.
4588   if (!S.getLangOpts().CPlusPlus) {
4589     // If allowed, check whether this is an Objective-C writeback conversion.
4590     if (allowObjCWritebackConversion &&
4591         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
4592       return;
4593     }
4594 
4595     if (TryOCLSamplerInitialization(S, *this, DestType, Initializer))
4596       return;
4597 
4598     if (TryOCLZeroEventInitialization(S, *this, DestType, Initializer))
4599       return;
4600 
4601     // Handle initialization in C
4602     AddCAssignmentStep(DestType);
4603     MaybeProduceObjCObject(S, *this, Entity);
4604     return;
4605   }
4606 
4607   assert(S.getLangOpts().CPlusPlus);
4608 
4609   //     - If the destination type is a (possibly cv-qualified) class type:
4610   if (DestType->isRecordType()) {
4611     //     - If the initialization is direct-initialization, or if it is
4612     //       copy-initialization where the cv-unqualified version of the
4613     //       source type is the same class as, or a derived class of, the
4614     //       class of the destination, constructors are considered. [...]
4615     if (Kind.getKind() == InitializationKind::IK_Direct ||
4616         (Kind.getKind() == InitializationKind::IK_Copy &&
4617          (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4618           S.IsDerivedFrom(SourceType, DestType))))
4619       TryConstructorInitialization(S, Entity, Kind, Args,
4620                                    Entity.getType(), *this);
4621     //     - Otherwise (i.e., for the remaining copy-initialization cases),
4622     //       user-defined conversion sequences that can convert from the source
4623     //       type to the destination type or (when a conversion function is
4624     //       used) to a derived class thereof are enumerated as described in
4625     //       13.3.1.4, and the best one is chosen through overload resolution
4626     //       (13.3).
4627     else
4628       TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4629                                TopLevelOfInitList);
4630     return;
4631   }
4632 
4633   if (Args.size() > 1) {
4634     SetFailed(FK_TooManyInitsForScalar);
4635     return;
4636   }
4637   assert(Args.size() == 1 && "Zero-argument case handled above");
4638 
4639   //    - Otherwise, if the source type is a (possibly cv-qualified) class
4640   //      type, conversion functions are considered.
4641   if (!SourceType.isNull() && SourceType->isRecordType()) {
4642     TryUserDefinedConversion(S, Entity, Kind, Initializer, *this,
4643                              TopLevelOfInitList);
4644     MaybeProduceObjCObject(S, *this, Entity);
4645     return;
4646   }
4647 
4648   //    - Otherwise, the initial value of the object being initialized is the
4649   //      (possibly converted) value of the initializer expression. Standard
4650   //      conversions (Clause 4) will be used, if necessary, to convert the
4651   //      initializer expression to the cv-unqualified version of the
4652   //      destination type; no user-defined conversions are considered.
4653 
4654   ImplicitConversionSequence ICS
4655     = S.TryImplicitConversion(Initializer, Entity.getType(),
4656                               /*SuppressUserConversions*/true,
4657                               /*AllowExplicitConversions*/ false,
4658                               /*InOverloadResolution*/ false,
4659                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4660                               allowObjCWritebackConversion);
4661 
4662   if (ICS.isStandard() &&
4663       ICS.Standard.Second == ICK_Writeback_Conversion) {
4664     // Objective-C ARC writeback conversion.
4665 
4666     // We should copy unless we're passing to an argument explicitly
4667     // marked 'out'.
4668     bool ShouldCopy = true;
4669     if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4670       ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4671 
4672     // If there was an lvalue adjustment, add it as a separate conversion.
4673     if (ICS.Standard.First == ICK_Array_To_Pointer ||
4674         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4675       ImplicitConversionSequence LvalueICS;
4676       LvalueICS.setStandard();
4677       LvalueICS.Standard.setAsIdentityConversion();
4678       LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4679       LvalueICS.Standard.First = ICS.Standard.First;
4680       AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
4681     }
4682 
4683     AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4684   } else if (ICS.isBad()) {
4685     DeclAccessPair dap;
4686     if (isLibstdcxxPointerReturnFalseHack(S, Entity, Initializer)) {
4687       AddZeroInitializationStep(Entity.getType());
4688     } else if (Initializer->getType() == Context.OverloadTy &&
4689                !S.ResolveAddressOfOverloadedFunction(Initializer, DestType,
4690                                                      false, dap))
4691       SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4692     else
4693       SetFailed(InitializationSequence::FK_ConversionFailed);
4694   } else {
4695     AddConversionSequenceStep(ICS, Entity.getType(), TopLevelOfInitList);
4696 
4697     MaybeProduceObjCObject(S, *this, Entity);
4698   }
4699 }
4700 
4701 InitializationSequence::~InitializationSequence() {
4702   for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
4703                                           StepEnd = Steps.end();
4704        Step != StepEnd; ++Step)
4705     Step->Destroy();
4706 }
4707 
4708 //===----------------------------------------------------------------------===//
4709 // Perform initialization
4710 //===----------------------------------------------------------------------===//
4711 static Sema::AssignmentAction
4712 getAssignmentAction(const InitializedEntity &Entity, bool Diagnose = false) {
4713   switch(Entity.getKind()) {
4714   case InitializedEntity::EK_Variable:
4715   case InitializedEntity::EK_New:
4716   case InitializedEntity::EK_Exception:
4717   case InitializedEntity::EK_Base:
4718   case InitializedEntity::EK_Delegating:
4719     return Sema::AA_Initializing;
4720 
4721   case InitializedEntity::EK_Parameter:
4722     if (Entity.getDecl() &&
4723         isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4724       return Sema::AA_Sending;
4725 
4726     return Sema::AA_Passing;
4727 
4728   case InitializedEntity::EK_Parameter_CF_Audited:
4729     if (Entity.getDecl() &&
4730       isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4731       return Sema::AA_Sending;
4732 
4733     return !Diagnose ? Sema::AA_Passing : Sema::AA_Passing_CFAudited;
4734 
4735   case InitializedEntity::EK_Result:
4736     return Sema::AA_Returning;
4737 
4738   case InitializedEntity::EK_Temporary:
4739   case InitializedEntity::EK_RelatedResult:
4740     // FIXME: Can we tell apart casting vs. converting?
4741     return Sema::AA_Casting;
4742 
4743   case InitializedEntity::EK_Member:
4744   case InitializedEntity::EK_ArrayElement:
4745   case InitializedEntity::EK_VectorElement:
4746   case InitializedEntity::EK_ComplexElement:
4747   case InitializedEntity::EK_BlockElement:
4748   case InitializedEntity::EK_LambdaCapture:
4749   case InitializedEntity::EK_CompoundLiteralInit:
4750     return Sema::AA_Initializing;
4751   }
4752 
4753   llvm_unreachable("Invalid EntityKind!");
4754 }
4755 
4756 /// \brief Whether we should bind a created object as a temporary when
4757 /// initializing the given entity.
4758 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
4759   switch (Entity.getKind()) {
4760   case InitializedEntity::EK_ArrayElement:
4761   case InitializedEntity::EK_Member:
4762   case InitializedEntity::EK_Result:
4763   case InitializedEntity::EK_New:
4764   case InitializedEntity::EK_Variable:
4765   case InitializedEntity::EK_Base:
4766   case InitializedEntity::EK_Delegating:
4767   case InitializedEntity::EK_VectorElement:
4768   case InitializedEntity::EK_ComplexElement:
4769   case InitializedEntity::EK_Exception:
4770   case InitializedEntity::EK_BlockElement:
4771   case InitializedEntity::EK_LambdaCapture:
4772   case InitializedEntity::EK_CompoundLiteralInit:
4773     return false;
4774 
4775   case InitializedEntity::EK_Parameter:
4776   case InitializedEntity::EK_Parameter_CF_Audited:
4777   case InitializedEntity::EK_Temporary:
4778   case InitializedEntity::EK_RelatedResult:
4779     return true;
4780   }
4781 
4782   llvm_unreachable("missed an InitializedEntity kind?");
4783 }
4784 
4785 /// \brief Whether the given entity, when initialized with an object
4786 /// created for that initialization, requires destruction.
4787 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4788   switch (Entity.getKind()) {
4789     case InitializedEntity::EK_Result:
4790     case InitializedEntity::EK_New:
4791     case InitializedEntity::EK_Base:
4792     case InitializedEntity::EK_Delegating:
4793     case InitializedEntity::EK_VectorElement:
4794     case InitializedEntity::EK_ComplexElement:
4795     case InitializedEntity::EK_BlockElement:
4796     case InitializedEntity::EK_LambdaCapture:
4797       return false;
4798 
4799     case InitializedEntity::EK_Member:
4800     case InitializedEntity::EK_Variable:
4801     case InitializedEntity::EK_Parameter:
4802     case InitializedEntity::EK_Parameter_CF_Audited:
4803     case InitializedEntity::EK_Temporary:
4804     case InitializedEntity::EK_ArrayElement:
4805     case InitializedEntity::EK_Exception:
4806     case InitializedEntity::EK_CompoundLiteralInit:
4807     case InitializedEntity::EK_RelatedResult:
4808       return true;
4809   }
4810 
4811   llvm_unreachable("missed an InitializedEntity kind?");
4812 }
4813 
4814 /// \brief Look for copy and move constructors and constructor templates, for
4815 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4816 static void LookupCopyAndMoveConstructors(Sema &S,
4817                                           OverloadCandidateSet &CandidateSet,
4818                                           CXXRecordDecl *Class,
4819                                           Expr *CurInitExpr) {
4820   DeclContext::lookup_result R = S.LookupConstructors(Class);
4821   // The container holding the constructors can under certain conditions
4822   // be changed while iterating (e.g. because of deserialization).
4823   // To be safe we copy the lookup results to a new container.
4824   SmallVector<NamedDecl*, 16> Ctors(R.begin(), R.end());
4825   for (SmallVectorImpl<NamedDecl *>::iterator
4826          CI = Ctors.begin(), CE = Ctors.end(); CI != CE; ++CI) {
4827     NamedDecl *D = *CI;
4828     CXXConstructorDecl *Constructor = 0;
4829 
4830     if ((Constructor = dyn_cast<CXXConstructorDecl>(D))) {
4831       // Handle copy/moveconstructors, only.
4832       if (!Constructor || Constructor->isInvalidDecl() ||
4833           !Constructor->isCopyOrMoveConstructor() ||
4834           !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4835         continue;
4836 
4837       DeclAccessPair FoundDecl
4838         = DeclAccessPair::make(Constructor, Constructor->getAccess());
4839       S.AddOverloadCandidate(Constructor, FoundDecl,
4840                              CurInitExpr, CandidateSet);
4841       continue;
4842     }
4843 
4844     // Handle constructor templates.
4845     FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(D);
4846     if (ConstructorTmpl->isInvalidDecl())
4847       continue;
4848 
4849     Constructor = cast<CXXConstructorDecl>(
4850                                          ConstructorTmpl->getTemplatedDecl());
4851     if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4852       continue;
4853 
4854     // FIXME: Do we need to limit this to copy-constructor-like
4855     // candidates?
4856     DeclAccessPair FoundDecl
4857       = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4858     S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4859                                    CurInitExpr, CandidateSet, true);
4860   }
4861 }
4862 
4863 /// \brief Get the location at which initialization diagnostics should appear.
4864 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4865                                            Expr *Initializer) {
4866   switch (Entity.getKind()) {
4867   case InitializedEntity::EK_Result:
4868     return Entity.getReturnLoc();
4869 
4870   case InitializedEntity::EK_Exception:
4871     return Entity.getThrowLoc();
4872 
4873   case InitializedEntity::EK_Variable:
4874     return Entity.getDecl()->getLocation();
4875 
4876   case InitializedEntity::EK_LambdaCapture:
4877     return Entity.getCaptureLoc();
4878 
4879   case InitializedEntity::EK_ArrayElement:
4880   case InitializedEntity::EK_Member:
4881   case InitializedEntity::EK_Parameter:
4882   case InitializedEntity::EK_Parameter_CF_Audited:
4883   case InitializedEntity::EK_Temporary:
4884   case InitializedEntity::EK_New:
4885   case InitializedEntity::EK_Base:
4886   case InitializedEntity::EK_Delegating:
4887   case InitializedEntity::EK_VectorElement:
4888   case InitializedEntity::EK_ComplexElement:
4889   case InitializedEntity::EK_BlockElement:
4890   case InitializedEntity::EK_CompoundLiteralInit:
4891   case InitializedEntity::EK_RelatedResult:
4892     return Initializer->getLocStart();
4893   }
4894   llvm_unreachable("missed an InitializedEntity kind?");
4895 }
4896 
4897 /// \brief Make a (potentially elidable) temporary copy of the object
4898 /// provided by the given initializer by calling the appropriate copy
4899 /// constructor.
4900 ///
4901 /// \param S The Sema object used for type-checking.
4902 ///
4903 /// \param T The type of the temporary object, which must either be
4904 /// the type of the initializer expression or a superclass thereof.
4905 ///
4906 /// \param Entity The entity being initialized.
4907 ///
4908 /// \param CurInit The initializer expression.
4909 ///
4910 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4911 /// is permitted in C++03 (but not C++0x) when binding a reference to
4912 /// an rvalue.
4913 ///
4914 /// \returns An expression that copies the initializer expression into
4915 /// a temporary object, or an error expression if a copy could not be
4916 /// created.
4917 static ExprResult CopyObject(Sema &S,
4918                              QualType T,
4919                              const InitializedEntity &Entity,
4920                              ExprResult CurInit,
4921                              bool IsExtraneousCopy) {
4922   // Determine which class type we're copying to.
4923   Expr *CurInitExpr = (Expr *)CurInit.get();
4924   CXXRecordDecl *Class = 0;
4925   if (const RecordType *Record = T->getAs<RecordType>())
4926     Class = cast<CXXRecordDecl>(Record->getDecl());
4927   if (!Class)
4928     return CurInit;
4929 
4930   // C++0x [class.copy]p32:
4931   //   When certain criteria are met, an implementation is allowed to
4932   //   omit the copy/move construction of a class object, even if the
4933   //   copy/move constructor and/or destructor for the object have
4934   //   side effects. [...]
4935   //     - when a temporary class object that has not been bound to a
4936   //       reference (12.2) would be copied/moved to a class object
4937   //       with the same cv-unqualified type, the copy/move operation
4938   //       can be omitted by constructing the temporary object
4939   //       directly into the target of the omitted copy/move
4940   //
4941   // Note that the other three bullets are handled elsewhere. Copy
4942   // elision for return statements and throw expressions are handled as part
4943   // of constructor initialization, while copy elision for exception handlers
4944   // is handled by the run-time.
4945   bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
4946   SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
4947 
4948   // Make sure that the type we are copying is complete.
4949   if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
4950     return CurInit;
4951 
4952   // Perform overload resolution using the class's copy/move constructors.
4953   // Only consider constructors and constructor templates. Per
4954   // C++0x [dcl.init]p16, second bullet to class types, this initialization
4955   // is direct-initialization.
4956   OverloadCandidateSet CandidateSet(Loc);
4957   LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
4958 
4959   bool HadMultipleCandidates = (CandidateSet.size() > 1);
4960 
4961   OverloadCandidateSet::iterator Best;
4962   switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
4963   case OR_Success:
4964     break;
4965 
4966   case OR_No_Viable_Function:
4967     S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4968            ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4969            : diag::err_temp_copy_no_viable)
4970       << (int)Entity.getKind() << CurInitExpr->getType()
4971       << CurInitExpr->getSourceRange();
4972     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
4973     if (!IsExtraneousCopy || S.isSFINAEContext())
4974       return ExprError();
4975     return CurInit;
4976 
4977   case OR_Ambiguous:
4978     S.Diag(Loc, diag::err_temp_copy_ambiguous)
4979       << (int)Entity.getKind() << CurInitExpr->getType()
4980       << CurInitExpr->getSourceRange();
4981     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
4982     return ExprError();
4983 
4984   case OR_Deleted:
4985     S.Diag(Loc, diag::err_temp_copy_deleted)
4986       << (int)Entity.getKind() << CurInitExpr->getType()
4987       << CurInitExpr->getSourceRange();
4988     S.NoteDeletedFunction(Best->Function);
4989     return ExprError();
4990   }
4991 
4992   CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
4993   SmallVector<Expr*, 8> ConstructorArgs;
4994   CurInit.release(); // Ownership transferred into MultiExprArg, below.
4995 
4996   S.CheckConstructorAccess(Loc, Constructor, Entity,
4997                            Best->FoundDecl.getAccess(), IsExtraneousCopy);
4998 
4999   if (IsExtraneousCopy) {
5000     // If this is a totally extraneous copy for C++03 reference
5001     // binding purposes, just return the original initialization
5002     // expression. We don't generate an (elided) copy operation here
5003     // because doing so would require us to pass down a flag to avoid
5004     // infinite recursion, where each step adds another extraneous,
5005     // elidable copy.
5006 
5007     // Instantiate the default arguments of any extra parameters in
5008     // the selected copy constructor, as if we were going to create a
5009     // proper call to the copy constructor.
5010     for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
5011       ParmVarDecl *Parm = Constructor->getParamDecl(I);
5012       if (S.RequireCompleteType(Loc, Parm->getType(),
5013                                 diag::err_call_incomplete_argument))
5014         break;
5015 
5016       // Build the default argument expression; we don't actually care
5017       // if this succeeds or not, because this routine will complain
5018       // if there was a problem.
5019       S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
5020     }
5021 
5022     return S.Owned(CurInitExpr);
5023   }
5024 
5025   // Determine the arguments required to actually perform the
5026   // constructor call (we might have derived-to-base conversions, or
5027   // the copy constructor may have default arguments).
5028   if (S.CompleteConstructorCall(Constructor, CurInitExpr, Loc, ConstructorArgs))
5029     return ExprError();
5030 
5031   // Actually perform the constructor call.
5032   CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
5033                                     ConstructorArgs,
5034                                     HadMultipleCandidates,
5035                                     /*ListInit*/ false,
5036                                     /*ZeroInit*/ false,
5037                                     CXXConstructExpr::CK_Complete,
5038                                     SourceRange());
5039 
5040   // If we're supposed to bind temporaries, do so.
5041   if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
5042     CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5043   return CurInit;
5044 }
5045 
5046 /// \brief Check whether elidable copy construction for binding a reference to
5047 /// a temporary would have succeeded if we were building in C++98 mode, for
5048 /// -Wc++98-compat.
5049 static void CheckCXX98CompatAccessibleCopy(Sema &S,
5050                                            const InitializedEntity &Entity,
5051                                            Expr *CurInitExpr) {
5052   assert(S.getLangOpts().CPlusPlus11);
5053 
5054   const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
5055   if (!Record)
5056     return;
5057 
5058   SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
5059   if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
5060         == DiagnosticsEngine::Ignored)
5061     return;
5062 
5063   // Find constructors which would have been considered.
5064   OverloadCandidateSet CandidateSet(Loc);
5065   LookupCopyAndMoveConstructors(
5066       S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
5067 
5068   // Perform overload resolution.
5069   OverloadCandidateSet::iterator Best;
5070   OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
5071 
5072   PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
5073     << OR << (int)Entity.getKind() << CurInitExpr->getType()
5074     << CurInitExpr->getSourceRange();
5075 
5076   switch (OR) {
5077   case OR_Success:
5078     S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
5079                              Entity, Best->FoundDecl.getAccess(), Diag);
5080     // FIXME: Check default arguments as far as that's possible.
5081     break;
5082 
5083   case OR_No_Viable_Function:
5084     S.Diag(Loc, Diag);
5085     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
5086     break;
5087 
5088   case OR_Ambiguous:
5089     S.Diag(Loc, Diag);
5090     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
5091     break;
5092 
5093   case OR_Deleted:
5094     S.Diag(Loc, Diag);
5095     S.NoteDeletedFunction(Best->Function);
5096     break;
5097   }
5098 }
5099 
5100 void InitializationSequence::PrintInitLocationNote(Sema &S,
5101                                               const InitializedEntity &Entity) {
5102   if (Entity.isParameterKind() && Entity.getDecl()) {
5103     if (Entity.getDecl()->getLocation().isInvalid())
5104       return;
5105 
5106     if (Entity.getDecl()->getDeclName())
5107       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
5108         << Entity.getDecl()->getDeclName();
5109     else
5110       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
5111   }
5112   else if (Entity.getKind() == InitializedEntity::EK_RelatedResult &&
5113            Entity.getMethodDecl())
5114     S.Diag(Entity.getMethodDecl()->getLocation(),
5115            diag::note_method_return_type_change)
5116       << Entity.getMethodDecl()->getDeclName();
5117 }
5118 
5119 static bool isReferenceBinding(const InitializationSequence::Step &s) {
5120   return s.Kind == InitializationSequence::SK_BindReference ||
5121          s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
5122 }
5123 
5124 /// Returns true if the parameters describe a constructor initialization of
5125 /// an explicit temporary object, e.g. "Point(x, y)".
5126 static bool isExplicitTemporary(const InitializedEntity &Entity,
5127                                 const InitializationKind &Kind,
5128                                 unsigned NumArgs) {
5129   switch (Entity.getKind()) {
5130   case InitializedEntity::EK_Temporary:
5131   case InitializedEntity::EK_CompoundLiteralInit:
5132   case InitializedEntity::EK_RelatedResult:
5133     break;
5134   default:
5135     return false;
5136   }
5137 
5138   switch (Kind.getKind()) {
5139   case InitializationKind::IK_DirectList:
5140     return true;
5141   // FIXME: Hack to work around cast weirdness.
5142   case InitializationKind::IK_Direct:
5143   case InitializationKind::IK_Value:
5144     return NumArgs != 1;
5145   default:
5146     return false;
5147   }
5148 }
5149 
5150 static ExprResult
5151 PerformConstructorInitialization(Sema &S,
5152                                  const InitializedEntity &Entity,
5153                                  const InitializationKind &Kind,
5154                                  MultiExprArg Args,
5155                                  const InitializationSequence::Step& Step,
5156                                  bool &ConstructorInitRequiresZeroInit,
5157                                  bool IsListInitialization,
5158                                  SourceLocation LBraceLoc,
5159                                  SourceLocation RBraceLoc) {
5160   unsigned NumArgs = Args.size();
5161   CXXConstructorDecl *Constructor
5162     = cast<CXXConstructorDecl>(Step.Function.Function);
5163   bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
5164 
5165   // Build a call to the selected constructor.
5166   SmallVector<Expr*, 8> ConstructorArgs;
5167   SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
5168                          ? Kind.getEqualLoc()
5169                          : Kind.getLocation();
5170 
5171   if (Kind.getKind() == InitializationKind::IK_Default) {
5172     // Force even a trivial, implicit default constructor to be
5173     // semantically checked. We do this explicitly because we don't build
5174     // the definition for completely trivial constructors.
5175     assert(Constructor->getParent() && "No parent class for constructor.");
5176     if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
5177         Constructor->isTrivial() && !Constructor->isUsed(false))
5178       S.DefineImplicitDefaultConstructor(Loc, Constructor);
5179   }
5180 
5181   ExprResult CurInit = S.Owned((Expr *)0);
5182 
5183   // C++ [over.match.copy]p1:
5184   //   - When initializing a temporary to be bound to the first parameter
5185   //     of a constructor that takes a reference to possibly cv-qualified
5186   //     T as its first argument, called with a single argument in the
5187   //     context of direct-initialization, explicit conversion functions
5188   //     are also considered.
5189   bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
5190                            Args.size() == 1 &&
5191                            Constructor->isCopyOrMoveConstructor();
5192 
5193   // Determine the arguments required to actually perform the constructor
5194   // call.
5195   if (S.CompleteConstructorCall(Constructor, Args,
5196                                 Loc, ConstructorArgs,
5197                                 AllowExplicitConv,
5198                                 IsListInitialization))
5199     return ExprError();
5200 
5201 
5202   if (isExplicitTemporary(Entity, Kind, NumArgs)) {
5203     // An explicitly-constructed temporary, e.g., X(1, 2).
5204     S.MarkFunctionReferenced(Loc, Constructor);
5205     if (S.DiagnoseUseOfDecl(Constructor, Loc))
5206       return ExprError();
5207 
5208     TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5209     if (!TSInfo)
5210       TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
5211     SourceRange ParenOrBraceRange =
5212       (Kind.getKind() == InitializationKind::IK_DirectList)
5213       ? SourceRange(LBraceLoc, RBraceLoc)
5214       : Kind.getParenRange();
5215 
5216     CurInit = S.Owned(
5217       new (S.Context) CXXTemporaryObjectExpr(S.Context, Constructor,
5218                                              TSInfo, ConstructorArgs,
5219                                              ParenOrBraceRange,
5220                                              HadMultipleCandidates,
5221                                              IsListInitialization,
5222                                              ConstructorInitRequiresZeroInit));
5223   } else {
5224     CXXConstructExpr::ConstructionKind ConstructKind =
5225       CXXConstructExpr::CK_Complete;
5226 
5227     if (Entity.getKind() == InitializedEntity::EK_Base) {
5228       ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
5229         CXXConstructExpr::CK_VirtualBase :
5230         CXXConstructExpr::CK_NonVirtualBase;
5231     } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
5232       ConstructKind = CXXConstructExpr::CK_Delegating;
5233     }
5234 
5235     // Only get the parenthesis or brace range if it is a list initialization or
5236     // direct construction.
5237     SourceRange ParenOrBraceRange;
5238     if (IsListInitialization)
5239       ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc);
5240     else if (Kind.getKind() == InitializationKind::IK_Direct)
5241       ParenOrBraceRange = Kind.getParenRange();
5242 
5243     // If the entity allows NRVO, mark the construction as elidable
5244     // unconditionally.
5245     if (Entity.allowsNRVO())
5246       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5247                                         Constructor, /*Elidable=*/true,
5248                                         ConstructorArgs,
5249                                         HadMultipleCandidates,
5250                                         IsListInitialization,
5251                                         ConstructorInitRequiresZeroInit,
5252                                         ConstructKind,
5253                                         ParenOrBraceRange);
5254     else
5255       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
5256                                         Constructor,
5257                                         ConstructorArgs,
5258                                         HadMultipleCandidates,
5259                                         IsListInitialization,
5260                                         ConstructorInitRequiresZeroInit,
5261                                         ConstructKind,
5262                                         ParenOrBraceRange);
5263   }
5264   if (CurInit.isInvalid())
5265     return ExprError();
5266 
5267   // Only check access if all of that succeeded.
5268   S.CheckConstructorAccess(Loc, Constructor, Entity,
5269                            Step.Function.FoundDecl.getAccess());
5270   if (S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc))
5271     return ExprError();
5272 
5273   if (shouldBindAsTemporary(Entity))
5274     CurInit = S.MaybeBindToTemporary(CurInit.take());
5275 
5276   return CurInit;
5277 }
5278 
5279 /// Determine whether the specified InitializedEntity definitely has a lifetime
5280 /// longer than the current full-expression. Conservatively returns false if
5281 /// it's unclear.
5282 static bool
5283 InitializedEntityOutlivesFullExpression(const InitializedEntity &Entity) {
5284   const InitializedEntity *Top = &Entity;
5285   while (Top->getParent())
5286     Top = Top->getParent();
5287 
5288   switch (Top->getKind()) {
5289   case InitializedEntity::EK_Variable:
5290   case InitializedEntity::EK_Result:
5291   case InitializedEntity::EK_Exception:
5292   case InitializedEntity::EK_Member:
5293   case InitializedEntity::EK_New:
5294   case InitializedEntity::EK_Base:
5295   case InitializedEntity::EK_Delegating:
5296     return true;
5297 
5298   case InitializedEntity::EK_ArrayElement:
5299   case InitializedEntity::EK_VectorElement:
5300   case InitializedEntity::EK_BlockElement:
5301   case InitializedEntity::EK_ComplexElement:
5302     // Could not determine what the full initialization is. Assume it might not
5303     // outlive the full-expression.
5304     return false;
5305 
5306   case InitializedEntity::EK_Parameter:
5307   case InitializedEntity::EK_Parameter_CF_Audited:
5308   case InitializedEntity::EK_Temporary:
5309   case InitializedEntity::EK_LambdaCapture:
5310   case InitializedEntity::EK_CompoundLiteralInit:
5311   case InitializedEntity::EK_RelatedResult:
5312     // The entity being initialized might not outlive the full-expression.
5313     return false;
5314   }
5315 
5316   llvm_unreachable("unknown entity kind");
5317 }
5318 
5319 /// Determine the declaration which an initialized entity ultimately refers to,
5320 /// for the purpose of lifetime-extending a temporary bound to a reference in
5321 /// the initialization of \p Entity.
5322 static const ValueDecl *
5323 getDeclForTemporaryLifetimeExtension(const InitializedEntity &Entity,
5324                                      const ValueDecl *FallbackDecl = 0) {
5325   // C++11 [class.temporary]p5:
5326   switch (Entity.getKind()) {
5327   case InitializedEntity::EK_Variable:
5328     //   The temporary [...] persists for the lifetime of the reference
5329     return Entity.getDecl();
5330 
5331   case InitializedEntity::EK_Member:
5332     // For subobjects, we look at the complete object.
5333     if (Entity.getParent())
5334       return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5335                                                   Entity.getDecl());
5336 
5337     //   except:
5338     //   -- A temporary bound to a reference member in a constructor's
5339     //      ctor-initializer persists until the constructor exits.
5340     return Entity.getDecl();
5341 
5342   case InitializedEntity::EK_Parameter:
5343   case InitializedEntity::EK_Parameter_CF_Audited:
5344     //   -- A temporary bound to a reference parameter in a function call
5345     //      persists until the completion of the full-expression containing
5346     //      the call.
5347   case InitializedEntity::EK_Result:
5348     //   -- The lifetime of a temporary bound to the returned value in a
5349     //      function return statement is not extended; the temporary is
5350     //      destroyed at the end of the full-expression in the return statement.
5351   case InitializedEntity::EK_New:
5352     //   -- A temporary bound to a reference in a new-initializer persists
5353     //      until the completion of the full-expression containing the
5354     //      new-initializer.
5355     return 0;
5356 
5357   case InitializedEntity::EK_Temporary:
5358   case InitializedEntity::EK_CompoundLiteralInit:
5359   case InitializedEntity::EK_RelatedResult:
5360     // We don't yet know the storage duration of the surrounding temporary.
5361     // Assume it's got full-expression duration for now, it will patch up our
5362     // storage duration if that's not correct.
5363     return 0;
5364 
5365   case InitializedEntity::EK_ArrayElement:
5366     // For subobjects, we look at the complete object.
5367     return getDeclForTemporaryLifetimeExtension(*Entity.getParent(),
5368                                                 FallbackDecl);
5369 
5370   case InitializedEntity::EK_Base:
5371   case InitializedEntity::EK_Delegating:
5372     // We can reach this case for aggregate initialization in a constructor:
5373     //   struct A { int &&r; };
5374     //   struct B : A { B() : A{0} {} };
5375     // In this case, use the innermost field decl as the context.
5376     return FallbackDecl;
5377 
5378   case InitializedEntity::EK_BlockElement:
5379   case InitializedEntity::EK_LambdaCapture:
5380   case InitializedEntity::EK_Exception:
5381   case InitializedEntity::EK_VectorElement:
5382   case InitializedEntity::EK_ComplexElement:
5383     return 0;
5384   }
5385   llvm_unreachable("unknown entity kind");
5386 }
5387 
5388 static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD);
5389 
5390 /// Update a glvalue expression that is used as the initializer of a reference
5391 /// to note that its lifetime is extended.
5392 /// \return \c true if any temporary had its lifetime extended.
5393 static bool performReferenceExtension(Expr *Init, const ValueDecl *ExtendingD) {
5394   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5395     if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
5396       // This is just redundant braces around an initializer. Step over it.
5397       Init = ILE->getInit(0);
5398     }
5399   }
5400 
5401   // Walk past any constructs which we can lifetime-extend across.
5402   Expr *Old;
5403   do {
5404     Old = Init;
5405 
5406     // Step over any subobject adjustments; we may have a materialized
5407     // temporary inside them.
5408     SmallVector<const Expr *, 2> CommaLHSs;
5409     SmallVector<SubobjectAdjustment, 2> Adjustments;
5410     Init = const_cast<Expr *>(
5411         Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5412 
5413     // Per current approach for DR1376, look through casts to reference type
5414     // when performing lifetime extension.
5415     if (CastExpr *CE = dyn_cast<CastExpr>(Init))
5416       if (CE->getSubExpr()->isGLValue())
5417         Init = CE->getSubExpr();
5418 
5419     // FIXME: Per DR1213, subscripting on an array temporary produces an xvalue.
5420     // It's unclear if binding a reference to that xvalue extends the array
5421     // temporary.
5422   } while (Init != Old);
5423 
5424   if (MaterializeTemporaryExpr *ME = dyn_cast<MaterializeTemporaryExpr>(Init)) {
5425     // Update the storage duration of the materialized temporary.
5426     // FIXME: Rebuild the expression instead of mutating it.
5427     ME->setExtendingDecl(ExtendingD);
5428     performLifetimeExtension(ME->GetTemporaryExpr(), ExtendingD);
5429     return true;
5430   }
5431 
5432   return false;
5433 }
5434 
5435 /// Update a prvalue expression that is going to be materialized as a
5436 /// lifetime-extended temporary.
5437 static void performLifetimeExtension(Expr *Init, const ValueDecl *ExtendingD) {
5438   // Dig out the expression which constructs the extended temporary.
5439   SmallVector<const Expr *, 2> CommaLHSs;
5440   SmallVector<SubobjectAdjustment, 2> Adjustments;
5441   Init = const_cast<Expr *>(
5442       Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments));
5443 
5444   if (CXXBindTemporaryExpr *BTE = dyn_cast<CXXBindTemporaryExpr>(Init))
5445     Init = BTE->getSubExpr();
5446 
5447   if (CXXStdInitializerListExpr *ILE =
5448           dyn_cast<CXXStdInitializerListExpr>(Init)) {
5449     performReferenceExtension(ILE->getSubExpr(), ExtendingD);
5450     return;
5451   }
5452 
5453   if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
5454     if (ILE->getType()->isArrayType()) {
5455       for (unsigned I = 0, N = ILE->getNumInits(); I != N; ++I)
5456         performLifetimeExtension(ILE->getInit(I), ExtendingD);
5457       return;
5458     }
5459 
5460     if (CXXRecordDecl *RD = ILE->getType()->getAsCXXRecordDecl()) {
5461       assert(RD->isAggregate() && "aggregate init on non-aggregate");
5462 
5463       // If we lifetime-extend a braced initializer which is initializing an
5464       // aggregate, and that aggregate contains reference members which are
5465       // bound to temporaries, those temporaries are also lifetime-extended.
5466       if (RD->isUnion() && ILE->getInitializedFieldInUnion() &&
5467           ILE->getInitializedFieldInUnion()->getType()->isReferenceType())
5468         performReferenceExtension(ILE->getInit(0), ExtendingD);
5469       else {
5470         unsigned Index = 0;
5471         for (RecordDecl::field_iterator I = RD->field_begin(),
5472                                         E = RD->field_end();
5473              I != E; ++I) {
5474           if (Index >= ILE->getNumInits())
5475             break;
5476           if (I->isUnnamedBitfield())
5477             continue;
5478           Expr *SubInit = ILE->getInit(Index);
5479           if (I->getType()->isReferenceType())
5480             performReferenceExtension(SubInit, ExtendingD);
5481           else if (isa<InitListExpr>(SubInit) ||
5482                    isa<CXXStdInitializerListExpr>(SubInit))
5483             // This may be either aggregate-initialization of a member or
5484             // initialization of a std::initializer_list object. Either way,
5485             // we should recursively lifetime-extend that initializer.
5486             performLifetimeExtension(SubInit, ExtendingD);
5487           ++Index;
5488         }
5489       }
5490     }
5491   }
5492 }
5493 
5494 static void warnOnLifetimeExtension(Sema &S, const InitializedEntity &Entity,
5495                                     const Expr *Init, bool IsInitializerList,
5496                                     const ValueDecl *ExtendingDecl) {
5497   // Warn if a field lifetime-extends a temporary.
5498   if (isa<FieldDecl>(ExtendingDecl)) {
5499     if (IsInitializerList) {
5500       S.Diag(Init->getExprLoc(), diag::warn_dangling_std_initializer_list)
5501         << /*at end of constructor*/true;
5502       return;
5503     }
5504 
5505     bool IsSubobjectMember = false;
5506     for (const InitializedEntity *Ent = Entity.getParent(); Ent;
5507          Ent = Ent->getParent()) {
5508       if (Ent->getKind() != InitializedEntity::EK_Base) {
5509         IsSubobjectMember = true;
5510         break;
5511       }
5512     }
5513     S.Diag(Init->getExprLoc(),
5514            diag::warn_bind_ref_member_to_temporary)
5515       << ExtendingDecl << Init->getSourceRange()
5516       << IsSubobjectMember << IsInitializerList;
5517     if (IsSubobjectMember)
5518       S.Diag(ExtendingDecl->getLocation(),
5519              diag::note_ref_subobject_of_member_declared_here);
5520     else
5521       S.Diag(ExtendingDecl->getLocation(),
5522              diag::note_ref_or_ptr_member_declared_here)
5523         << /*is pointer*/false;
5524   }
5525 }
5526 
5527 static void DiagnoseNarrowingInInitList(Sema &S,
5528                                         const ImplicitConversionSequence &ICS,
5529                                         QualType PreNarrowingType,
5530                                         QualType EntityType,
5531                                         const Expr *PostInit);
5532 
5533 ExprResult
5534 InitializationSequence::Perform(Sema &S,
5535                                 const InitializedEntity &Entity,
5536                                 const InitializationKind &Kind,
5537                                 MultiExprArg Args,
5538                                 QualType *ResultType) {
5539   if (Failed()) {
5540     Diagnose(S, Entity, Kind, Args);
5541     return ExprError();
5542   }
5543 
5544   if (getKind() == DependentSequence) {
5545     // If the declaration is a non-dependent, incomplete array type
5546     // that has an initializer, then its type will be completed once
5547     // the initializer is instantiated.
5548     if (ResultType && !Entity.getType()->isDependentType() &&
5549         Args.size() == 1) {
5550       QualType DeclType = Entity.getType();
5551       if (const IncompleteArrayType *ArrayT
5552                            = S.Context.getAsIncompleteArrayType(DeclType)) {
5553         // FIXME: We don't currently have the ability to accurately
5554         // compute the length of an initializer list without
5555         // performing full type-checking of the initializer list
5556         // (since we have to determine where braces are implicitly
5557         // introduced and such).  So, we fall back to making the array
5558         // type a dependently-sized array type with no specified
5559         // bound.
5560         if (isa<InitListExpr>((Expr *)Args[0])) {
5561           SourceRange Brackets;
5562 
5563           // Scavange the location of the brackets from the entity, if we can.
5564           if (DeclaratorDecl *DD = Entity.getDecl()) {
5565             if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
5566               TypeLoc TL = TInfo->getTypeLoc();
5567               if (IncompleteArrayTypeLoc ArrayLoc =
5568                       TL.getAs<IncompleteArrayTypeLoc>())
5569                 Brackets = ArrayLoc.getBracketsRange();
5570             }
5571           }
5572 
5573           *ResultType
5574             = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
5575                                                    /*NumElts=*/0,
5576                                                    ArrayT->getSizeModifier(),
5577                                        ArrayT->getIndexTypeCVRQualifiers(),
5578                                                    Brackets);
5579         }
5580 
5581       }
5582     }
5583     if (Kind.getKind() == InitializationKind::IK_Direct &&
5584         !Kind.isExplicitCast()) {
5585       // Rebuild the ParenListExpr.
5586       SourceRange ParenRange = Kind.getParenRange();
5587       return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
5588                                   Args);
5589     }
5590     assert(Kind.getKind() == InitializationKind::IK_Copy ||
5591            Kind.isExplicitCast() ||
5592            Kind.getKind() == InitializationKind::IK_DirectList);
5593     return ExprResult(Args[0]);
5594   }
5595 
5596   // No steps means no initialization.
5597   if (Steps.empty())
5598     return S.Owned((Expr *)0);
5599 
5600   if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() &&
5601       Args.size() == 1 && isa<InitListExpr>(Args[0]) &&
5602       !Entity.isParameterKind()) {
5603     // Produce a C++98 compatibility warning if we are initializing a reference
5604     // from an initializer list. For parameters, we produce a better warning
5605     // elsewhere.
5606     Expr *Init = Args[0];
5607     S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
5608       << Init->getSourceRange();
5609   }
5610 
5611   // Diagnose cases where we initialize a pointer to an array temporary, and the
5612   // pointer obviously outlives the temporary.
5613   if (Args.size() == 1 && Args[0]->getType()->isArrayType() &&
5614       Entity.getType()->isPointerType() &&
5615       InitializedEntityOutlivesFullExpression(Entity)) {
5616     Expr *Init = Args[0];
5617     Expr::LValueClassification Kind = Init->ClassifyLValue(S.Context);
5618     if (Kind == Expr::LV_ClassTemporary || Kind == Expr::LV_ArrayTemporary)
5619       S.Diag(Init->getLocStart(), diag::warn_temporary_array_to_pointer_decay)
5620         << Init->getSourceRange();
5621   }
5622 
5623   QualType DestType = Entity.getType().getNonReferenceType();
5624   // FIXME: Ugly hack around the fact that Entity.getType() is not
5625   // the same as Entity.getDecl()->getType() in cases involving type merging,
5626   //  and we want latter when it makes sense.
5627   if (ResultType)
5628     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
5629                                      Entity.getType();
5630 
5631   ExprResult CurInit = S.Owned((Expr *)0);
5632 
5633   // For initialization steps that start with a single initializer,
5634   // grab the only argument out the Args and place it into the "current"
5635   // initializer.
5636   switch (Steps.front().Kind) {
5637   case SK_ResolveAddressOfOverloadedFunction:
5638   case SK_CastDerivedToBaseRValue:
5639   case SK_CastDerivedToBaseXValue:
5640   case SK_CastDerivedToBaseLValue:
5641   case SK_BindReference:
5642   case SK_BindReferenceToTemporary:
5643   case SK_ExtraneousCopyToTemporary:
5644   case SK_UserConversion:
5645   case SK_QualificationConversionLValue:
5646   case SK_QualificationConversionXValue:
5647   case SK_QualificationConversionRValue:
5648   case SK_LValueToRValue:
5649   case SK_ConversionSequence:
5650   case SK_ConversionSequenceNoNarrowing:
5651   case SK_ListInitialization:
5652   case SK_UnwrapInitList:
5653   case SK_RewrapInitList:
5654   case SK_CAssignment:
5655   case SK_StringInit:
5656   case SK_ObjCObjectConversion:
5657   case SK_ArrayInit:
5658   case SK_ParenthesizedArrayInit:
5659   case SK_PassByIndirectCopyRestore:
5660   case SK_PassByIndirectRestore:
5661   case SK_ProduceObjCObject:
5662   case SK_StdInitializerList:
5663   case SK_OCLSamplerInit:
5664   case SK_OCLZeroEvent: {
5665     assert(Args.size() == 1);
5666     CurInit = Args[0];
5667     if (!CurInit.get()) return ExprError();
5668     break;
5669   }
5670 
5671   case SK_ConstructorInitialization:
5672   case SK_ListConstructorCall:
5673   case SK_ZeroInitialization:
5674     break;
5675   }
5676 
5677   // Walk through the computed steps for the initialization sequence,
5678   // performing the specified conversions along the way.
5679   bool ConstructorInitRequiresZeroInit = false;
5680   for (step_iterator Step = step_begin(), StepEnd = step_end();
5681        Step != StepEnd; ++Step) {
5682     if (CurInit.isInvalid())
5683       return ExprError();
5684 
5685     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
5686 
5687     switch (Step->Kind) {
5688     case SK_ResolveAddressOfOverloadedFunction:
5689       // Overload resolution determined which function invoke; update the
5690       // initializer to reflect that choice.
5691       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
5692       if (S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation()))
5693         return ExprError();
5694       CurInit = S.FixOverloadedFunctionReference(CurInit,
5695                                                  Step->Function.FoundDecl,
5696                                                  Step->Function.Function);
5697       break;
5698 
5699     case SK_CastDerivedToBaseRValue:
5700     case SK_CastDerivedToBaseXValue:
5701     case SK_CastDerivedToBaseLValue: {
5702       // We have a derived-to-base cast that produces either an rvalue or an
5703       // lvalue. Perform that cast.
5704 
5705       CXXCastPath BasePath;
5706 
5707       // Casts to inaccessible base classes are allowed with C-style casts.
5708       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
5709       if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
5710                                          CurInit.get()->getLocStart(),
5711                                          CurInit.get()->getSourceRange(),
5712                                          &BasePath, IgnoreBaseAccess))
5713         return ExprError();
5714 
5715       if (S.BasePathInvolvesVirtualBase(BasePath)) {
5716         QualType T = SourceType;
5717         if (const PointerType *Pointer = T->getAs<PointerType>())
5718           T = Pointer->getPointeeType();
5719         if (const RecordType *RecordTy = T->getAs<RecordType>())
5720           S.MarkVTableUsed(CurInit.get()->getLocStart(),
5721                            cast<CXXRecordDecl>(RecordTy->getDecl()));
5722       }
5723 
5724       ExprValueKind VK =
5725           Step->Kind == SK_CastDerivedToBaseLValue ?
5726               VK_LValue :
5727               (Step->Kind == SK_CastDerivedToBaseXValue ?
5728                    VK_XValue :
5729                    VK_RValue);
5730       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5731                                                  Step->Type,
5732                                                  CK_DerivedToBase,
5733                                                  CurInit.get(),
5734                                                  &BasePath, VK));
5735       break;
5736     }
5737 
5738     case SK_BindReference:
5739       // References cannot bind to bit-fields (C++ [dcl.init.ref]p5).
5740       if (CurInit.get()->refersToBitField()) {
5741         // We don't necessarily have an unambiguous source bit-field.
5742         FieldDecl *BitField = CurInit.get()->getSourceBitField();
5743         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
5744           << Entity.getType().isVolatileQualified()
5745           << (BitField ? BitField->getDeclName() : DeclarationName())
5746           << (BitField != NULL)
5747           << CurInit.get()->getSourceRange();
5748         if (BitField)
5749           S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
5750 
5751         return ExprError();
5752       }
5753 
5754       if (CurInit.get()->refersToVectorElement()) {
5755         // References cannot bind to vector elements.
5756         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
5757           << Entity.getType().isVolatileQualified()
5758           << CurInit.get()->getSourceRange();
5759         PrintInitLocationNote(S, Entity);
5760         return ExprError();
5761       }
5762 
5763       // Reference binding does not have any corresponding ASTs.
5764 
5765       // Check exception specifications
5766       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5767         return ExprError();
5768 
5769       // Even though we didn't materialize a temporary, the binding may still
5770       // extend the lifetime of a temporary. This happens if we bind a reference
5771       // to the result of a cast to reference type.
5772       if (const ValueDecl *ExtendingDecl =
5773               getDeclForTemporaryLifetimeExtension(Entity)) {
5774         if (performReferenceExtension(CurInit.get(), ExtendingDecl))
5775           warnOnLifetimeExtension(S, Entity, CurInit.get(), false,
5776                                   ExtendingDecl);
5777       }
5778 
5779       break;
5780 
5781     case SK_BindReferenceToTemporary: {
5782       // Make sure the "temporary" is actually an rvalue.
5783       assert(CurInit.get()->isRValue() && "not a temporary");
5784 
5785       // Check exception specifications
5786       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
5787         return ExprError();
5788 
5789       // Maybe lifetime-extend the temporary's subobjects to match the
5790       // entity's lifetime.
5791       const ValueDecl *ExtendingDecl =
5792           getDeclForTemporaryLifetimeExtension(Entity);
5793       if (ExtendingDecl) {
5794         performLifetimeExtension(CurInit.get(), ExtendingDecl);
5795         warnOnLifetimeExtension(S, Entity, CurInit.get(), false, ExtendingDecl);
5796       }
5797 
5798       // Materialize the temporary into memory.
5799       MaterializeTemporaryExpr *MTE = new (S.Context) MaterializeTemporaryExpr(
5800           Entity.getType().getNonReferenceType(), CurInit.get(),
5801           Entity.getType()->isLValueReferenceType(), ExtendingDecl);
5802 
5803       // If we're binding to an Objective-C object that has lifetime, we
5804       // need cleanups. Likewise if we're extending this temporary to automatic
5805       // storage duration -- we need to register its cleanup during the
5806       // full-expression's cleanups.
5807       if ((S.getLangOpts().ObjCAutoRefCount &&
5808            MTE->getType()->isObjCLifetimeType()) ||
5809           (MTE->getStorageDuration() == SD_Automatic &&
5810            MTE->getType().isDestructedType()))
5811         S.ExprNeedsCleanups = true;
5812 
5813       CurInit = S.Owned(MTE);
5814       break;
5815     }
5816 
5817     case SK_ExtraneousCopyToTemporary:
5818       CurInit = CopyObject(S, Step->Type, Entity, CurInit,
5819                            /*IsExtraneousCopy=*/true);
5820       break;
5821 
5822     case SK_UserConversion: {
5823       // We have a user-defined conversion that invokes either a constructor
5824       // or a conversion function.
5825       CastKind CastKind;
5826       bool IsCopy = false;
5827       FunctionDecl *Fn = Step->Function.Function;
5828       DeclAccessPair FoundFn = Step->Function.FoundDecl;
5829       bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
5830       bool CreatedObject = false;
5831       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
5832         // Build a call to the selected constructor.
5833         SmallVector<Expr*, 8> ConstructorArgs;
5834         SourceLocation Loc = CurInit.get()->getLocStart();
5835         CurInit.release(); // Ownership transferred into MultiExprArg, below.
5836 
5837         // Determine the arguments required to actually perform the constructor
5838         // call.
5839         Expr *Arg = CurInit.get();
5840         if (S.CompleteConstructorCall(Constructor,
5841                                       MultiExprArg(&Arg, 1),
5842                                       Loc, ConstructorArgs))
5843           return ExprError();
5844 
5845         // Build an expression that constructs a temporary.
5846         CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
5847                                           ConstructorArgs,
5848                                           HadMultipleCandidates,
5849                                           /*ListInit*/ false,
5850                                           /*ZeroInit*/ false,
5851                                           CXXConstructExpr::CK_Complete,
5852                                           SourceRange());
5853         if (CurInit.isInvalid())
5854           return ExprError();
5855 
5856         S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
5857                                  FoundFn.getAccess());
5858         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5859           return ExprError();
5860 
5861         CastKind = CK_ConstructorConversion;
5862         QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5863         if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5864             S.IsDerivedFrom(SourceType, Class))
5865           IsCopy = true;
5866 
5867         CreatedObject = true;
5868       } else {
5869         // Build a call to the conversion function.
5870         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
5871         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
5872                                     FoundFn);
5873         if (S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation()))
5874           return ExprError();
5875 
5876         // FIXME: Should we move this initialization into a separate
5877         // derived-to-base conversion? I believe the answer is "no", because
5878         // we don't want to turn off access control here for c-style casts.
5879         ExprResult CurInitExprRes =
5880           S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5881                                                 FoundFn, Conversion);
5882         if(CurInitExprRes.isInvalid())
5883           return ExprError();
5884         CurInit = CurInitExprRes;
5885 
5886         // Build the actual call to the conversion function.
5887         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5888                                            HadMultipleCandidates);
5889         if (CurInit.isInvalid() || !CurInit.get())
5890           return ExprError();
5891 
5892         CastKind = CK_UserDefinedConversion;
5893 
5894         CreatedObject = Conversion->getReturnType()->isRecordType();
5895       }
5896 
5897       bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
5898       bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5899 
5900       if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
5901         QualType T = CurInit.get()->getType();
5902         if (const RecordType *Record = T->getAs<RecordType>()) {
5903           CXXDestructorDecl *Destructor
5904             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
5905           S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
5906                                   S.PDiag(diag::err_access_dtor_temp) << T);
5907           S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
5908           if (S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart()))
5909             return ExprError();
5910         }
5911       }
5912 
5913       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
5914                                                  CurInit.get()->getType(),
5915                                                  CastKind, CurInit.get(), 0,
5916                                                 CurInit.get()->getValueKind()));
5917       if (MaybeBindToTemp)
5918         CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
5919       if (RequiresCopy)
5920         CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5921                              CurInit, /*IsExtraneousCopy=*/false);
5922       break;
5923     }
5924 
5925     case SK_QualificationConversionLValue:
5926     case SK_QualificationConversionXValue:
5927     case SK_QualificationConversionRValue: {
5928       // Perform a qualification conversion; these can never go wrong.
5929       ExprValueKind VK =
5930           Step->Kind == SK_QualificationConversionLValue ?
5931               VK_LValue :
5932               (Step->Kind == SK_QualificationConversionXValue ?
5933                    VK_XValue :
5934                    VK_RValue);
5935       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
5936       break;
5937     }
5938 
5939     case SK_LValueToRValue: {
5940       assert(CurInit.get()->isGLValue() && "cannot load from a prvalue");
5941       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
5942                                                  CK_LValueToRValue,
5943                                                  CurInit.take(),
5944                                                  /*BasePath=*/0,
5945                                                  VK_RValue));
5946       break;
5947     }
5948 
5949     case SK_ConversionSequence:
5950     case SK_ConversionSequenceNoNarrowing: {
5951       Sema::CheckedConversionKind CCK
5952         = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5953         : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
5954         : Kind.isExplicitCast()? Sema::CCK_OtherCast
5955         : Sema::CCK_ImplicitConversion;
5956       ExprResult CurInitExprRes =
5957         S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
5958                                     getAssignmentAction(Entity), CCK);
5959       if (CurInitExprRes.isInvalid())
5960         return ExprError();
5961       CurInit = CurInitExprRes;
5962 
5963       if (Step->Kind == SK_ConversionSequenceNoNarrowing &&
5964           S.getLangOpts().CPlusPlus && !CurInit.get()->isValueDependent())
5965         DiagnoseNarrowingInInitList(S, *Step->ICS, SourceType, Entity.getType(),
5966                                     CurInit.get());
5967       break;
5968     }
5969 
5970     case SK_ListInitialization: {
5971       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5972       // If we're not initializing the top-level entity, we need to create an
5973       // InitializeTemporary entity for our target type.
5974       QualType Ty = Step->Type;
5975       bool IsTemporary = !S.Context.hasSameType(Entity.getType(), Ty);
5976       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5977       InitializedEntity InitEntity = IsTemporary ? TempEntity : Entity;
5978       InitListChecker PerformInitList(S, InitEntity,
5979           InitList, Ty, /*VerifyOnly=*/false);
5980       if (PerformInitList.HadError())
5981         return ExprError();
5982 
5983       // Hack: We must update *ResultType if available in order to set the
5984       // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5985       // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5986       if (ResultType &&
5987           ResultType->getNonReferenceType()->isIncompleteArrayType()) {
5988         if ((*ResultType)->isRValueReferenceType())
5989           Ty = S.Context.getRValueReferenceType(Ty);
5990         else if ((*ResultType)->isLValueReferenceType())
5991           Ty = S.Context.getLValueReferenceType(Ty,
5992             (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5993         *ResultType = Ty;
5994       }
5995 
5996       InitListExpr *StructuredInitList =
5997           PerformInitList.getFullyStructuredList();
5998       CurInit.release();
5999       CurInit = shouldBindAsTemporary(InitEntity)
6000           ? S.MaybeBindToTemporary(StructuredInitList)
6001           : S.Owned(StructuredInitList);
6002       break;
6003     }
6004 
6005     case SK_ListConstructorCall: {
6006       // When an initializer list is passed for a parameter of type "reference
6007       // to object", we don't get an EK_Temporary entity, but instead an
6008       // EK_Parameter entity with reference type.
6009       // FIXME: This is a hack. What we really should do is create a user
6010       // conversion step for this case, but this makes it considerably more
6011       // complicated. For now, this will do.
6012       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6013                                         Entity.getType().getNonReferenceType());
6014       bool UseTemporary = Entity.getType()->isReferenceType();
6015       assert(Args.size() == 1 && "expected a single argument for list init");
6016       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6017       S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
6018         << InitList->getSourceRange();
6019       MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
6020       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
6021                                                                    Entity,
6022                                                  Kind, Arg, *Step,
6023                                                ConstructorInitRequiresZeroInit,
6024                                                /*IsListInitialization*/ true,
6025                                                InitList->getLBraceLoc(),
6026                                                InitList->getRBraceLoc());
6027       break;
6028     }
6029 
6030     case SK_UnwrapInitList:
6031       CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
6032       break;
6033 
6034     case SK_RewrapInitList: {
6035       Expr *E = CurInit.take();
6036       InitListExpr *Syntactic = Step->WrappingSyntacticList;
6037       InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
6038           Syntactic->getLBraceLoc(), E, Syntactic->getRBraceLoc());
6039       ILE->setSyntacticForm(Syntactic);
6040       ILE->setType(E->getType());
6041       ILE->setValueKind(E->getValueKind());
6042       CurInit = S.Owned(ILE);
6043       break;
6044     }
6045 
6046     case SK_ConstructorInitialization: {
6047       // When an initializer list is passed for a parameter of type "reference
6048       // to object", we don't get an EK_Temporary entity, but instead an
6049       // EK_Parameter entity with reference type.
6050       // FIXME: This is a hack. What we really should do is create a user
6051       // conversion step for this case, but this makes it considerably more
6052       // complicated. For now, this will do.
6053       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
6054                                         Entity.getType().getNonReferenceType());
6055       bool UseTemporary = Entity.getType()->isReferenceType();
6056       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
6057                                                                  : Entity,
6058                                                  Kind, Args, *Step,
6059                                                ConstructorInitRequiresZeroInit,
6060                                                /*IsListInitialization*/ false,
6061                                                /*LBraceLoc*/ SourceLocation(),
6062                                                /*RBraceLoc*/ SourceLocation());
6063       break;
6064     }
6065 
6066     case SK_ZeroInitialization: {
6067       step_iterator NextStep = Step;
6068       ++NextStep;
6069       if (NextStep != StepEnd &&
6070           (NextStep->Kind == SK_ConstructorInitialization ||
6071            NextStep->Kind == SK_ListConstructorCall)) {
6072         // The need for zero-initialization is recorded directly into
6073         // the call to the object's constructor within the next step.
6074         ConstructorInitRequiresZeroInit = true;
6075       } else if (Kind.getKind() == InitializationKind::IK_Value &&
6076                  S.getLangOpts().CPlusPlus &&
6077                  !Kind.isImplicitValueInit()) {
6078         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
6079         if (!TSInfo)
6080           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
6081                                                     Kind.getRange().getBegin());
6082 
6083         CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
6084                               TSInfo->getType().getNonLValueExprType(S.Context),
6085                                                                  TSInfo,
6086                                                     Kind.getRange().getEnd()));
6087       } else {
6088         CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
6089       }
6090       break;
6091     }
6092 
6093     case SK_CAssignment: {
6094       QualType SourceType = CurInit.get()->getType();
6095       ExprResult Result = CurInit;
6096       Sema::AssignConvertType ConvTy =
6097         S.CheckSingleAssignmentConstraints(Step->Type, Result, true,
6098             Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited);
6099       if (Result.isInvalid())
6100         return ExprError();
6101       CurInit = Result;
6102 
6103       // If this is a call, allow conversion to a transparent union.
6104       ExprResult CurInitExprRes = CurInit;
6105       if (ConvTy != Sema::Compatible &&
6106           Entity.isParameterKind() &&
6107           S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
6108             == Sema::Compatible)
6109         ConvTy = Sema::Compatible;
6110       if (CurInitExprRes.isInvalid())
6111         return ExprError();
6112       CurInit = CurInitExprRes;
6113 
6114       bool Complained;
6115       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
6116                                      Step->Type, SourceType,
6117                                      CurInit.get(),
6118                                      getAssignmentAction(Entity, true),
6119                                      &Complained)) {
6120         PrintInitLocationNote(S, Entity);
6121         return ExprError();
6122       } else if (Complained)
6123         PrintInitLocationNote(S, Entity);
6124       break;
6125     }
6126 
6127     case SK_StringInit: {
6128       QualType Ty = Step->Type;
6129       CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
6130                       S.Context.getAsArrayType(Ty), S);
6131       break;
6132     }
6133 
6134     case SK_ObjCObjectConversion:
6135       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6136                           CK_ObjCObjectLValueCast,
6137                           CurInit.get()->getValueKind());
6138       break;
6139 
6140     case SK_ArrayInit:
6141       // Okay: we checked everything before creating this step. Note that
6142       // this is a GNU extension.
6143       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
6144         << Step->Type << CurInit.get()->getType()
6145         << CurInit.get()->getSourceRange();
6146 
6147       // If the destination type is an incomplete array type, update the
6148       // type accordingly.
6149       if (ResultType) {
6150         if (const IncompleteArrayType *IncompleteDest
6151                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
6152           if (const ConstantArrayType *ConstantSource
6153                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
6154             *ResultType = S.Context.getConstantArrayType(
6155                                              IncompleteDest->getElementType(),
6156                                              ConstantSource->getSize(),
6157                                              ArrayType::Normal, 0);
6158           }
6159         }
6160       }
6161       break;
6162 
6163     case SK_ParenthesizedArrayInit:
6164       // Okay: we checked everything before creating this step. Note that
6165       // this is a GNU extension.
6166       S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
6167         << CurInit.get()->getSourceRange();
6168       break;
6169 
6170     case SK_PassByIndirectCopyRestore:
6171     case SK_PassByIndirectRestore:
6172       checkIndirectCopyRestoreSource(S, CurInit.get());
6173       CurInit = S.Owned(new (S.Context)
6174                         ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
6175                                 Step->Kind == SK_PassByIndirectCopyRestore));
6176       break;
6177 
6178     case SK_ProduceObjCObject:
6179       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
6180                                                  CK_ARCProduceObject,
6181                                                  CurInit.take(), 0, VK_RValue));
6182       break;
6183 
6184     case SK_StdInitializerList: {
6185       S.Diag(CurInit.get()->getExprLoc(),
6186              diag::warn_cxx98_compat_initializer_list_init)
6187         << CurInit.get()->getSourceRange();
6188 
6189       // Maybe lifetime-extend the array temporary's subobjects to match the
6190       // entity's lifetime.
6191       const ValueDecl *ExtendingDecl =
6192           getDeclForTemporaryLifetimeExtension(Entity);
6193       if (ExtendingDecl) {
6194         performLifetimeExtension(CurInit.get(), ExtendingDecl);
6195         warnOnLifetimeExtension(S, Entity, CurInit.get(), true, ExtendingDecl);
6196       }
6197 
6198       // Materialize the temporary into memory.
6199       MaterializeTemporaryExpr *MTE = new (S.Context)
6200           MaterializeTemporaryExpr(CurInit.get()->getType(), CurInit.get(),
6201                                    /*lvalue reference*/ false, ExtendingDecl);
6202 
6203       // Wrap it in a construction of a std::initializer_list<T>.
6204       CurInit = S.Owned(
6205           new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE));
6206 
6207       // Bind the result, in case the library has given initializer_list a
6208       // non-trivial destructor.
6209       if (shouldBindAsTemporary(Entity))
6210         CurInit = S.MaybeBindToTemporary(CurInit.take());
6211       break;
6212     }
6213 
6214     case SK_OCLSamplerInit: {
6215       assert(Step->Type->isSamplerT() &&
6216              "Sampler initialization on non-sampler type.");
6217 
6218       QualType SourceType = CurInit.get()->getType();
6219 
6220       if (Entity.isParameterKind()) {
6221         if (!SourceType->isSamplerT())
6222           S.Diag(Kind.getLocation(), diag::err_sampler_argument_required)
6223             << SourceType;
6224       } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
6225         llvm_unreachable("Invalid EntityKind!");
6226       }
6227 
6228       break;
6229     }
6230     case SK_OCLZeroEvent: {
6231       assert(Step->Type->isEventT() &&
6232              "Event initialization on non-event type.");
6233 
6234       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
6235                                     CK_ZeroToOCLEvent,
6236                                     CurInit.get()->getValueKind());
6237       break;
6238     }
6239     }
6240   }
6241 
6242   // Diagnose non-fatal problems with the completed initialization.
6243   if (Entity.getKind() == InitializedEntity::EK_Member &&
6244       cast<FieldDecl>(Entity.getDecl())->isBitField())
6245     S.CheckBitFieldInitialization(Kind.getLocation(),
6246                                   cast<FieldDecl>(Entity.getDecl()),
6247                                   CurInit.get());
6248 
6249   return CurInit;
6250 }
6251 
6252 /// Somewhere within T there is an uninitialized reference subobject.
6253 /// Dig it out and diagnose it.
6254 static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc,
6255                                            QualType T) {
6256   if (T->isReferenceType()) {
6257     S.Diag(Loc, diag::err_reference_without_init)
6258       << T.getNonReferenceType();
6259     return true;
6260   }
6261 
6262   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6263   if (!RD || !RD->hasUninitializedReferenceMember())
6264     return false;
6265 
6266   for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
6267                                      FE = RD->field_end(); FI != FE; ++FI) {
6268     if (FI->isUnnamedBitfield())
6269       continue;
6270 
6271     if (DiagnoseUninitializedReference(S, FI->getLocation(), FI->getType())) {
6272       S.Diag(Loc, diag::note_value_initialization_here) << RD;
6273       return true;
6274     }
6275   }
6276 
6277   for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
6278                                           BE = RD->bases_end();
6279        BI != BE; ++BI) {
6280     if (DiagnoseUninitializedReference(S, BI->getLocStart(), BI->getType())) {
6281       S.Diag(Loc, diag::note_value_initialization_here) << RD;
6282       return true;
6283     }
6284   }
6285 
6286   return false;
6287 }
6288 
6289 
6290 //===----------------------------------------------------------------------===//
6291 // Diagnose initialization failures
6292 //===----------------------------------------------------------------------===//
6293 
6294 /// Emit notes associated with an initialization that failed due to a
6295 /// "simple" conversion failure.
6296 static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity,
6297                                    Expr *op) {
6298   QualType destType = entity.getType();
6299   if (destType.getNonReferenceType()->isObjCObjectPointerType() &&
6300       op->getType()->isObjCObjectPointerType()) {
6301 
6302     // Emit a possible note about the conversion failing because the
6303     // operand is a message send with a related result type.
6304     S.EmitRelatedResultTypeNote(op);
6305 
6306     // Emit a possible note about a return failing because we're
6307     // expecting a related result type.
6308     if (entity.getKind() == InitializedEntity::EK_Result)
6309       S.EmitRelatedResultTypeNoteForReturn(destType);
6310   }
6311 }
6312 
6313 static void diagnoseListInit(Sema &S, const InitializedEntity &Entity,
6314                              InitListExpr *InitList) {
6315   QualType DestType = Entity.getType();
6316 
6317   QualType E;
6318   if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(DestType, &E)) {
6319     QualType ArrayType = S.Context.getConstantArrayType(
6320         E.withConst(),
6321         llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
6322                     InitList->getNumInits()),
6323         clang::ArrayType::Normal, 0);
6324     InitializedEntity HiddenArray =
6325         InitializedEntity::InitializeTemporary(ArrayType);
6326     return diagnoseListInit(S, HiddenArray, InitList);
6327   }
6328 
6329   InitListChecker DiagnoseInitList(S, Entity, InitList, DestType,
6330                                    /*VerifyOnly=*/false);
6331   assert(DiagnoseInitList.HadError() &&
6332          "Inconsistent init list check result.");
6333 }
6334 
6335 bool InitializationSequence::Diagnose(Sema &S,
6336                                       const InitializedEntity &Entity,
6337                                       const InitializationKind &Kind,
6338                                       ArrayRef<Expr *> Args) {
6339   if (!Failed())
6340     return false;
6341 
6342   QualType DestType = Entity.getType();
6343   switch (Failure) {
6344   case FK_TooManyInitsForReference:
6345     // FIXME: Customize for the initialized entity?
6346     if (Args.empty()) {
6347       // Dig out the reference subobject which is uninitialized and diagnose it.
6348       // If this is value-initialization, this could be nested some way within
6349       // the target type.
6350       assert(Kind.getKind() == InitializationKind::IK_Value ||
6351              DestType->isReferenceType());
6352       bool Diagnosed =
6353         DiagnoseUninitializedReference(S, Kind.getLocation(), DestType);
6354       assert(Diagnosed && "couldn't find uninitialized reference to diagnose");
6355       (void)Diagnosed;
6356     } else  // FIXME: diagnostic below could be better!
6357       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
6358         << SourceRange(Args.front()->getLocStart(), Args.back()->getLocEnd());
6359     break;
6360 
6361   case FK_ArrayNeedsInitList:
6362     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 0;
6363     break;
6364   case FK_ArrayNeedsInitListOrStringLiteral:
6365     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 1;
6366     break;
6367   case FK_ArrayNeedsInitListOrWideStringLiteral:
6368     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list) << 2;
6369     break;
6370   case FK_NarrowStringIntoWideCharArray:
6371     S.Diag(Kind.getLocation(), diag::err_array_init_narrow_string_into_wchar);
6372     break;
6373   case FK_WideStringIntoCharArray:
6374     S.Diag(Kind.getLocation(), diag::err_array_init_wide_string_into_char);
6375     break;
6376   case FK_IncompatWideStringIntoWideChar:
6377     S.Diag(Kind.getLocation(),
6378            diag::err_array_init_incompat_wide_string_into_wchar);
6379     break;
6380   case FK_ArrayTypeMismatch:
6381   case FK_NonConstantArrayInit:
6382     S.Diag(Kind.getLocation(),
6383            (Failure == FK_ArrayTypeMismatch
6384               ? diag::err_array_init_different_type
6385               : diag::err_array_init_non_constant_array))
6386       << DestType.getNonReferenceType()
6387       << Args[0]->getType()
6388       << Args[0]->getSourceRange();
6389     break;
6390 
6391   case FK_VariableLengthArrayHasInitializer:
6392     S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
6393       << Args[0]->getSourceRange();
6394     break;
6395 
6396   case FK_AddressOfOverloadFailed: {
6397     DeclAccessPair Found;
6398     S.ResolveAddressOfOverloadedFunction(Args[0],
6399                                          DestType.getNonReferenceType(),
6400                                          true,
6401                                          Found);
6402     break;
6403   }
6404 
6405   case FK_ReferenceInitOverloadFailed:
6406   case FK_UserConversionOverloadFailed:
6407     switch (FailedOverloadResult) {
6408     case OR_Ambiguous:
6409       if (Failure == FK_UserConversionOverloadFailed)
6410         S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
6411           << Args[0]->getType() << DestType
6412           << Args[0]->getSourceRange();
6413       else
6414         S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
6415           << DestType << Args[0]->getType()
6416           << Args[0]->getSourceRange();
6417 
6418       FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6419       break;
6420 
6421     case OR_No_Viable_Function:
6422       if (!S.RequireCompleteType(Kind.getLocation(),
6423                                  DestType.getNonReferenceType(),
6424                           diag::err_typecheck_nonviable_condition_incomplete,
6425                                Args[0]->getType(), Args[0]->getSourceRange()))
6426         S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
6427           << Args[0]->getType() << Args[0]->getSourceRange()
6428           << DestType.getNonReferenceType();
6429 
6430       FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6431       break;
6432 
6433     case OR_Deleted: {
6434       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
6435         << Args[0]->getType() << DestType.getNonReferenceType()
6436         << Args[0]->getSourceRange();
6437       OverloadCandidateSet::iterator Best;
6438       OverloadingResult Ovl
6439         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
6440                                                 true);
6441       if (Ovl == OR_Deleted) {
6442         S.NoteDeletedFunction(Best->Function);
6443       } else {
6444         llvm_unreachable("Inconsistent overload resolution?");
6445       }
6446       break;
6447     }
6448 
6449     case OR_Success:
6450       llvm_unreachable("Conversion did not fail!");
6451     }
6452     break;
6453 
6454   case FK_NonConstLValueReferenceBindingToTemporary:
6455     if (isa<InitListExpr>(Args[0])) {
6456       S.Diag(Kind.getLocation(),
6457              diag::err_lvalue_reference_bind_to_initlist)
6458       << DestType.getNonReferenceType().isVolatileQualified()
6459       << DestType.getNonReferenceType()
6460       << Args[0]->getSourceRange();
6461       break;
6462     }
6463     // Intentional fallthrough
6464 
6465   case FK_NonConstLValueReferenceBindingToUnrelated:
6466     S.Diag(Kind.getLocation(),
6467            Failure == FK_NonConstLValueReferenceBindingToTemporary
6468              ? diag::err_lvalue_reference_bind_to_temporary
6469              : diag::err_lvalue_reference_bind_to_unrelated)
6470       << DestType.getNonReferenceType().isVolatileQualified()
6471       << DestType.getNonReferenceType()
6472       << Args[0]->getType()
6473       << Args[0]->getSourceRange();
6474     break;
6475 
6476   case FK_RValueReferenceBindingToLValue:
6477     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
6478       << DestType.getNonReferenceType() << Args[0]->getType()
6479       << Args[0]->getSourceRange();
6480     break;
6481 
6482   case FK_ReferenceInitDropsQualifiers:
6483     S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
6484       << DestType.getNonReferenceType()
6485       << Args[0]->getType()
6486       << Args[0]->getSourceRange();
6487     break;
6488 
6489   case FK_ReferenceInitFailed:
6490     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
6491       << DestType.getNonReferenceType()
6492       << Args[0]->isLValue()
6493       << Args[0]->getType()
6494       << Args[0]->getSourceRange();
6495     emitBadConversionNotes(S, Entity, Args[0]);
6496     break;
6497 
6498   case FK_ConversionFailed: {
6499     QualType FromType = Args[0]->getType();
6500     PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
6501       << (int)Entity.getKind()
6502       << DestType
6503       << Args[0]->isLValue()
6504       << FromType
6505       << Args[0]->getSourceRange();
6506     S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
6507     S.Diag(Kind.getLocation(), PDiag);
6508     emitBadConversionNotes(S, Entity, Args[0]);
6509     break;
6510   }
6511 
6512   case FK_ConversionFromPropertyFailed:
6513     // No-op. This error has already been reported.
6514     break;
6515 
6516   case FK_TooManyInitsForScalar: {
6517     SourceRange R;
6518 
6519     if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
6520       R = SourceRange(InitList->getInit(0)->getLocEnd(),
6521                       InitList->getLocEnd());
6522     else
6523       R = SourceRange(Args.front()->getLocEnd(), Args.back()->getLocEnd());
6524 
6525     R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
6526     if (Kind.isCStyleOrFunctionalCast())
6527       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
6528         << R;
6529     else
6530       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
6531         << /*scalar=*/2 << R;
6532     break;
6533   }
6534 
6535   case FK_ReferenceBindingToInitList:
6536     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
6537       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
6538     break;
6539 
6540   case FK_InitListBadDestinationType:
6541     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
6542       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
6543     break;
6544 
6545   case FK_ListConstructorOverloadFailed:
6546   case FK_ConstructorOverloadFailed: {
6547     SourceRange ArgsRange;
6548     if (Args.size())
6549       ArgsRange = SourceRange(Args.front()->getLocStart(),
6550                               Args.back()->getLocEnd());
6551 
6552     if (Failure == FK_ListConstructorOverloadFailed) {
6553       assert(Args.size() == 1 && "List construction from other than 1 argument.");
6554       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6555       Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
6556     }
6557 
6558     // FIXME: Using "DestType" for the entity we're printing is probably
6559     // bad.
6560     switch (FailedOverloadResult) {
6561       case OR_Ambiguous:
6562         S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
6563           << DestType << ArgsRange;
6564         FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args);
6565         break;
6566 
6567       case OR_No_Viable_Function:
6568         if (Kind.getKind() == InitializationKind::IK_Default &&
6569             (Entity.getKind() == InitializedEntity::EK_Base ||
6570              Entity.getKind() == InitializedEntity::EK_Member) &&
6571             isa<CXXConstructorDecl>(S.CurContext)) {
6572           // This is implicit default initialization of a member or
6573           // base within a constructor. If no viable function was
6574           // found, notify the user that she needs to explicitly
6575           // initialize this base/member.
6576           CXXConstructorDecl *Constructor
6577             = cast<CXXConstructorDecl>(S.CurContext);
6578           if (Entity.getKind() == InitializedEntity::EK_Base) {
6579             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6580               << (Constructor->getInheritedConstructor() ? 2 :
6581                   Constructor->isImplicit() ? 1 : 0)
6582               << S.Context.getTypeDeclType(Constructor->getParent())
6583               << /*base=*/0
6584               << Entity.getType();
6585 
6586             RecordDecl *BaseDecl
6587               = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
6588                                                                   ->getDecl();
6589             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
6590               << S.Context.getTagDeclType(BaseDecl);
6591           } else {
6592             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
6593               << (Constructor->getInheritedConstructor() ? 2 :
6594                   Constructor->isImplicit() ? 1 : 0)
6595               << S.Context.getTypeDeclType(Constructor->getParent())
6596               << /*member=*/1
6597               << Entity.getName();
6598             S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
6599 
6600             if (const RecordType *Record
6601                                  = Entity.getType()->getAs<RecordType>())
6602               S.Diag(Record->getDecl()->getLocation(),
6603                      diag::note_previous_decl)
6604                 << S.Context.getTagDeclType(Record->getDecl());
6605           }
6606           break;
6607         }
6608 
6609         S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
6610           << DestType << ArgsRange;
6611         FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args);
6612         break;
6613 
6614       case OR_Deleted: {
6615         OverloadCandidateSet::iterator Best;
6616         OverloadingResult Ovl
6617           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6618         if (Ovl != OR_Deleted) {
6619           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6620             << true << DestType << ArgsRange;
6621           llvm_unreachable("Inconsistent overload resolution?");
6622           break;
6623         }
6624 
6625         // If this is a defaulted or implicitly-declared function, then
6626         // it was implicitly deleted. Make it clear that the deletion was
6627         // implicit.
6628         if (S.isImplicitlyDeleted(Best->Function))
6629           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
6630             << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
6631             << DestType << ArgsRange;
6632         else
6633           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
6634             << true << DestType << ArgsRange;
6635 
6636         S.NoteDeletedFunction(Best->Function);
6637         break;
6638       }
6639 
6640       case OR_Success:
6641         llvm_unreachable("Conversion did not fail!");
6642     }
6643   }
6644   break;
6645 
6646   case FK_DefaultInitOfConst:
6647     if (Entity.getKind() == InitializedEntity::EK_Member &&
6648         isa<CXXConstructorDecl>(S.CurContext)) {
6649       // This is implicit default-initialization of a const member in
6650       // a constructor. Complain that it needs to be explicitly
6651       // initialized.
6652       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
6653       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
6654         << (Constructor->getInheritedConstructor() ? 2 :
6655             Constructor->isImplicit() ? 1 : 0)
6656         << S.Context.getTypeDeclType(Constructor->getParent())
6657         << /*const=*/1
6658         << Entity.getName();
6659       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
6660         << Entity.getName();
6661     } else {
6662       S.Diag(Kind.getLocation(), diag::err_default_init_const)
6663         << DestType << (bool)DestType->getAs<RecordType>();
6664     }
6665     break;
6666 
6667   case FK_Incomplete:
6668     S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
6669                           diag::err_init_incomplete_type);
6670     break;
6671 
6672   case FK_ListInitializationFailed: {
6673     // Run the init list checker again to emit diagnostics.
6674     InitListExpr *InitList = cast<InitListExpr>(Args[0]);
6675     diagnoseListInit(S, Entity, InitList);
6676     break;
6677   }
6678 
6679   case FK_PlaceholderType: {
6680     // FIXME: Already diagnosed!
6681     break;
6682   }
6683 
6684   case FK_ExplicitConstructor: {
6685     S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
6686       << Args[0]->getSourceRange();
6687     OverloadCandidateSet::iterator Best;
6688     OverloadingResult Ovl
6689       = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
6690     (void)Ovl;
6691     assert(Ovl == OR_Success && "Inconsistent overload resolution");
6692     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
6693     S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
6694     break;
6695   }
6696   }
6697 
6698   PrintInitLocationNote(S, Entity);
6699   return true;
6700 }
6701 
6702 void InitializationSequence::dump(raw_ostream &OS) const {
6703   switch (SequenceKind) {
6704   case FailedSequence: {
6705     OS << "Failed sequence: ";
6706     switch (Failure) {
6707     case FK_TooManyInitsForReference:
6708       OS << "too many initializers for reference";
6709       break;
6710 
6711     case FK_ArrayNeedsInitList:
6712       OS << "array requires initializer list";
6713       break;
6714 
6715     case FK_ArrayNeedsInitListOrStringLiteral:
6716       OS << "array requires initializer list or string literal";
6717       break;
6718 
6719     case FK_ArrayNeedsInitListOrWideStringLiteral:
6720       OS << "array requires initializer list or wide string literal";
6721       break;
6722 
6723     case FK_NarrowStringIntoWideCharArray:
6724       OS << "narrow string into wide char array";
6725       break;
6726 
6727     case FK_WideStringIntoCharArray:
6728       OS << "wide string into char array";
6729       break;
6730 
6731     case FK_IncompatWideStringIntoWideChar:
6732       OS << "incompatible wide string into wide char array";
6733       break;
6734 
6735     case FK_ArrayTypeMismatch:
6736       OS << "array type mismatch";
6737       break;
6738 
6739     case FK_NonConstantArrayInit:
6740       OS << "non-constant array initializer";
6741       break;
6742 
6743     case FK_AddressOfOverloadFailed:
6744       OS << "address of overloaded function failed";
6745       break;
6746 
6747     case FK_ReferenceInitOverloadFailed:
6748       OS << "overload resolution for reference initialization failed";
6749       break;
6750 
6751     case FK_NonConstLValueReferenceBindingToTemporary:
6752       OS << "non-const lvalue reference bound to temporary";
6753       break;
6754 
6755     case FK_NonConstLValueReferenceBindingToUnrelated:
6756       OS << "non-const lvalue reference bound to unrelated type";
6757       break;
6758 
6759     case FK_RValueReferenceBindingToLValue:
6760       OS << "rvalue reference bound to an lvalue";
6761       break;
6762 
6763     case FK_ReferenceInitDropsQualifiers:
6764       OS << "reference initialization drops qualifiers";
6765       break;
6766 
6767     case FK_ReferenceInitFailed:
6768       OS << "reference initialization failed";
6769       break;
6770 
6771     case FK_ConversionFailed:
6772       OS << "conversion failed";
6773       break;
6774 
6775     case FK_ConversionFromPropertyFailed:
6776       OS << "conversion from property failed";
6777       break;
6778 
6779     case FK_TooManyInitsForScalar:
6780       OS << "too many initializers for scalar";
6781       break;
6782 
6783     case FK_ReferenceBindingToInitList:
6784       OS << "referencing binding to initializer list";
6785       break;
6786 
6787     case FK_InitListBadDestinationType:
6788       OS << "initializer list for non-aggregate, non-scalar type";
6789       break;
6790 
6791     case FK_UserConversionOverloadFailed:
6792       OS << "overloading failed for user-defined conversion";
6793       break;
6794 
6795     case FK_ConstructorOverloadFailed:
6796       OS << "constructor overloading failed";
6797       break;
6798 
6799     case FK_DefaultInitOfConst:
6800       OS << "default initialization of a const variable";
6801       break;
6802 
6803     case FK_Incomplete:
6804       OS << "initialization of incomplete type";
6805       break;
6806 
6807     case FK_ListInitializationFailed:
6808       OS << "list initialization checker failure";
6809       break;
6810 
6811     case FK_VariableLengthArrayHasInitializer:
6812       OS << "variable length array has an initializer";
6813       break;
6814 
6815     case FK_PlaceholderType:
6816       OS << "initializer expression isn't contextually valid";
6817       break;
6818 
6819     case FK_ListConstructorOverloadFailed:
6820       OS << "list constructor overloading failed";
6821       break;
6822 
6823     case FK_ExplicitConstructor:
6824       OS << "list copy initialization chose explicit constructor";
6825       break;
6826     }
6827     OS << '\n';
6828     return;
6829   }
6830 
6831   case DependentSequence:
6832     OS << "Dependent sequence\n";
6833     return;
6834 
6835   case NormalSequence:
6836     OS << "Normal sequence: ";
6837     break;
6838   }
6839 
6840   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
6841     if (S != step_begin()) {
6842       OS << " -> ";
6843     }
6844 
6845     switch (S->Kind) {
6846     case SK_ResolveAddressOfOverloadedFunction:
6847       OS << "resolve address of overloaded function";
6848       break;
6849 
6850     case SK_CastDerivedToBaseRValue:
6851       OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
6852       break;
6853 
6854     case SK_CastDerivedToBaseXValue:
6855       OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
6856       break;
6857 
6858     case SK_CastDerivedToBaseLValue:
6859       OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
6860       break;
6861 
6862     case SK_BindReference:
6863       OS << "bind reference to lvalue";
6864       break;
6865 
6866     case SK_BindReferenceToTemporary:
6867       OS << "bind reference to a temporary";
6868       break;
6869 
6870     case SK_ExtraneousCopyToTemporary:
6871       OS << "extraneous C++03 copy to temporary";
6872       break;
6873 
6874     case SK_UserConversion:
6875       OS << "user-defined conversion via " << *S->Function.Function;
6876       break;
6877 
6878     case SK_QualificationConversionRValue:
6879       OS << "qualification conversion (rvalue)";
6880       break;
6881 
6882     case SK_QualificationConversionXValue:
6883       OS << "qualification conversion (xvalue)";
6884       break;
6885 
6886     case SK_QualificationConversionLValue:
6887       OS << "qualification conversion (lvalue)";
6888       break;
6889 
6890     case SK_LValueToRValue:
6891       OS << "load (lvalue to rvalue)";
6892       break;
6893 
6894     case SK_ConversionSequence:
6895       OS << "implicit conversion sequence (";
6896       S->ICS->dump(); // FIXME: use OS
6897       OS << ")";
6898       break;
6899 
6900     case SK_ConversionSequenceNoNarrowing:
6901       OS << "implicit conversion sequence with narrowing prohibited (";
6902       S->ICS->dump(); // FIXME: use OS
6903       OS << ")";
6904       break;
6905 
6906     case SK_ListInitialization:
6907       OS << "list aggregate initialization";
6908       break;
6909 
6910     case SK_ListConstructorCall:
6911       OS << "list initialization via constructor";
6912       break;
6913 
6914     case SK_UnwrapInitList:
6915       OS << "unwrap reference initializer list";
6916       break;
6917 
6918     case SK_RewrapInitList:
6919       OS << "rewrap reference initializer list";
6920       break;
6921 
6922     case SK_ConstructorInitialization:
6923       OS << "constructor initialization";
6924       break;
6925 
6926     case SK_ZeroInitialization:
6927       OS << "zero initialization";
6928       break;
6929 
6930     case SK_CAssignment:
6931       OS << "C assignment";
6932       break;
6933 
6934     case SK_StringInit:
6935       OS << "string initialization";
6936       break;
6937 
6938     case SK_ObjCObjectConversion:
6939       OS << "Objective-C object conversion";
6940       break;
6941 
6942     case SK_ArrayInit:
6943       OS << "array initialization";
6944       break;
6945 
6946     case SK_ParenthesizedArrayInit:
6947       OS << "parenthesized array initialization";
6948       break;
6949 
6950     case SK_PassByIndirectCopyRestore:
6951       OS << "pass by indirect copy and restore";
6952       break;
6953 
6954     case SK_PassByIndirectRestore:
6955       OS << "pass by indirect restore";
6956       break;
6957 
6958     case SK_ProduceObjCObject:
6959       OS << "Objective-C object retension";
6960       break;
6961 
6962     case SK_StdInitializerList:
6963       OS << "std::initializer_list from initializer list";
6964       break;
6965 
6966     case SK_OCLSamplerInit:
6967       OS << "OpenCL sampler_t from integer constant";
6968       break;
6969 
6970     case SK_OCLZeroEvent:
6971       OS << "OpenCL event_t from zero";
6972       break;
6973     }
6974 
6975     OS << " [" << S->Type.getAsString() << ']';
6976   }
6977 
6978   OS << '\n';
6979 }
6980 
6981 void InitializationSequence::dump() const {
6982   dump(llvm::errs());
6983 }
6984 
6985 static void DiagnoseNarrowingInInitList(Sema &S,
6986                                         const ImplicitConversionSequence &ICS,
6987                                         QualType PreNarrowingType,
6988                                         QualType EntityType,
6989                                         const Expr *PostInit) {
6990   const StandardConversionSequence *SCS = 0;
6991   switch (ICS.getKind()) {
6992   case ImplicitConversionSequence::StandardConversion:
6993     SCS = &ICS.Standard;
6994     break;
6995   case ImplicitConversionSequence::UserDefinedConversion:
6996     SCS = &ICS.UserDefined.After;
6997     break;
6998   case ImplicitConversionSequence::AmbiguousConversion:
6999   case ImplicitConversionSequence::EllipsisConversion:
7000   case ImplicitConversionSequence::BadConversion:
7001     return;
7002   }
7003 
7004   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
7005   APValue ConstantValue;
7006   QualType ConstantType;
7007   switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
7008                                 ConstantType)) {
7009   case NK_Not_Narrowing:
7010     // No narrowing occurred.
7011     return;
7012 
7013   case NK_Type_Narrowing:
7014     // This was a floating-to-integer conversion, which is always considered a
7015     // narrowing conversion even if the value is a constant and can be
7016     // represented exactly as an integer.
7017     S.Diag(PostInit->getLocStart(),
7018            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7019                ? diag::warn_init_list_type_narrowing
7020                : diag::ext_init_list_type_narrowing)
7021       << PostInit->getSourceRange()
7022       << PreNarrowingType.getLocalUnqualifiedType()
7023       << EntityType.getLocalUnqualifiedType();
7024     break;
7025 
7026   case NK_Constant_Narrowing:
7027     // A constant value was narrowed.
7028     S.Diag(PostInit->getLocStart(),
7029            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7030                ? diag::warn_init_list_constant_narrowing
7031                : diag::ext_init_list_constant_narrowing)
7032       << PostInit->getSourceRange()
7033       << ConstantValue.getAsString(S.getASTContext(), ConstantType)
7034       << EntityType.getLocalUnqualifiedType();
7035     break;
7036 
7037   case NK_Variable_Narrowing:
7038     // A variable's value may have been narrowed.
7039     S.Diag(PostInit->getLocStart(),
7040            (S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus11)
7041                ? diag::warn_init_list_variable_narrowing
7042                : diag::ext_init_list_variable_narrowing)
7043       << PostInit->getSourceRange()
7044       << PreNarrowingType.getLocalUnqualifiedType()
7045       << EntityType.getLocalUnqualifiedType();
7046     break;
7047   }
7048 
7049   SmallString<128> StaticCast;
7050   llvm::raw_svector_ostream OS(StaticCast);
7051   OS << "static_cast<";
7052   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
7053     // It's important to use the typedef's name if there is one so that the
7054     // fixit doesn't break code using types like int64_t.
7055     //
7056     // FIXME: This will break if the typedef requires qualification.  But
7057     // getQualifiedNameAsString() includes non-machine-parsable components.
7058     OS << *TT->getDecl();
7059   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
7060     OS << BT->getName(S.getLangOpts());
7061   else {
7062     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
7063     // with a broken cast.
7064     return;
7065   }
7066   OS << ">(";
7067   S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
7068     << PostInit->getSourceRange()
7069     << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
7070     << FixItHint::CreateInsertion(
7071       S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
7072 }
7073 
7074 //===----------------------------------------------------------------------===//
7075 // Initialization helper functions
7076 //===----------------------------------------------------------------------===//
7077 bool
7078 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
7079                                    ExprResult Init) {
7080   if (Init.isInvalid())
7081     return false;
7082 
7083   Expr *InitE = Init.get();
7084   assert(InitE && "No initialization expression");
7085 
7086   InitializationKind Kind
7087     = InitializationKind::CreateCopy(InitE->getLocStart(), SourceLocation());
7088   InitializationSequence Seq(*this, Entity, Kind, InitE);
7089   return !Seq.Failed();
7090 }
7091 
7092 ExprResult
7093 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
7094                                 SourceLocation EqualLoc,
7095                                 ExprResult Init,
7096                                 bool TopLevelOfInitList,
7097                                 bool AllowExplicit) {
7098   if (Init.isInvalid())
7099     return ExprError();
7100 
7101   Expr *InitE = Init.get();
7102   assert(InitE && "No initialization expression?");
7103 
7104   if (EqualLoc.isInvalid())
7105     EqualLoc = InitE->getLocStart();
7106 
7107   InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
7108                                                            EqualLoc,
7109                                                            AllowExplicit);
7110   InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList);
7111   Init.release();
7112 
7113   ExprResult Result = Seq.Perform(*this, Entity, Kind, InitE);
7114 
7115   return Result;
7116 }
7117