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