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