clang API Documentation

SemaInit.cpp
Go to the documentation of this file.
00001 //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements semantic analysis for initializers.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/Designator.h"
00015 #include "clang/Sema/Initialization.h"
00016 #include "clang/Sema/Lookup.h"
00017 #include "clang/Sema/SemaInternal.h"
00018 #include "clang/Lex/Preprocessor.h"
00019 #include "clang/AST/ASTContext.h"
00020 #include "clang/AST/DeclObjC.h"
00021 #include "clang/AST/ExprCXX.h"
00022 #include "clang/AST/ExprObjC.h"
00023 #include "clang/AST/TypeLoc.h"
00024 #include "llvm/ADT/APInt.h"
00025 #include "llvm/ADT/SmallString.h"
00026 #include "llvm/Support/ErrorHandling.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include <map>
00029 using namespace clang;
00030 
00031 //===----------------------------------------------------------------------===//
00032 // Sema Initialization Checking
00033 //===----------------------------------------------------------------------===//
00034 
00035 static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
00036                           ASTContext &Context) {
00037   if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
00038     return 0;
00039 
00040   // See if this is a string literal or @encode.
00041   Init = Init->IgnoreParens();
00042 
00043   // Handle @encode, which is a narrow string.
00044   if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
00045     return Init;
00046 
00047   // Otherwise we can only handle string literals.
00048   StringLiteral *SL = dyn_cast<StringLiteral>(Init);
00049   if (SL == 0) return 0;
00050 
00051   QualType ElemTy = Context.getCanonicalType(AT->getElementType());
00052 
00053   switch (SL->getKind()) {
00054   case StringLiteral::Ascii:
00055   case StringLiteral::UTF8:
00056     // char array can be initialized with a narrow string.
00057     // Only allow char x[] = "foo";  not char x[] = L"foo";
00058     return ElemTy->isCharType() ? Init : 0;
00059   case StringLiteral::UTF16:
00060     return ElemTy->isChar16Type() ? Init : 0;
00061   case StringLiteral::UTF32:
00062     return ElemTy->isChar32Type() ? Init : 0;
00063   case StringLiteral::Wide:
00064     // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
00065     // correction from DR343): "An array with element type compatible with a
00066     // qualified or unqualified version of wchar_t may be initialized by a wide
00067     // string literal, optionally enclosed in braces."
00068     if (Context.typesAreCompatible(Context.getWCharType(),
00069                                    ElemTy.getUnqualifiedType()))
00070       return Init;
00071 
00072     return 0;
00073   }
00074 
00075   llvm_unreachable("missed a StringLiteral kind?");
00076 }
00077 
00078 static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
00079   const ArrayType *arrayType = Context.getAsArrayType(declType);
00080   if (!arrayType) return 0;
00081 
00082   return IsStringInit(init, arrayType, Context);
00083 }
00084 
00085 static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
00086                             Sema &S) {
00087   // Get the length of the string as parsed.
00088   uint64_t StrLength =
00089     cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
00090 
00091 
00092   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
00093     // C99 6.7.8p14. We have an array of character type with unknown size
00094     // being initialized to a string literal.
00095     llvm::APSInt ConstVal(32);
00096     ConstVal = StrLength;
00097     // Return a new array type (C99 6.7.8p22).
00098     DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
00099                                            ConstVal,
00100                                            ArrayType::Normal, 0);
00101     return;
00102   }
00103 
00104   const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
00105 
00106   // We have an array of character type with known size.  However,
00107   // the size may be smaller or larger than the string we are initializing.
00108   // FIXME: Avoid truncation for 64-bit length strings.
00109   if (S.getLangOpts().CPlusPlus) {
00110     if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
00111       // For Pascal strings it's OK to strip off the terminating null character,
00112       // so the example below is valid:
00113       //
00114       // unsigned char a[2] = "\pa";
00115       if (SL->isPascal())
00116         StrLength--;
00117     }
00118   
00119     // [dcl.init.string]p2
00120     if (StrLength > CAT->getSize().getZExtValue())
00121       S.Diag(Str->getLocStart(),
00122              diag::err_initializer_string_for_char_array_too_long)
00123         << Str->getSourceRange();
00124   } else {
00125     // C99 6.7.8p14.
00126     if (StrLength-1 > CAT->getSize().getZExtValue())
00127       S.Diag(Str->getLocStart(),
00128              diag::warn_initializer_string_for_char_array_too_long)
00129         << Str->getSourceRange();
00130   }
00131 
00132   // Set the type to the actual size that we are initializing.  If we have
00133   // something like:
00134   //   char x[1] = "foo";
00135   // then this will set the string literal's type to char[1].
00136   Str->setType(DeclT);
00137 }
00138 
00139 //===----------------------------------------------------------------------===//
00140 // Semantic checking for initializer lists.
00141 //===----------------------------------------------------------------------===//
00142 
00143 /// @brief Semantic checking for initializer lists.
00144 ///
00145 /// The InitListChecker class contains a set of routines that each
00146 /// handle the initialization of a certain kind of entity, e.g.,
00147 /// arrays, vectors, struct/union types, scalars, etc. The
00148 /// InitListChecker itself performs a recursive walk of the subobject
00149 /// structure of the type to be initialized, while stepping through
00150 /// the initializer list one element at a time. The IList and Index
00151 /// parameters to each of the Check* routines contain the active
00152 /// (syntactic) initializer list and the index into that initializer
00153 /// list that represents the current initializer. Each routine is
00154 /// responsible for moving that Index forward as it consumes elements.
00155 ///
00156 /// Each Check* routine also has a StructuredList/StructuredIndex
00157 /// arguments, which contains the current "structured" (semantic)
00158 /// initializer list and the index into that initializer list where we
00159 /// are copying initializers as we map them over to the semantic
00160 /// list. Once we have completed our recursive walk of the subobject
00161 /// structure, we will have constructed a full semantic initializer
00162 /// list.
00163 ///
00164 /// C99 designators cause changes in the initializer list traversal,
00165 /// because they make the initialization "jump" into a specific
00166 /// subobject and then continue the initialization from that
00167 /// point. CheckDesignatedInitializer() recursively steps into the
00168 /// designated subobject and manages backing out the recursion to
00169 /// initialize the subobjects after the one designated.
00170 namespace {
00171 class InitListChecker {
00172   Sema &SemaRef;
00173   bool hadError;
00174   bool VerifyOnly; // no diagnostics, no structure building
00175   bool AllowBraceElision;
00176   llvm::DenseMap<InitListExpr *, InitListExpr *> SyntacticToSemantic;
00177   InitListExpr *FullyStructuredList;
00178 
00179   void CheckImplicitInitList(const InitializedEntity &Entity,
00180                              InitListExpr *ParentIList, QualType T,
00181                              unsigned &Index, InitListExpr *StructuredList,
00182                              unsigned &StructuredIndex);
00183   void CheckExplicitInitList(const InitializedEntity &Entity,
00184                              InitListExpr *IList, QualType &T,
00185                              unsigned &Index, InitListExpr *StructuredList,
00186                              unsigned &StructuredIndex,
00187                              bool TopLevelObject = false);
00188   void CheckListElementTypes(const InitializedEntity &Entity,
00189                              InitListExpr *IList, QualType &DeclType,
00190                              bool SubobjectIsDesignatorContext,
00191                              unsigned &Index,
00192                              InitListExpr *StructuredList,
00193                              unsigned &StructuredIndex,
00194                              bool TopLevelObject = false);
00195   void CheckSubElementType(const InitializedEntity &Entity,
00196                            InitListExpr *IList, QualType ElemType,
00197                            unsigned &Index,
00198                            InitListExpr *StructuredList,
00199                            unsigned &StructuredIndex);
00200   void CheckComplexType(const InitializedEntity &Entity,
00201                         InitListExpr *IList, QualType DeclType,
00202                         unsigned &Index,
00203                         InitListExpr *StructuredList,
00204                         unsigned &StructuredIndex);
00205   void CheckScalarType(const InitializedEntity &Entity,
00206                        InitListExpr *IList, QualType DeclType,
00207                        unsigned &Index,
00208                        InitListExpr *StructuredList,
00209                        unsigned &StructuredIndex);
00210   void CheckReferenceType(const InitializedEntity &Entity,
00211                           InitListExpr *IList, QualType DeclType,
00212                           unsigned &Index,
00213                           InitListExpr *StructuredList,
00214                           unsigned &StructuredIndex);
00215   void CheckVectorType(const InitializedEntity &Entity,
00216                        InitListExpr *IList, QualType DeclType, unsigned &Index,
00217                        InitListExpr *StructuredList,
00218                        unsigned &StructuredIndex);
00219   void CheckStructUnionTypes(const InitializedEntity &Entity,
00220                              InitListExpr *IList, QualType DeclType,
00221                              RecordDecl::field_iterator Field,
00222                              bool SubobjectIsDesignatorContext, unsigned &Index,
00223                              InitListExpr *StructuredList,
00224                              unsigned &StructuredIndex,
00225                              bool TopLevelObject = false);
00226   void CheckArrayType(const InitializedEntity &Entity,
00227                       InitListExpr *IList, QualType &DeclType,
00228                       llvm::APSInt elementIndex,
00229                       bool SubobjectIsDesignatorContext, unsigned &Index,
00230                       InitListExpr *StructuredList,
00231                       unsigned &StructuredIndex);
00232   bool CheckDesignatedInitializer(const InitializedEntity &Entity,
00233                                   InitListExpr *IList, DesignatedInitExpr *DIE,
00234                                   unsigned DesigIdx,
00235                                   QualType &CurrentObjectType,
00236                                   RecordDecl::field_iterator *NextField,
00237                                   llvm::APSInt *NextElementIndex,
00238                                   unsigned &Index,
00239                                   InitListExpr *StructuredList,
00240                                   unsigned &StructuredIndex,
00241                                   bool FinishSubobjectInit,
00242                                   bool TopLevelObject);
00243   InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
00244                                            QualType CurrentObjectType,
00245                                            InitListExpr *StructuredList,
00246                                            unsigned StructuredIndex,
00247                                            SourceRange InitRange);
00248   void UpdateStructuredListElement(InitListExpr *StructuredList,
00249                                    unsigned &StructuredIndex,
00250                                    Expr *expr);
00251   int numArrayElements(QualType DeclType);
00252   int numStructUnionElements(QualType DeclType);
00253 
00254   void FillInValueInitForField(unsigned Init, FieldDecl *Field,
00255                                const InitializedEntity &ParentEntity,
00256                                InitListExpr *ILE, bool &RequiresSecondPass);
00257   void FillInValueInitializations(const InitializedEntity &Entity,
00258                                   InitListExpr *ILE, bool &RequiresSecondPass);
00259   bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
00260                               Expr *InitExpr, FieldDecl *Field,
00261                               bool TopLevelObject);
00262   void CheckValueInitializable(const InitializedEntity &Entity);
00263 
00264 public:
00265   InitListChecker(Sema &S, const InitializedEntity &Entity,
00266                   InitListExpr *IL, QualType &T, bool VerifyOnly,
00267                   bool AllowBraceElision);
00268   bool HadError() { return hadError; }
00269 
00270   // @brief Retrieves the fully-structured initializer list used for
00271   // semantic analysis and code generation.
00272   InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
00273 };
00274 } // end anonymous namespace
00275 
00276 void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
00277   assert(VerifyOnly &&
00278          "CheckValueInitializable is only inteded for verification mode.");
00279 
00280   SourceLocation Loc;
00281   InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
00282                                                             true);
00283   InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
00284   if (InitSeq.Failed())
00285     hadError = true;
00286 }
00287 
00288 void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
00289                                         const InitializedEntity &ParentEntity,
00290                                               InitListExpr *ILE,
00291                                               bool &RequiresSecondPass) {
00292   SourceLocation Loc = ILE->getLocStart();
00293   unsigned NumInits = ILE->getNumInits();
00294   InitializedEntity MemberEntity
00295     = InitializedEntity::InitializeMember(Field, &ParentEntity);
00296   if (Init >= NumInits || !ILE->getInit(Init)) {
00297     // FIXME: We probably don't need to handle references
00298     // specially here, since value-initialization of references is
00299     // handled in InitializationSequence.
00300     if (Field->getType()->isReferenceType()) {
00301       // C++ [dcl.init.aggr]p9:
00302       //   If an incomplete or empty initializer-list leaves a
00303       //   member of reference type uninitialized, the program is
00304       //   ill-formed.
00305       SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
00306         << Field->getType()
00307         << ILE->getSyntacticForm()->getSourceRange();
00308       SemaRef.Diag(Field->getLocation(),
00309                    diag::note_uninit_reference_member);
00310       hadError = true;
00311       return;
00312     }
00313 
00314     InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
00315                                                               true);
00316     InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
00317     if (!InitSeq) {
00318       InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
00319       hadError = true;
00320       return;
00321     }
00322 
00323     ExprResult MemberInit
00324       = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
00325     if (MemberInit.isInvalid()) {
00326       hadError = true;
00327       return;
00328     }
00329 
00330     if (hadError) {
00331       // Do nothing
00332     } else if (Init < NumInits) {
00333       ILE->setInit(Init, MemberInit.takeAs<Expr>());
00334     } else if (InitSeq.isConstructorInitialization()) {
00335       // Value-initialization requires a constructor call, so
00336       // extend the initializer list to include the constructor
00337       // call and make a note that we'll need to take another pass
00338       // through the initializer list.
00339       ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
00340       RequiresSecondPass = true;
00341     }
00342   } else if (InitListExpr *InnerILE
00343                = dyn_cast<InitListExpr>(ILE->getInit(Init)))
00344     FillInValueInitializations(MemberEntity, InnerILE,
00345                                RequiresSecondPass);
00346 }
00347 
00348 /// Recursively replaces NULL values within the given initializer list
00349 /// with expressions that perform value-initialization of the
00350 /// appropriate type.
00351 void
00352 InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
00353                                             InitListExpr *ILE,
00354                                             bool &RequiresSecondPass) {
00355   assert((ILE->getType() != SemaRef.Context.VoidTy) &&
00356          "Should not have void type");
00357   SourceLocation Loc = ILE->getLocStart();
00358   if (ILE->getSyntacticForm())
00359     Loc = ILE->getSyntacticForm()->getLocStart();
00360 
00361   if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
00362     if (RType->getDecl()->isUnion() &&
00363         ILE->getInitializedFieldInUnion())
00364       FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
00365                               Entity, ILE, RequiresSecondPass);
00366     else {
00367       unsigned Init = 0;
00368       for (RecordDecl::field_iterator
00369              Field = RType->getDecl()->field_begin(),
00370              FieldEnd = RType->getDecl()->field_end();
00371            Field != FieldEnd; ++Field) {
00372         if (Field->isUnnamedBitfield())
00373           continue;
00374 
00375         if (hadError)
00376           return;
00377 
00378         FillInValueInitForField(Init, &*Field, Entity, ILE, RequiresSecondPass);
00379         if (hadError)
00380           return;
00381 
00382         ++Init;
00383 
00384         // Only look at the first initialization of a union.
00385         if (RType->getDecl()->isUnion())
00386           break;
00387       }
00388     }
00389 
00390     return;
00391   }
00392 
00393   QualType ElementType;
00394 
00395   InitializedEntity ElementEntity = Entity;
00396   unsigned NumInits = ILE->getNumInits();
00397   unsigned NumElements = NumInits;
00398   if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
00399     ElementType = AType->getElementType();
00400     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
00401       NumElements = CAType->getSize().getZExtValue();
00402     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
00403                                                          0, Entity);
00404   } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
00405     ElementType = VType->getElementType();
00406     NumElements = VType->getNumElements();
00407     ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
00408                                                          0, Entity);
00409   } else
00410     ElementType = ILE->getType();
00411 
00412 
00413   for (unsigned Init = 0; Init != NumElements; ++Init) {
00414     if (hadError)
00415       return;
00416 
00417     if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
00418         ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
00419       ElementEntity.setElementIndex(Init);
00420 
00421     Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
00422     if (!InitExpr && !ILE->hasArrayFiller()) {
00423       InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
00424                                                                 true);
00425       InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
00426       if (!InitSeq) {
00427         InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
00428         hadError = true;
00429         return;
00430       }
00431 
00432       ExprResult ElementInit
00433         = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
00434       if (ElementInit.isInvalid()) {
00435         hadError = true;
00436         return;
00437       }
00438 
00439       if (hadError) {
00440         // Do nothing
00441       } else if (Init < NumInits) {
00442         // For arrays, just set the expression used for value-initialization
00443         // of the "holes" in the array.
00444         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
00445           ILE->setArrayFiller(ElementInit.takeAs<Expr>());
00446         else
00447           ILE->setInit(Init, ElementInit.takeAs<Expr>());
00448       } else {
00449         // For arrays, just set the expression used for value-initialization
00450         // of the rest of elements and exit.
00451         if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
00452           ILE->setArrayFiller(ElementInit.takeAs<Expr>());
00453           return;
00454         }
00455 
00456         if (InitSeq.isConstructorInitialization()) {
00457           // Value-initialization requires a constructor call, so
00458           // extend the initializer list to include the constructor
00459           // call and make a note that we'll need to take another pass
00460           // through the initializer list.
00461           ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
00462           RequiresSecondPass = true;
00463         }
00464       }
00465     } else if (InitListExpr *InnerILE
00466                  = dyn_cast_or_null<InitListExpr>(InitExpr))
00467       FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
00468   }
00469 }
00470 
00471 
00472 InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
00473                                  InitListExpr *IL, QualType &T,
00474                                  bool VerifyOnly, bool AllowBraceElision)
00475   : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
00476   hadError = false;
00477 
00478   unsigned newIndex = 0;
00479   unsigned newStructuredIndex = 0;
00480   FullyStructuredList
00481     = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
00482   CheckExplicitInitList(Entity, IL, T, newIndex,
00483                         FullyStructuredList, newStructuredIndex,
00484                         /*TopLevelObject=*/true);
00485 
00486   if (!hadError && !VerifyOnly) {
00487     bool RequiresSecondPass = false;
00488     FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
00489     if (RequiresSecondPass && !hadError)
00490       FillInValueInitializations(Entity, FullyStructuredList,
00491                                  RequiresSecondPass);
00492   }
00493 }
00494 
00495 int InitListChecker::numArrayElements(QualType DeclType) {
00496   // FIXME: use a proper constant
00497   int maxElements = 0x7FFFFFFF;
00498   if (const ConstantArrayType *CAT =
00499         SemaRef.Context.getAsConstantArrayType(DeclType)) {
00500     maxElements = static_cast<int>(CAT->getSize().getZExtValue());
00501   }
00502   return maxElements;
00503 }
00504 
00505 int InitListChecker::numStructUnionElements(QualType DeclType) {
00506   RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
00507   int InitializableMembers = 0;
00508   for (RecordDecl::field_iterator
00509          Field = structDecl->field_begin(),
00510          FieldEnd = structDecl->field_end();
00511        Field != FieldEnd; ++Field) {
00512     if (!Field->isUnnamedBitfield())
00513       ++InitializableMembers;
00514   }
00515   if (structDecl->isUnion())
00516     return std::min(InitializableMembers, 1);
00517   return InitializableMembers - structDecl->hasFlexibleArrayMember();
00518 }
00519 
00520 void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
00521                                             InitListExpr *ParentIList,
00522                                             QualType T, unsigned &Index,
00523                                             InitListExpr *StructuredList,
00524                                             unsigned &StructuredIndex) {
00525   int maxElements = 0;
00526 
00527   if (T->isArrayType())
00528     maxElements = numArrayElements(T);
00529   else if (T->isRecordType())
00530     maxElements = numStructUnionElements(T);
00531   else if (T->isVectorType())
00532     maxElements = T->getAs<VectorType>()->getNumElements();
00533   else
00534     llvm_unreachable("CheckImplicitInitList(): Illegal type");
00535 
00536   if (maxElements == 0) {
00537     if (!VerifyOnly)
00538       SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
00539                    diag::err_implicit_empty_initializer);
00540     ++Index;
00541     hadError = true;
00542     return;
00543   }
00544 
00545   // Build a structured initializer list corresponding to this subobject.
00546   InitListExpr *StructuredSubobjectInitList
00547     = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
00548                                  StructuredIndex,
00549           SourceRange(ParentIList->getInit(Index)->getLocStart(),
00550                       ParentIList->getSourceRange().getEnd()));
00551   unsigned StructuredSubobjectInitIndex = 0;
00552 
00553   // Check the element types and build the structural subobject.
00554   unsigned StartIndex = Index;
00555   CheckListElementTypes(Entity, ParentIList, T,
00556                         /*SubobjectIsDesignatorContext=*/false, Index,
00557                         StructuredSubobjectInitList,
00558                         StructuredSubobjectInitIndex);
00559 
00560   if (VerifyOnly) {
00561     if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
00562       hadError = true;
00563   } else {
00564     StructuredSubobjectInitList->setType(T);
00565 
00566     unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
00567     // Update the structured sub-object initializer so that it's ending
00568     // range corresponds with the end of the last initializer it used.
00569     if (EndIndex < ParentIList->getNumInits()) {
00570       SourceLocation EndLoc
00571         = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
00572       StructuredSubobjectInitList->setRBraceLoc(EndLoc);
00573     }
00574 
00575     // Complain about missing braces.
00576     if (T->isArrayType() || T->isRecordType()) {
00577       SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
00578                     AllowBraceElision ? diag::warn_missing_braces :
00579                                         diag::err_missing_braces)
00580         << StructuredSubobjectInitList->getSourceRange()
00581         << FixItHint::CreateInsertion(
00582               StructuredSubobjectInitList->getLocStart(), "{")
00583         << FixItHint::CreateInsertion(
00584               SemaRef.PP.getLocForEndOfToken(
00585                                       StructuredSubobjectInitList->getLocEnd()),
00586               "}");
00587       if (!AllowBraceElision)
00588         hadError = true;
00589     }
00590   }
00591 }
00592 
00593 void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
00594                                             InitListExpr *IList, QualType &T,
00595                                             unsigned &Index,
00596                                             InitListExpr *StructuredList,
00597                                             unsigned &StructuredIndex,
00598                                             bool TopLevelObject) {
00599   assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
00600   if (!VerifyOnly) {
00601     SyntacticToSemantic[IList] = StructuredList;
00602     StructuredList->setSyntacticForm(IList);
00603   }
00604   CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
00605                         Index, StructuredList, StructuredIndex, TopLevelObject);
00606   if (!VerifyOnly) {
00607     QualType ExprTy = T;
00608     if (!ExprTy->isArrayType())
00609       ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
00610     IList->setType(ExprTy);
00611     StructuredList->setType(ExprTy);
00612   }
00613   if (hadError)
00614     return;
00615 
00616   if (Index < IList->getNumInits()) {
00617     // We have leftover initializers
00618     if (VerifyOnly) {
00619       if (SemaRef.getLangOpts().CPlusPlus ||
00620           (SemaRef.getLangOpts().OpenCL &&
00621            IList->getType()->isVectorType())) {
00622         hadError = true;
00623       }
00624       return;
00625     }
00626 
00627     if (StructuredIndex == 1 &&
00628         IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
00629       unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
00630       if (SemaRef.getLangOpts().CPlusPlus) {
00631         DK = diag::err_excess_initializers_in_char_array_initializer;
00632         hadError = true;
00633       }
00634       // Special-case
00635       SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
00636         << IList->getInit(Index)->getSourceRange();
00637     } else if (!T->isIncompleteType()) {
00638       // Don't complain for incomplete types, since we'll get an error
00639       // elsewhere
00640       QualType CurrentObjectType = StructuredList->getType();
00641       int initKind =
00642         CurrentObjectType->isArrayType()? 0 :
00643         CurrentObjectType->isVectorType()? 1 :
00644         CurrentObjectType->isScalarType()? 2 :
00645         CurrentObjectType->isUnionType()? 3 :
00646         4;
00647 
00648       unsigned DK = diag::warn_excess_initializers;
00649       if (SemaRef.getLangOpts().CPlusPlus) {
00650         DK = diag::err_excess_initializers;
00651         hadError = true;
00652       }
00653       if (SemaRef.getLangOpts().OpenCL && initKind == 1) {
00654         DK = diag::err_excess_initializers;
00655         hadError = true;
00656       }
00657 
00658       SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
00659         << initKind << IList->getInit(Index)->getSourceRange();
00660     }
00661   }
00662 
00663   if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
00664       !TopLevelObject)
00665     SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
00666       << IList->getSourceRange()
00667       << FixItHint::CreateRemoval(IList->getLocStart())
00668       << FixItHint::CreateRemoval(IList->getLocEnd());
00669 }
00670 
00671 void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
00672                                             InitListExpr *IList,
00673                                             QualType &DeclType,
00674                                             bool SubobjectIsDesignatorContext,
00675                                             unsigned &Index,
00676                                             InitListExpr *StructuredList,
00677                                             unsigned &StructuredIndex,
00678                                             bool TopLevelObject) {
00679   if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
00680     // Explicitly braced initializer for complex type can be real+imaginary
00681     // parts.
00682     CheckComplexType(Entity, IList, DeclType, Index,
00683                      StructuredList, StructuredIndex);
00684   } else if (DeclType->isScalarType()) {
00685     CheckScalarType(Entity, IList, DeclType, Index,
00686                     StructuredList, StructuredIndex);
00687   } else if (DeclType->isVectorType()) {
00688     CheckVectorType(Entity, IList, DeclType, Index,
00689                     StructuredList, StructuredIndex);
00690   } else if (DeclType->isAggregateType()) {
00691     if (DeclType->isRecordType()) {
00692       RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
00693       CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
00694                             SubobjectIsDesignatorContext, Index,
00695                             StructuredList, StructuredIndex,
00696                             TopLevelObject);
00697     } else if (DeclType->isArrayType()) {
00698       llvm::APSInt Zero(
00699                       SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
00700                       false);
00701       CheckArrayType(Entity, IList, DeclType, Zero,
00702                      SubobjectIsDesignatorContext, Index,
00703                      StructuredList, StructuredIndex);
00704     } else
00705       llvm_unreachable("Aggregate that isn't a structure or array?!");
00706   } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
00707     // This type is invalid, issue a diagnostic.
00708     ++Index;
00709     if (!VerifyOnly)
00710       SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
00711         << DeclType;
00712     hadError = true;
00713   } else if (DeclType->isRecordType()) {
00714     // C++ [dcl.init]p14:
00715     //   [...] If the class is an aggregate (8.5.1), and the initializer
00716     //   is a brace-enclosed list, see 8.5.1.
00717     //
00718     // Note: 8.5.1 is handled below; here, we diagnose the case where
00719     // we have an initializer list and a destination type that is not
00720     // an aggregate.
00721     // FIXME: In C++0x, this is yet another form of initialization.
00722     if (!VerifyOnly)
00723       SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
00724         << DeclType << IList->getSourceRange();
00725     hadError = true;
00726   } else if (DeclType->isReferenceType()) {
00727     CheckReferenceType(Entity, IList, DeclType, Index,
00728                        StructuredList, StructuredIndex);
00729   } else if (DeclType->isObjCObjectType()) {
00730     if (!VerifyOnly)
00731       SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
00732         << DeclType;
00733     hadError = true;
00734   } else {
00735     if (!VerifyOnly)
00736       SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
00737         << DeclType;
00738     hadError = true;
00739   }
00740 }
00741 
00742 void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
00743                                           InitListExpr *IList,
00744                                           QualType ElemType,
00745                                           unsigned &Index,
00746                                           InitListExpr *StructuredList,
00747                                           unsigned &StructuredIndex) {
00748   Expr *expr = IList->getInit(Index);
00749   if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
00750     unsigned newIndex = 0;
00751     unsigned newStructuredIndex = 0;
00752     InitListExpr *newStructuredList
00753       = getStructuredSubobjectInit(IList, Index, ElemType,
00754                                    StructuredList, StructuredIndex,
00755                                    SubInitList->getSourceRange());
00756     CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
00757                           newStructuredList, newStructuredIndex);
00758     ++StructuredIndex;
00759     ++Index;
00760     return;
00761   } else if (ElemType->isScalarType()) {
00762     return CheckScalarType(Entity, IList, ElemType, Index,
00763                            StructuredList, StructuredIndex);
00764   } else if (ElemType->isReferenceType()) {
00765     return CheckReferenceType(Entity, IList, ElemType, Index,
00766                               StructuredList, StructuredIndex);
00767   }
00768 
00769   if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
00770     // arrayType can be incomplete if we're initializing a flexible
00771     // array member.  There's nothing we can do with the completed
00772     // type here, though.
00773 
00774     if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
00775       if (!VerifyOnly) {
00776         CheckStringInit(Str, ElemType, arrayType, SemaRef);
00777         UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
00778       }
00779       ++Index;
00780       return;
00781     }
00782 
00783     // Fall through for subaggregate initialization.
00784 
00785   } else if (SemaRef.getLangOpts().CPlusPlus) {
00786     // C++ [dcl.init.aggr]p12:
00787     //   All implicit type conversions (clause 4) are considered when
00788     //   initializing the aggregate member with an initializer from
00789     //   an initializer-list. If the initializer can initialize a
00790     //   member, the member is initialized. [...]
00791 
00792     // FIXME: Better EqualLoc?
00793     InitializationKind Kind =
00794       InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
00795     InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
00796 
00797     if (Seq) {
00798       if (!VerifyOnly) {
00799         ExprResult Result =
00800           Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
00801         if (Result.isInvalid())
00802           hadError = true;
00803 
00804         UpdateStructuredListElement(StructuredList, StructuredIndex,
00805                                     Result.takeAs<Expr>());
00806       }
00807       ++Index;
00808       return;
00809     }
00810 
00811     // Fall through for subaggregate initialization
00812   } else {
00813     // C99 6.7.8p13:
00814     //
00815     //   The initializer for a structure or union object that has
00816     //   automatic storage duration shall be either an initializer
00817     //   list as described below, or a single expression that has
00818     //   compatible structure or union type. In the latter case, the
00819     //   initial value of the object, including unnamed members, is
00820     //   that of the expression.
00821     ExprResult ExprRes = SemaRef.Owned(expr);
00822     if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
00823         SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
00824                                                  !VerifyOnly)
00825           == Sema::Compatible) {
00826       if (ExprRes.isInvalid())
00827         hadError = true;
00828       else {
00829         ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
00830         if (ExprRes.isInvalid())
00831           hadError = true;
00832       }
00833       UpdateStructuredListElement(StructuredList, StructuredIndex,
00834                                   ExprRes.takeAs<Expr>());
00835       ++Index;
00836       return;
00837     }
00838     ExprRes.release();
00839     // Fall through for subaggregate initialization
00840   }
00841 
00842   // C++ [dcl.init.aggr]p12:
00843   //
00844   //   [...] Otherwise, if the member is itself a non-empty
00845   //   subaggregate, brace elision is assumed and the initializer is
00846   //   considered for the initialization of the first member of
00847   //   the subaggregate.
00848   if (!SemaRef.getLangOpts().OpenCL && 
00849       (ElemType->isAggregateType() || ElemType->isVectorType())) {
00850     CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
00851                           StructuredIndex);
00852     ++StructuredIndex;
00853   } else {
00854     if (!VerifyOnly) {
00855       // We cannot initialize this element, so let
00856       // PerformCopyInitialization produce the appropriate diagnostic.
00857       SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
00858                                         SemaRef.Owned(expr),
00859                                         /*TopLevelOfInitList=*/true);
00860     }
00861     hadError = true;
00862     ++Index;
00863     ++StructuredIndex;
00864   }
00865 }
00866 
00867 void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
00868                                        InitListExpr *IList, QualType DeclType,
00869                                        unsigned &Index,
00870                                        InitListExpr *StructuredList,
00871                                        unsigned &StructuredIndex) {
00872   assert(Index == 0 && "Index in explicit init list must be zero");
00873 
00874   // As an extension, clang supports complex initializers, which initialize
00875   // a complex number component-wise.  When an explicit initializer list for
00876   // a complex number contains two two initializers, this extension kicks in:
00877   // it exepcts the initializer list to contain two elements convertible to
00878   // the element type of the complex type. The first element initializes
00879   // the real part, and the second element intitializes the imaginary part.
00880 
00881   if (IList->getNumInits() != 2)
00882     return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
00883                            StructuredIndex);
00884 
00885   // This is an extension in C.  (The builtin _Complex type does not exist
00886   // in the C++ standard.)
00887   if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly)
00888     SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
00889       << IList->getSourceRange();
00890 
00891   // Initialize the complex number.
00892   QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
00893   InitializedEntity ElementEntity =
00894     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
00895 
00896   for (unsigned i = 0; i < 2; ++i) {
00897     ElementEntity.setElementIndex(Index);
00898     CheckSubElementType(ElementEntity, IList, elementType, Index,
00899                         StructuredList, StructuredIndex);
00900   }
00901 }
00902 
00903 
00904 void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
00905                                       InitListExpr *IList, QualType DeclType,
00906                                       unsigned &Index,
00907                                       InitListExpr *StructuredList,
00908                                       unsigned &StructuredIndex) {
00909   if (Index >= IList->getNumInits()) {
00910     if (!VerifyOnly)
00911       SemaRef.Diag(IList->getLocStart(),
00912                    SemaRef.getLangOpts().CPlusPlus0x ?
00913                      diag::warn_cxx98_compat_empty_scalar_initializer :
00914                      diag::err_empty_scalar_initializer)
00915         << IList->getSourceRange();
00916     hadError = !SemaRef.getLangOpts().CPlusPlus0x;
00917     ++Index;
00918     ++StructuredIndex;
00919     return;
00920   }
00921 
00922   Expr *expr = IList->getInit(Index);
00923   if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
00924     if (!VerifyOnly)
00925       SemaRef.Diag(SubIList->getLocStart(),
00926                    diag::warn_many_braces_around_scalar_init)
00927         << SubIList->getSourceRange();
00928 
00929     CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
00930                     StructuredIndex);
00931     return;
00932   } else if (isa<DesignatedInitExpr>(expr)) {
00933     if (!VerifyOnly)
00934       SemaRef.Diag(expr->getLocStart(),
00935                    diag::err_designator_for_scalar_init)
00936         << DeclType << expr->getSourceRange();
00937     hadError = true;
00938     ++Index;
00939     ++StructuredIndex;
00940     return;
00941   }
00942 
00943   if (VerifyOnly) {
00944     if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
00945       hadError = true;
00946     ++Index;
00947     return;
00948   }
00949 
00950   ExprResult Result =
00951     SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
00952                                       SemaRef.Owned(expr),
00953                                       /*TopLevelOfInitList=*/true);
00954 
00955   Expr *ResultExpr = 0;
00956 
00957   if (Result.isInvalid())
00958     hadError = true; // types weren't compatible.
00959   else {
00960     ResultExpr = Result.takeAs<Expr>();
00961 
00962     if (ResultExpr != expr) {
00963       // The type was promoted, update initializer list.
00964       IList->setInit(Index, ResultExpr);
00965     }
00966   }
00967   if (hadError)
00968     ++StructuredIndex;
00969   else
00970     UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
00971   ++Index;
00972 }
00973 
00974 void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
00975                                          InitListExpr *IList, QualType DeclType,
00976                                          unsigned &Index,
00977                                          InitListExpr *StructuredList,
00978                                          unsigned &StructuredIndex) {
00979   if (Index >= IList->getNumInits()) {
00980     // FIXME: It would be wonderful if we could point at the actual member. In
00981     // general, it would be useful to pass location information down the stack,
00982     // so that we know the location (or decl) of the "current object" being
00983     // initialized.
00984     if (!VerifyOnly)
00985       SemaRef.Diag(IList->getLocStart(),
00986                     diag::err_init_reference_member_uninitialized)
00987         << DeclType
00988         << IList->getSourceRange();
00989     hadError = true;
00990     ++Index;
00991     ++StructuredIndex;
00992     return;
00993   }
00994 
00995   Expr *expr = IList->getInit(Index);
00996   if (isa<InitListExpr>(expr) && !SemaRef.getLangOpts().CPlusPlus0x) {
00997     if (!VerifyOnly)
00998       SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
00999         << DeclType << IList->getSourceRange();
01000     hadError = true;
01001     ++Index;
01002     ++StructuredIndex;
01003     return;
01004   }
01005 
01006   if (VerifyOnly) {
01007     if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
01008       hadError = true;
01009     ++Index;
01010     return;
01011   }
01012 
01013   ExprResult Result =
01014     SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
01015                                       SemaRef.Owned(expr),
01016                                       /*TopLevelOfInitList=*/true);
01017 
01018   if (Result.isInvalid())
01019     hadError = true;
01020 
01021   expr = Result.takeAs<Expr>();
01022   IList->setInit(Index, expr);
01023 
01024   if (hadError)
01025     ++StructuredIndex;
01026   else
01027     UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
01028   ++Index;
01029 }
01030 
01031 void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
01032                                       InitListExpr *IList, QualType DeclType,
01033                                       unsigned &Index,
01034                                       InitListExpr *StructuredList,
01035                                       unsigned &StructuredIndex) {
01036   const VectorType *VT = DeclType->getAs<VectorType>();
01037   unsigned maxElements = VT->getNumElements();
01038   unsigned numEltsInit = 0;
01039   QualType elementType = VT->getElementType();
01040 
01041   if (Index >= IList->getNumInits()) {
01042     // Make sure the element type can be value-initialized.
01043     if (VerifyOnly)
01044       CheckValueInitializable(
01045           InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
01046     return;
01047   }
01048 
01049   if (!SemaRef.getLangOpts().OpenCL) {
01050     // If the initializing element is a vector, try to copy-initialize
01051     // instead of breaking it apart (which is doomed to failure anyway).
01052     Expr *Init = IList->getInit(Index);
01053     if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
01054       if (VerifyOnly) {
01055         if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
01056           hadError = true;
01057         ++Index;
01058         return;
01059       }
01060 
01061       ExprResult Result =
01062         SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
01063                                           SemaRef.Owned(Init),
01064                                           /*TopLevelOfInitList=*/true);
01065 
01066       Expr *ResultExpr = 0;
01067       if (Result.isInvalid())
01068         hadError = true; // types weren't compatible.
01069       else {
01070         ResultExpr = Result.takeAs<Expr>();
01071 
01072         if (ResultExpr != Init) {
01073           // The type was promoted, update initializer list.
01074           IList->setInit(Index, ResultExpr);
01075         }
01076       }
01077       if (hadError)
01078         ++StructuredIndex;
01079       else
01080         UpdateStructuredListElement(StructuredList, StructuredIndex,
01081                                     ResultExpr);
01082       ++Index;
01083       return;
01084     }
01085 
01086     InitializedEntity ElementEntity =
01087       InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
01088 
01089     for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
01090       // Don't attempt to go past the end of the init list
01091       if (Index >= IList->getNumInits()) {
01092         if (VerifyOnly)
01093           CheckValueInitializable(ElementEntity);
01094         break;
01095       }
01096 
01097       ElementEntity.setElementIndex(Index);
01098       CheckSubElementType(ElementEntity, IList, elementType, Index,
01099                           StructuredList, StructuredIndex);
01100     }
01101     return;
01102   }
01103 
01104   InitializedEntity ElementEntity =
01105     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
01106 
01107   // OpenCL initializers allows vectors to be constructed from vectors.
01108   for (unsigned i = 0; i < maxElements; ++i) {
01109     // Don't attempt to go past the end of the init list
01110     if (Index >= IList->getNumInits())
01111       break;
01112 
01113     ElementEntity.setElementIndex(Index);
01114 
01115     QualType IType = IList->getInit(Index)->getType();
01116     if (!IType->isVectorType()) {
01117       CheckSubElementType(ElementEntity, IList, elementType, Index,
01118                           StructuredList, StructuredIndex);
01119       ++numEltsInit;
01120     } else {
01121       QualType VecType;
01122       const VectorType *IVT = IType->getAs<VectorType>();
01123       unsigned numIElts = IVT->getNumElements();
01124 
01125       if (IType->isExtVectorType())
01126         VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
01127       else
01128         VecType = SemaRef.Context.getVectorType(elementType, numIElts,
01129                                                 IVT->getVectorKind());
01130       CheckSubElementType(ElementEntity, IList, VecType, Index,
01131                           StructuredList, StructuredIndex);
01132       numEltsInit += numIElts;
01133     }
01134   }
01135 
01136   // OpenCL requires all elements to be initialized.
01137   if (numEltsInit != maxElements) {
01138     if (!VerifyOnly)
01139       SemaRef.Diag(IList->getLocStart(),
01140                    diag::err_vector_incorrect_num_initializers)
01141         << (numEltsInit < maxElements) << maxElements << numEltsInit;
01142     hadError = true;
01143   }
01144 }
01145 
01146 void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
01147                                      InitListExpr *IList, QualType &DeclType,
01148                                      llvm::APSInt elementIndex,
01149                                      bool SubobjectIsDesignatorContext,
01150                                      unsigned &Index,
01151                                      InitListExpr *StructuredList,
01152                                      unsigned &StructuredIndex) {
01153   const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
01154 
01155   // Check for the special-case of initializing an array with a string.
01156   if (Index < IList->getNumInits()) {
01157     if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
01158                                  SemaRef.Context)) {
01159       // We place the string literal directly into the resulting
01160       // initializer list. This is the only place where the structure
01161       // of the structured initializer list doesn't match exactly,
01162       // because doing so would involve allocating one character
01163       // constant for each string.
01164       if (!VerifyOnly) {
01165         CheckStringInit(Str, DeclType, arrayType, SemaRef);
01166         UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
01167         StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
01168       }
01169       ++Index;
01170       return;
01171     }
01172   }
01173   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
01174     // Check for VLAs; in standard C it would be possible to check this
01175     // earlier, but I don't know where clang accepts VLAs (gcc accepts
01176     // them in all sorts of strange places).
01177     if (!VerifyOnly)
01178       SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
01179                     diag::err_variable_object_no_init)
01180         << VAT->getSizeExpr()->getSourceRange();
01181     hadError = true;
01182     ++Index;
01183     ++StructuredIndex;
01184     return;
01185   }
01186 
01187   // We might know the maximum number of elements in advance.
01188   llvm::APSInt maxElements(elementIndex.getBitWidth(),
01189                            elementIndex.isUnsigned());
01190   bool maxElementsKnown = false;
01191   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
01192     maxElements = CAT->getSize();
01193     elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
01194     elementIndex.setIsUnsigned(maxElements.isUnsigned());
01195     maxElementsKnown = true;
01196   }
01197 
01198   QualType elementType = arrayType->getElementType();
01199   while (Index < IList->getNumInits()) {
01200     Expr *Init = IList->getInit(Index);
01201     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
01202       // If we're not the subobject that matches up with the '{' for
01203       // the designator, we shouldn't be handling the
01204       // designator. Return immediately.
01205       if (!SubobjectIsDesignatorContext)
01206         return;
01207 
01208       // Handle this designated initializer. elementIndex will be
01209       // updated to be the next array element we'll initialize.
01210       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
01211                                      DeclType, 0, &elementIndex, Index,
01212                                      StructuredList, StructuredIndex, true,
01213                                      false)) {
01214         hadError = true;
01215         continue;
01216       }
01217 
01218       if (elementIndex.getBitWidth() > maxElements.getBitWidth())
01219         maxElements = maxElements.extend(elementIndex.getBitWidth());
01220       else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
01221         elementIndex = elementIndex.extend(maxElements.getBitWidth());
01222       elementIndex.setIsUnsigned(maxElements.isUnsigned());
01223 
01224       // If the array is of incomplete type, keep track of the number of
01225       // elements in the initializer.
01226       if (!maxElementsKnown && elementIndex > maxElements)
01227         maxElements = elementIndex;
01228 
01229       continue;
01230     }
01231 
01232     // If we know the maximum number of elements, and we've already
01233     // hit it, stop consuming elements in the initializer list.
01234     if (maxElementsKnown && elementIndex == maxElements)
01235       break;
01236 
01237     InitializedEntity ElementEntity =
01238       InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
01239                                            Entity);
01240     // Check this element.
01241     CheckSubElementType(ElementEntity, IList, elementType, Index,
01242                         StructuredList, StructuredIndex);
01243     ++elementIndex;
01244 
01245     // If the array is of incomplete type, keep track of the number of
01246     // elements in the initializer.
01247     if (!maxElementsKnown && elementIndex > maxElements)
01248       maxElements = elementIndex;
01249   }
01250   if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
01251     // If this is an incomplete array type, the actual type needs to
01252     // be calculated here.
01253     llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
01254     if (maxElements == Zero) {
01255       // Sizing an array implicitly to zero is not allowed by ISO C,
01256       // but is supported by GNU.
01257       SemaRef.Diag(IList->getLocStart(),
01258                     diag::ext_typecheck_zero_array_size);
01259     }
01260 
01261     DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
01262                                                      ArrayType::Normal, 0);
01263   }
01264   if (!hadError && VerifyOnly) {
01265     // Check if there are any members of the array that get value-initialized.
01266     // If so, check if doing that is possible.
01267     // FIXME: This needs to detect holes left by designated initializers too.
01268     if (maxElementsKnown && elementIndex < maxElements)
01269       CheckValueInitializable(InitializedEntity::InitializeElement(
01270                                                   SemaRef.Context, 0, Entity));
01271   }
01272 }
01273 
01274 bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
01275                                              Expr *InitExpr,
01276                                              FieldDecl *Field,
01277                                              bool TopLevelObject) {
01278   // Handle GNU flexible array initializers.
01279   unsigned FlexArrayDiag;
01280   if (isa<InitListExpr>(InitExpr) &&
01281       cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
01282     // Empty flexible array init always allowed as an extension
01283     FlexArrayDiag = diag::ext_flexible_array_init;
01284   } else if (SemaRef.getLangOpts().CPlusPlus) {
01285     // Disallow flexible array init in C++; it is not required for gcc
01286     // compatibility, and it needs work to IRGen correctly in general.
01287     FlexArrayDiag = diag::err_flexible_array_init;
01288   } else if (!TopLevelObject) {
01289     // Disallow flexible array init on non-top-level object
01290     FlexArrayDiag = diag::err_flexible_array_init;
01291   } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
01292     // Disallow flexible array init on anything which is not a variable.
01293     FlexArrayDiag = diag::err_flexible_array_init;
01294   } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
01295     // Disallow flexible array init on local variables.
01296     FlexArrayDiag = diag::err_flexible_array_init;
01297   } else {
01298     // Allow other cases.
01299     FlexArrayDiag = diag::ext_flexible_array_init;
01300   }
01301 
01302   if (!VerifyOnly) {
01303     SemaRef.Diag(InitExpr->getLocStart(),
01304                  FlexArrayDiag)
01305       << InitExpr->getLocStart();
01306     SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
01307       << Field;
01308   }
01309 
01310   return FlexArrayDiag != diag::ext_flexible_array_init;
01311 }
01312 
01313 void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
01314                                             InitListExpr *IList,
01315                                             QualType DeclType,
01316                                             RecordDecl::field_iterator Field,
01317                                             bool SubobjectIsDesignatorContext,
01318                                             unsigned &Index,
01319                                             InitListExpr *StructuredList,
01320                                             unsigned &StructuredIndex,
01321                                             bool TopLevelObject) {
01322   RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
01323 
01324   // If the record is invalid, some of it's members are invalid. To avoid
01325   // confusion, we forgo checking the intializer for the entire record.
01326   if (structDecl->isInvalidDecl()) {
01327     hadError = true;
01328     return;
01329   }
01330 
01331   if (DeclType->isUnionType() && IList->getNumInits() == 0) {
01332     // Value-initialize the first named member of the union.
01333     RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
01334     for (RecordDecl::field_iterator FieldEnd = RD->field_end();
01335          Field != FieldEnd; ++Field) {
01336       if (Field->getDeclName()) {
01337         if (VerifyOnly)
01338           CheckValueInitializable(
01339               InitializedEntity::InitializeMember(&*Field, &Entity));
01340         else
01341           StructuredList->setInitializedFieldInUnion(&*Field);
01342         break;
01343       }
01344     }
01345     return;
01346   }
01347 
01348   // If structDecl is a forward declaration, this loop won't do
01349   // anything except look at designated initializers; That's okay,
01350   // because an error should get printed out elsewhere. It might be
01351   // worthwhile to skip over the rest of the initializer, though.
01352   RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
01353   RecordDecl::field_iterator FieldEnd = RD->field_end();
01354   bool InitializedSomething = false;
01355   bool CheckForMissingFields = true;
01356   while (Index < IList->getNumInits()) {
01357     Expr *Init = IList->getInit(Index);
01358 
01359     if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
01360       // If we're not the subobject that matches up with the '{' for
01361       // the designator, we shouldn't be handling the
01362       // designator. Return immediately.
01363       if (!SubobjectIsDesignatorContext)
01364         return;
01365 
01366       // Handle this designated initializer. Field will be updated to
01367       // the next field that we'll be initializing.
01368       if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
01369                                      DeclType, &Field, 0, Index,
01370                                      StructuredList, StructuredIndex,
01371                                      true, TopLevelObject))
01372         hadError = true;
01373 
01374       InitializedSomething = true;
01375 
01376       // Disable check for missing fields when designators are used.
01377       // This matches gcc behaviour.
01378       CheckForMissingFields = false;
01379       continue;
01380     }
01381 
01382     if (Field == FieldEnd) {
01383       // We've run out of fields. We're done.
01384       break;
01385     }
01386 
01387     // We've already initialized a member of a union. We're done.
01388     if (InitializedSomething && DeclType->isUnionType())
01389       break;
01390 
01391     // If we've hit the flexible array member at the end, we're done.
01392     if (Field->getType()->isIncompleteArrayType())
01393       break;
01394 
01395     if (Field->isUnnamedBitfield()) {
01396       // Don't initialize unnamed bitfields, e.g. "int : 20;"
01397       ++Field;
01398       continue;
01399     }
01400 
01401     // Make sure we can use this declaration.
01402     bool InvalidUse;
01403     if (VerifyOnly)
01404       InvalidUse = !SemaRef.CanUseDecl(&*Field);
01405     else
01406       InvalidUse = SemaRef.DiagnoseUseOfDecl(&*Field,
01407                                           IList->getInit(Index)->getLocStart());
01408     if (InvalidUse) {
01409       ++Index;
01410       ++Field;
01411       hadError = true;
01412       continue;
01413     }
01414 
01415     InitializedEntity MemberEntity =
01416       InitializedEntity::InitializeMember(&*Field, &Entity);
01417     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
01418                         StructuredList, StructuredIndex);
01419     InitializedSomething = true;
01420 
01421     if (DeclType->isUnionType() && !VerifyOnly) {
01422       // Initialize the first field within the union.
01423       StructuredList->setInitializedFieldInUnion(&*Field);
01424     }
01425 
01426     ++Field;
01427   }
01428 
01429   // Emit warnings for missing struct field initializers.
01430   if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
01431       Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
01432       !DeclType->isUnionType()) {
01433     // It is possible we have one or more unnamed bitfields remaining.
01434     // Find first (if any) named field and emit warning.
01435     for (RecordDecl::field_iterator it = Field, end = RD->field_end();
01436          it != end; ++it) {
01437       if (!it->isUnnamedBitfield()) {
01438         SemaRef.Diag(IList->getSourceRange().getEnd(),
01439                      diag::warn_missing_field_initializers) << it->getName();
01440         break;
01441       }
01442     }
01443   }
01444 
01445   // Check that any remaining fields can be value-initialized.
01446   if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
01447       !Field->getType()->isIncompleteArrayType()) {
01448     // FIXME: Should check for holes left by designated initializers too.
01449     for (; Field != FieldEnd && !hadError; ++Field) {
01450       if (!Field->isUnnamedBitfield())
01451         CheckValueInitializable(
01452             InitializedEntity::InitializeMember(&*Field, &Entity));
01453     }
01454   }
01455 
01456   if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
01457       Index >= IList->getNumInits())
01458     return;
01459 
01460   if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), &*Field,
01461                              TopLevelObject)) {
01462     hadError = true;
01463     ++Index;
01464     return;
01465   }
01466 
01467   InitializedEntity MemberEntity =
01468     InitializedEntity::InitializeMember(&*Field, &Entity);
01469 
01470   if (isa<InitListExpr>(IList->getInit(Index)))
01471     CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
01472                         StructuredList, StructuredIndex);
01473   else
01474     CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
01475                           StructuredList, StructuredIndex);
01476 }
01477 
01478 /// \brief Expand a field designator that refers to a member of an
01479 /// anonymous struct or union into a series of field designators that
01480 /// refers to the field within the appropriate subobject.
01481 ///
01482 static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
01483                                            DesignatedInitExpr *DIE,
01484                                            unsigned DesigIdx,
01485                                            IndirectFieldDecl *IndirectField) {
01486   typedef DesignatedInitExpr::Designator Designator;
01487 
01488   // Build the replacement designators.
01489   SmallVector<Designator, 4> Replacements;
01490   for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
01491        PE = IndirectField->chain_end(); PI != PE; ++PI) {
01492     if (PI + 1 == PE)
01493       Replacements.push_back(Designator((IdentifierInfo *)0,
01494                                     DIE->getDesignator(DesigIdx)->getDotLoc(),
01495                                 DIE->getDesignator(DesigIdx)->getFieldLoc()));
01496     else
01497       Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
01498                                         SourceLocation()));
01499     assert(isa<FieldDecl>(*PI));
01500     Replacements.back().setField(cast<FieldDecl>(*PI));
01501   }
01502 
01503   // Expand the current designator into the set of replacement
01504   // designators, so we have a full subobject path down to where the
01505   // member of the anonymous struct/union is actually stored.
01506   DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
01507                         &Replacements[0] + Replacements.size());
01508 }
01509 
01510 /// \brief Given an implicit anonymous field, search the IndirectField that
01511 ///  corresponds to FieldName.
01512 static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
01513                                                  IdentifierInfo *FieldName) {
01514   assert(AnonField->isAnonymousStructOrUnion());
01515   Decl *NextDecl = AnonField->getNextDeclInContext();
01516   while (IndirectFieldDecl *IF = 
01517           dyn_cast_or_null<IndirectFieldDecl>(NextDecl)) {
01518     if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
01519       return IF;
01520     NextDecl = NextDecl->getNextDeclInContext();
01521   }
01522   return 0;
01523 }
01524 
01525 static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
01526                                                    DesignatedInitExpr *DIE) {
01527   unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
01528   SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
01529   for (unsigned I = 0; I < NumIndexExprs; ++I)
01530     IndexExprs[I] = DIE->getSubExpr(I + 1);
01531   return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
01532                                     DIE->size(), IndexExprs.data(),
01533                                     NumIndexExprs, DIE->getEqualOrColonLoc(),
01534                                     DIE->usesGNUSyntax(), DIE->getInit());
01535 }
01536 
01537 namespace {
01538 
01539 // Callback to only accept typo corrections that are for field members of
01540 // the given struct or union.
01541 class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
01542  public:
01543   explicit FieldInitializerValidatorCCC(RecordDecl *RD)
01544       : Record(RD) {}
01545 
01546   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
01547     FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
01548     return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
01549   }
01550 
01551  private:
01552   RecordDecl *Record;
01553 };
01554 
01555 }
01556 
01557 /// @brief Check the well-formedness of a C99 designated initializer.
01558 ///
01559 /// Determines whether the designated initializer @p DIE, which
01560 /// resides at the given @p Index within the initializer list @p
01561 /// IList, is well-formed for a current object of type @p DeclType
01562 /// (C99 6.7.8). The actual subobject that this designator refers to
01563 /// within the current subobject is returned in either
01564 /// @p NextField or @p NextElementIndex (whichever is appropriate).
01565 ///
01566 /// @param IList  The initializer list in which this designated
01567 /// initializer occurs.
01568 ///
01569 /// @param DIE The designated initializer expression.
01570 ///
01571 /// @param DesigIdx  The index of the current designator.
01572 ///
01573 /// @param DeclType  The type of the "current object" (C99 6.7.8p17),
01574 /// into which the designation in @p DIE should refer.
01575 ///
01576 /// @param NextField  If non-NULL and the first designator in @p DIE is
01577 /// a field, this will be set to the field declaration corresponding
01578 /// to the field named by the designator.
01579 ///
01580 /// @param NextElementIndex  If non-NULL and the first designator in @p
01581 /// DIE is an array designator or GNU array-range designator, this
01582 /// will be set to the last index initialized by this designator.
01583 ///
01584 /// @param Index  Index into @p IList where the designated initializer
01585 /// @p DIE occurs.
01586 ///
01587 /// @param StructuredList  The initializer list expression that
01588 /// describes all of the subobject initializers in the order they'll
01589 /// actually be initialized.
01590 ///
01591 /// @returns true if there was an error, false otherwise.
01592 bool
01593 InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
01594                                             InitListExpr *IList,
01595                                             DesignatedInitExpr *DIE,
01596                                             unsigned DesigIdx,
01597                                             QualType &CurrentObjectType,
01598                                           RecordDecl::field_iterator *NextField,
01599                                             llvm::APSInt *NextElementIndex,
01600                                             unsigned &Index,
01601                                             InitListExpr *StructuredList,
01602                                             unsigned &StructuredIndex,
01603                                             bool FinishSubobjectInit,
01604                                             bool TopLevelObject) {
01605   if (DesigIdx == DIE->size()) {
01606     // Check the actual initialization for the designated object type.
01607     bool prevHadError = hadError;
01608 
01609     // Temporarily remove the designator expression from the
01610     // initializer list that the child calls see, so that we don't try
01611     // to re-process the designator.
01612     unsigned OldIndex = Index;
01613     IList->setInit(OldIndex, DIE->getInit());
01614 
01615     CheckSubElementType(Entity, IList, CurrentObjectType, Index,
01616                         StructuredList, StructuredIndex);
01617 
01618     // Restore the designated initializer expression in the syntactic
01619     // form of the initializer list.
01620     if (IList->getInit(OldIndex) != DIE->getInit())
01621       DIE->setInit(IList->getInit(OldIndex));
01622     IList->setInit(OldIndex, DIE);
01623 
01624     return hadError && !prevHadError;
01625   }
01626 
01627   DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
01628   bool IsFirstDesignator = (DesigIdx == 0);
01629   if (!VerifyOnly) {
01630     assert((IsFirstDesignator || StructuredList) &&
01631            "Need a non-designated initializer list to start from");
01632 
01633     // Determine the structural initializer list that corresponds to the
01634     // current subobject.
01635     StructuredList = IsFirstDesignator? SyntacticToSemantic.lookup(IList)
01636       : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
01637                                    StructuredList, StructuredIndex,
01638                                    SourceRange(D->getStartLocation(),
01639                                                DIE->getSourceRange().getEnd()));
01640     assert(StructuredList && "Expected a structured initializer list");
01641   }
01642 
01643   if (D->isFieldDesignator()) {
01644     // C99 6.7.8p7:
01645     //
01646     //   If a designator has the form
01647     //
01648     //      . identifier
01649     //
01650     //   then the current object (defined below) shall have
01651     //   structure or union type and the identifier shall be the
01652     //   name of a member of that type.
01653     const RecordType *RT = CurrentObjectType->getAs<RecordType>();
01654     if (!RT) {
01655       SourceLocation Loc = D->getDotLoc();
01656       if (Loc.isInvalid())
01657         Loc = D->getFieldLoc();
01658       if (!VerifyOnly)
01659         SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
01660           << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
01661       ++Index;
01662       return true;
01663     }
01664 
01665     // Note: we perform a linear search of the fields here, despite
01666     // the fact that we have a faster lookup method, because we always
01667     // need to compute the field's index.
01668     FieldDecl *KnownField = D->getField();
01669     IdentifierInfo *FieldName = D->getFieldName();
01670     unsigned FieldIndex = 0;
01671     RecordDecl::field_iterator
01672       Field = RT->getDecl()->field_begin(),
01673       FieldEnd = RT->getDecl()->field_end();
01674     for (; Field != FieldEnd; ++Field) {
01675       if (Field->isUnnamedBitfield())
01676         continue;
01677 
01678       // If we find a field representing an anonymous field, look in the
01679       // IndirectFieldDecl that follow for the designated initializer.
01680       if (!KnownField && Field->isAnonymousStructOrUnion()) {
01681         if (IndirectFieldDecl *IF =
01682             FindIndirectFieldDesignator(&*Field, FieldName)) {
01683           // In verify mode, don't modify the original.
01684           if (VerifyOnly)
01685             DIE = CloneDesignatedInitExpr(SemaRef, DIE);
01686           ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
01687           D = DIE->getDesignator(DesigIdx);
01688           break;
01689         }
01690       }
01691       if (KnownField && KnownField == &*Field)
01692         break;
01693       if (FieldName && FieldName == Field->getIdentifier())
01694         break;
01695 
01696       ++FieldIndex;
01697     }
01698 
01699     if (Field == FieldEnd) {
01700       if (VerifyOnly) {
01701         ++Index;
01702         return true; // No typo correction when just trying this out.
01703       }
01704 
01705       // There was no normal field in the struct with the designated
01706       // name. Perform another lookup for this name, which may find
01707       // something that we can't designate (e.g., a member function),
01708       // may find nothing, or may find a member of an anonymous
01709       // struct/union.
01710       DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
01711       FieldDecl *ReplacementField = 0;
01712       if (Lookup.first == Lookup.second) {
01713         // Name lookup didn't find anything. Determine whether this
01714         // was a typo for another field name.
01715         FieldInitializerValidatorCCC Validator(RT->getDecl());
01716         TypoCorrection Corrected = SemaRef.CorrectTypo(
01717             DeclarationNameInfo(FieldName, D->getFieldLoc()),
01718             Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, Validator,
01719             RT->getDecl());
01720         if (Corrected) {
01721           std::string CorrectedStr(
01722               Corrected.getAsString(SemaRef.getLangOpts()));
01723           std::string CorrectedQuotedStr(
01724               Corrected.getQuoted(SemaRef.getLangOpts()));
01725           ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
01726           SemaRef.Diag(D->getFieldLoc(),
01727                        diag::err_field_designator_unknown_suggest)
01728             << FieldName << CurrentObjectType << CorrectedQuotedStr
01729             << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
01730           SemaRef.Diag(ReplacementField->getLocation(),
01731                        diag::note_previous_decl) << CorrectedQuotedStr;
01732           hadError = true;
01733         } else {
01734           SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
01735             << FieldName << CurrentObjectType;
01736           ++Index;
01737           return true;
01738         }
01739       }
01740 
01741       if (!ReplacementField) {
01742         // Name lookup found something, but it wasn't a field.
01743         SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
01744           << FieldName;
01745         SemaRef.Diag((*Lookup.first)->getLocation(),
01746                       diag::note_field_designator_found);
01747         ++Index;
01748         return true;
01749       }
01750 
01751       if (!KnownField) {
01752         // The replacement field comes from typo correction; find it
01753         // in the list of fields.
01754         FieldIndex = 0;
01755         Field = RT->getDecl()->field_begin();
01756         for (; Field != FieldEnd; ++Field) {
01757           if (Field->isUnnamedBitfield())
01758             continue;
01759 
01760           if (ReplacementField == &*Field ||
01761               Field->getIdentifier() == ReplacementField->getIdentifier())
01762             break;
01763 
01764           ++FieldIndex;
01765         }
01766       }
01767     }
01768 
01769     // All of the fields of a union are located at the same place in
01770     // the initializer list.
01771     if (RT->getDecl()->isUnion()) {
01772       FieldIndex = 0;
01773       if (!VerifyOnly)
01774         StructuredList->setInitializedFieldInUnion(&*Field);
01775     }
01776 
01777     // Make sure we can use this declaration.
01778     bool InvalidUse;
01779     if (VerifyOnly)
01780       InvalidUse = !SemaRef.CanUseDecl(&*Field);
01781     else
01782       InvalidUse = SemaRef.DiagnoseUseOfDecl(&*Field, D->getFieldLoc());
01783     if (InvalidUse) {
01784       ++Index;
01785       return true;
01786     }
01787 
01788     if (!VerifyOnly) {
01789       // Update the designator with the field declaration.
01790       D->setField(&*Field);
01791 
01792       // Make sure that our non-designated initializer list has space
01793       // for a subobject corresponding to this field.
01794       if (FieldIndex >= StructuredList->getNumInits())
01795         StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
01796     }
01797 
01798     // This designator names a flexible array member.
01799     if (Field->getType()->isIncompleteArrayType()) {
01800       bool Invalid = false;
01801       if ((DesigIdx + 1) != DIE->size()) {
01802         // We can't designate an object within the flexible array
01803         // member (because GCC doesn't allow it).
01804         if (!VerifyOnly) {
01805           DesignatedInitExpr::Designator *NextD
01806             = DIE->getDesignator(DesigIdx + 1);
01807           SemaRef.Diag(NextD->getStartLocation(),
01808                         diag::err_designator_into_flexible_array_member)
01809             << SourceRange(NextD->getStartLocation(),
01810                            DIE->getSourceRange().getEnd());
01811           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
01812             << &*Field;
01813         }
01814         Invalid = true;
01815       }
01816 
01817       if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
01818           !isa<StringLiteral>(DIE->getInit())) {
01819         // The initializer is not an initializer list.
01820         if (!VerifyOnly) {
01821           SemaRef.Diag(DIE->getInit()->getLocStart(),
01822                         diag::err_flexible_array_init_needs_braces)
01823             << DIE->getInit()->getSourceRange();
01824           SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
01825             << &*Field;
01826         }
01827         Invalid = true;
01828       }
01829 
01830       // Check GNU flexible array initializer.
01831       if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), &*Field,
01832                                              TopLevelObject))
01833         Invalid = true;
01834 
01835       if (Invalid) {
01836         ++Index;
01837         return true;
01838       }
01839 
01840       // Initialize the array.
01841       bool prevHadError = hadError;
01842       unsigned newStructuredIndex = FieldIndex;
01843       unsigned OldIndex = Index;
01844       IList->setInit(Index, DIE->getInit());
01845 
01846       InitializedEntity MemberEntity =
01847         InitializedEntity::InitializeMember(&*Field, &Entity);
01848       CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
01849                           StructuredList, newStructuredIndex);
01850 
01851       IList->setInit(OldIndex, DIE);
01852       if (hadError && !prevHadError) {
01853         ++Field;
01854         ++FieldIndex;
01855         if (NextField)
01856           *NextField = Field;
01857         StructuredIndex = FieldIndex;
01858         return true;
01859       }
01860     } else {
01861       // Recurse to check later designated subobjects.
01862       QualType FieldType = Field->getType();
01863       unsigned newStructuredIndex = FieldIndex;
01864 
01865       InitializedEntity MemberEntity =
01866         InitializedEntity::InitializeMember(&*Field, &Entity);
01867       if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
01868                                      FieldType, 0, 0, Index,
01869                                      StructuredList, newStructuredIndex,
01870                                      true, false))
01871         return true;
01872     }
01873 
01874     // Find the position of the next field to be initialized in this
01875     // subobject.
01876     ++Field;
01877     ++FieldIndex;
01878 
01879     // If this the first designator, our caller will continue checking
01880     // the rest of this struct/class/union subobject.
01881     if (IsFirstDesignator) {
01882       if (NextField)
01883         *NextField = Field;
01884       StructuredIndex = FieldIndex;
01885       return false;
01886     }
01887 
01888     if (!FinishSubobjectInit)
01889       return false;
01890 
01891     // We've already initialized something in the union; we're done.
01892     if (RT->getDecl()->isUnion())
01893       return hadError;
01894 
01895     // Check the remaining fields within this class/struct/union subobject.
01896     bool prevHadError = hadError;
01897 
01898     CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
01899                           StructuredList, FieldIndex);
01900     return hadError && !prevHadError;
01901   }
01902 
01903   // C99 6.7.8p6:
01904   //
01905   //   If a designator has the form
01906   //
01907   //      [ constant-expression ]
01908   //
01909   //   then the current object (defined below) shall have array
01910   //   type and the expression shall be an integer constant
01911   //   expression. If the array is of unknown size, any
01912   //   nonnegative value is valid.
01913   //
01914   // Additionally, cope with the GNU extension that permits
01915   // designators of the form
01916   //
01917   //      [ constant-expression ... constant-expression ]
01918   const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
01919   if (!AT) {
01920     if (!VerifyOnly)
01921       SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
01922         << CurrentObjectType;
01923     ++Index;
01924     return true;
01925   }
01926 
01927   Expr *IndexExpr = 0;
01928   llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
01929   if (D->isArrayDesignator()) {
01930     IndexExpr = DIE->getArrayIndex(*D);
01931     DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
01932     DesignatedEndIndex = DesignatedStartIndex;
01933   } else {
01934     assert(D->isArrayRangeDesignator() && "Need array-range designator");
01935 
01936     DesignatedStartIndex =
01937       DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
01938     DesignatedEndIndex =
01939       DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
01940     IndexExpr = DIE->getArrayRangeEnd(*D);
01941 
01942     // Codegen can't handle evaluating array range designators that have side
01943     // effects, because we replicate the AST value for each initialized element.
01944     // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
01945     // elements with something that has a side effect, so codegen can emit an
01946     // "error unsupported" error instead of miscompiling the app.
01947     if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
01948         DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
01949       FullyStructuredList->sawArrayRangeDesignator();
01950   }
01951 
01952   if (isa<ConstantArrayType>(AT)) {
01953     llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
01954     DesignatedStartIndex
01955       = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
01956     DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
01957     DesignatedEndIndex
01958       = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
01959     DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
01960     if (DesignatedEndIndex >= MaxElements) {
01961       if (!VerifyOnly)
01962         SemaRef.Diag(IndexExpr->getLocStart(),
01963                       diag::err_array_designator_too_large)
01964           << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
01965           << IndexExpr->getSourceRange();
01966       ++Index;
01967       return true;
01968     }
01969   } else {
01970     // Make sure the bit-widths and signedness match.
01971     if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
01972       DesignatedEndIndex
01973         = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
01974     else if (DesignatedStartIndex.getBitWidth() <
01975              DesignatedEndIndex.getBitWidth())
01976       DesignatedStartIndex
01977         = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
01978     DesignatedStartIndex.setIsUnsigned(true);
01979     DesignatedEndIndex.setIsUnsigned(true);
01980   }
01981 
01982   // Make sure that our non-designated initializer list has space
01983   // for a subobject corresponding to this array element.
01984   if (!VerifyOnly &&
01985       DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
01986     StructuredList->resizeInits(SemaRef.Context,
01987                                 DesignatedEndIndex.getZExtValue() + 1);
01988 
01989   // Repeatedly perform subobject initializations in the range
01990   // [DesignatedStartIndex, DesignatedEndIndex].
01991 
01992   // Move to the next designator
01993   unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
01994   unsigned OldIndex = Index;
01995 
01996   InitializedEntity ElementEntity =
01997     InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
01998 
01999   while (DesignatedStartIndex <= DesignatedEndIndex) {
02000     // Recurse to check later designated subobjects.
02001     QualType ElementType = AT->getElementType();
02002     Index = OldIndex;
02003 
02004     ElementEntity.setElementIndex(ElementIndex);
02005     if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
02006                                    ElementType, 0, 0, Index,
02007                                    StructuredList, ElementIndex,
02008                                    (DesignatedStartIndex == DesignatedEndIndex),
02009                                    false))
02010       return true;
02011 
02012     // Move to the next index in the array that we'll be initializing.
02013     ++DesignatedStartIndex;
02014     ElementIndex = DesignatedStartIndex.getZExtValue();
02015   }
02016 
02017   // If this the first designator, our caller will continue checking
02018   // the rest of this array subobject.
02019   if (IsFirstDesignator) {
02020     if (NextElementIndex)
02021       *NextElementIndex = DesignatedStartIndex;
02022     StructuredIndex = ElementIndex;
02023     return false;
02024   }
02025 
02026   if (!FinishSubobjectInit)
02027     return false;
02028 
02029   // Check the remaining elements within this array subobject.
02030   bool prevHadError = hadError;
02031   CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
02032                  /*SubobjectIsDesignatorContext=*/false, Index,
02033                  StructuredList, ElementIndex);
02034   return hadError && !prevHadError;
02035 }
02036 
02037 // Get the structured initializer list for a subobject of type
02038 // @p CurrentObjectType.
02039 InitListExpr *
02040 InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
02041                                             QualType CurrentObjectType,
02042                                             InitListExpr *StructuredList,
02043                                             unsigned StructuredIndex,
02044                                             SourceRange InitRange) {
02045   if (VerifyOnly)
02046     return 0; // No structured list in verification-only mode.
02047   Expr *ExistingInit = 0;
02048   if (!StructuredList)
02049     ExistingInit = SyntacticToSemantic.lookup(IList);
02050   else if (StructuredIndex < StructuredList->getNumInits())
02051     ExistingInit = StructuredList->getInit(StructuredIndex);
02052 
02053   if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
02054     return Result;
02055 
02056   if (ExistingInit) {
02057     // We are creating an initializer list that initializes the
02058     // subobjects of the current object, but there was already an
02059     // initialization that completely initialized the current
02060     // subobject, e.g., by a compound literal:
02061     //
02062     // struct X { int a, b; };
02063     // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
02064     //
02065     // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
02066     // designated initializer re-initializes the whole
02067     // subobject [0], overwriting previous initializers.
02068     SemaRef.Diag(InitRange.getBegin(),
02069                  diag::warn_subobject_initializer_overrides)
02070       << InitRange;
02071     SemaRef.Diag(ExistingInit->getLocStart(),
02072                   diag::note_previous_initializer)
02073       << /*FIXME:has side effects=*/0
02074       << ExistingInit->getSourceRange();
02075   }
02076 
02077   InitListExpr *Result
02078     = new (SemaRef.Context) InitListExpr(SemaRef.Context,
02079                                          InitRange.getBegin(), 0, 0,
02080                                          InitRange.getEnd());
02081 
02082   QualType ResultType = CurrentObjectType;
02083   if (!ResultType->isArrayType())
02084     ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
02085   Result->setType(ResultType);
02086 
02087   // Pre-allocate storage for the structured initializer list.
02088   unsigned NumElements = 0;
02089   unsigned NumInits = 0;
02090   bool GotNumInits = false;
02091   if (!StructuredList) {
02092     NumInits = IList->getNumInits();
02093     GotNumInits = true;
02094   } else if (Index < IList->getNumInits()) {
02095     if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
02096       NumInits = SubList->getNumInits();
02097       GotNumInits = true;
02098     }
02099   }
02100 
02101   if (const ArrayType *AType
02102       = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
02103     if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
02104       NumElements = CAType->getSize().getZExtValue();
02105       // Simple heuristic so that we don't allocate a very large
02106       // initializer with many empty entries at the end.
02107       if (GotNumInits && NumElements > NumInits)
02108         NumElements = 0;
02109     }
02110   } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
02111     NumElements = VType->getNumElements();
02112   else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
02113     RecordDecl *RDecl = RType->getDecl();
02114     if (RDecl->isUnion())
02115       NumElements = 1;
02116     else
02117       NumElements = std::distance(RDecl->field_begin(),
02118                                   RDecl->field_end());
02119   }
02120 
02121   Result->reserveInits(SemaRef.Context, NumElements);
02122 
02123   // Link this new initializer list into the structured initializer
02124   // lists.
02125   if (StructuredList)
02126     StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
02127   else {
02128     Result->setSyntacticForm(IList);
02129     SyntacticToSemantic[IList] = Result;
02130   }
02131 
02132   return Result;
02133 }
02134 
02135 /// Update the initializer at index @p StructuredIndex within the
02136 /// structured initializer list to the value @p expr.
02137 void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
02138                                                   unsigned &StructuredIndex,
02139                                                   Expr *expr) {
02140   // No structured initializer list to update
02141   if (!StructuredList)
02142     return;
02143 
02144   if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
02145                                                   StructuredIndex, expr)) {
02146     // This initializer overwrites a previous initializer. Warn.
02147     SemaRef.Diag(expr->getLocStart(),
02148                   diag::warn_initializer_overrides)
02149       << expr->getSourceRange();
02150     SemaRef.Diag(PrevInit->getLocStart(),
02151                   diag::note_previous_initializer)
02152       << /*FIXME:has side effects=*/0
02153       << PrevInit->getSourceRange();
02154   }
02155 
02156   ++StructuredIndex;
02157 }
02158 
02159 /// Check that the given Index expression is a valid array designator
02160 /// value. This is essentially just a wrapper around
02161 /// VerifyIntegerConstantExpression that also checks for negative values
02162 /// and produces a reasonable diagnostic if there is a
02163 /// failure. Returns the index expression, possibly with an implicit cast
02164 /// added, on success.  If everything went okay, Value will receive the
02165 /// value of the constant expression.
02166 static ExprResult
02167 CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
02168   SourceLocation Loc = Index->getLocStart();
02169 
02170   // Make sure this is an integer constant expression.
02171   ExprResult Result = S.VerifyIntegerConstantExpression(Index, &Value);
02172   if (Result.isInvalid())
02173     return Result;
02174 
02175   if (Value.isSigned() && Value.isNegative())
02176     return S.Diag(Loc, diag::err_array_designator_negative)
02177       << Value.toString(10) << Index->getSourceRange();
02178 
02179   Value.setIsUnsigned(true);
02180   return Result;
02181 }
02182 
02183 ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
02184                                             SourceLocation Loc,
02185                                             bool GNUSyntax,
02186                                             ExprResult Init) {
02187   typedef DesignatedInitExpr::Designator ASTDesignator;
02188 
02189   bool Invalid = false;
02190   SmallVector<ASTDesignator, 32> Designators;
02191   SmallVector<Expr *, 32> InitExpressions;
02192 
02193   // Build designators and check array designator expressions.
02194   for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
02195     const Designator &D = Desig.getDesignator(Idx);
02196     switch (D.getKind()) {
02197     case Designator::FieldDesignator:
02198       Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
02199                                           D.getFieldLoc()));
02200       break;
02201 
02202     case Designator::ArrayDesignator: {
02203       Expr *Index = static_cast<Expr *>(D.getArrayIndex());
02204       llvm::APSInt IndexValue;
02205       if (!Index->isTypeDependent() && !Index->isValueDependent())
02206         Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).take();
02207       if (!Index)
02208         Invalid = true;
02209       else {
02210         Designators.push_back(ASTDesignator(InitExpressions.size(),
02211                                             D.getLBracketLoc(),
02212                                             D.getRBracketLoc()));
02213         InitExpressions.push_back(Index);
02214       }
02215       break;
02216     }
02217 
02218     case Designator::ArrayRangeDesignator: {
02219       Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
02220       Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
02221       llvm::APSInt StartValue;
02222       llvm::APSInt EndValue;
02223       bool StartDependent = StartIndex->isTypeDependent() ||
02224                             StartIndex->isValueDependent();
02225       bool EndDependent = EndIndex->isTypeDependent() ||
02226                           EndIndex->isValueDependent();
02227       if (!StartDependent)
02228         StartIndex =
02229             CheckArrayDesignatorExpr(*this, StartIndex, StartValue).take();
02230       if (!EndDependent)
02231         EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).take();
02232 
02233       if (!StartIndex || !EndIndex)
02234         Invalid = true;
02235       else {
02236         // Make sure we're comparing values with the same bit width.
02237         if (StartDependent || EndDependent) {
02238           // Nothing to compute.
02239         } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
02240           EndValue = EndValue.extend(StartValue.getBitWidth());
02241         else if (StartValue.getBitWidth() < EndValue.getBitWidth())
02242           StartValue = StartValue.extend(EndValue.getBitWidth());
02243 
02244         if (!StartDependent && !EndDependent && EndValue < StartValue) {
02245           Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
02246             << StartValue.toString(10) << EndValue.toString(10)
02247             << StartIndex->getSourceRange() << EndIndex->getSourceRange();
02248           Invalid = true;
02249         } else {
02250           Designators.push_back(ASTDesignator(InitExpressions.size(),
02251                                               D.getLBracketLoc(),
02252                                               D.getEllipsisLoc(),
02253                                               D.getRBracketLoc()));
02254           InitExpressions.push_back(StartIndex);
02255           InitExpressions.push_back(EndIndex);
02256         }
02257       }
02258       break;
02259     }
02260     }
02261   }
02262 
02263   if (Invalid || Init.isInvalid())
02264     return ExprError();
02265 
02266   // Clear out the expressions within the designation.
02267   Desig.ClearExprs(*this);
02268 
02269   DesignatedInitExpr *DIE
02270     = DesignatedInitExpr::Create(Context,
02271                                  Designators.data(), Designators.size(),
02272                                  InitExpressions.data(), InitExpressions.size(),
02273                                  Loc, GNUSyntax, Init.takeAs<Expr>());
02274 
02275   if (!getLangOpts().C99)
02276     Diag(DIE->getLocStart(), diag::ext_designated_init)
02277       << DIE->getSourceRange();
02278 
02279   return Owned(DIE);
02280 }
02281 
02282 //===----------------------------------------------------------------------===//
02283 // Initialization entity
02284 //===----------------------------------------------------------------------===//
02285 
02286 InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
02287                                      const InitializedEntity &Parent)
02288   : Parent(&Parent), Index(Index)
02289 {
02290   if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
02291     Kind = EK_ArrayElement;
02292     Type = AT->getElementType();
02293   } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
02294     Kind = EK_VectorElement;
02295     Type = VT->getElementType();
02296   } else {
02297     const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
02298     assert(CT && "Unexpected type");
02299     Kind = EK_ComplexElement;
02300     Type = CT->getElementType();
02301   }
02302 }
02303 
02304 InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
02305                                                     CXXBaseSpecifier *Base,
02306                                                     bool IsInheritedVirtualBase)
02307 {
02308   InitializedEntity Result;
02309   Result.Kind = EK_Base;
02310   Result.Base = reinterpret_cast<uintptr_t>(Base);
02311   if (IsInheritedVirtualBase)
02312     Result.Base |= 0x01;
02313 
02314   Result.Type = Base->getType();
02315   return Result;
02316 }
02317 
02318 DeclarationName InitializedEntity::getName() const {
02319   switch (getKind()) {
02320   case EK_Parameter: {
02321     ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
02322     return (D ? D->getDeclName() : DeclarationName());
02323   }
02324 
02325   case EK_Variable:
02326   case EK_Member:
02327     return VariableOrMember->getDeclName();
02328 
02329   case EK_LambdaCapture:
02330     return Capture.Var->getDeclName();
02331       
02332   case EK_Result:
02333   case EK_Exception:
02334   case EK_New:
02335   case EK_Temporary:
02336   case EK_Base:
02337   case EK_Delegating:
02338   case EK_ArrayElement:
02339   case EK_VectorElement:
02340   case EK_ComplexElement:
02341   case EK_BlockElement:
02342     return DeclarationName();
02343   }
02344 
02345   llvm_unreachable("Invalid EntityKind!");
02346 }
02347 
02348 DeclaratorDecl *InitializedEntity::getDecl() const {
02349   switch (getKind()) {
02350   case EK_Variable:
02351   case EK_Member:
02352     return VariableOrMember;
02353 
02354   case EK_Parameter:
02355     return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
02356 
02357   case EK_Result:
02358   case EK_Exception:
02359   case EK_New:
02360   case EK_Temporary:
02361   case EK_Base:
02362   case EK_Delegating:
02363   case EK_ArrayElement:
02364   case EK_VectorElement:
02365   case EK_ComplexElement:
02366   case EK_BlockElement:
02367   case EK_LambdaCapture:
02368     return 0;
02369   }
02370 
02371   llvm_unreachable("Invalid EntityKind!");
02372 }
02373 
02374 bool InitializedEntity::allowsNRVO() const {
02375   switch (getKind()) {
02376   case EK_Result:
02377   case EK_Exception:
02378     return LocAndNRVO.NRVO;
02379 
02380   case EK_Variable:
02381   case EK_Parameter:
02382   case EK_Member:
02383   case EK_New:
02384   case EK_Temporary:
02385   case EK_Base:
02386   case EK_Delegating:
02387   case EK_ArrayElement:
02388   case EK_VectorElement:
02389   case EK_ComplexElement:
02390   case EK_BlockElement:
02391   case EK_LambdaCapture:
02392     break;
02393   }
02394 
02395   return false;
02396 }
02397 
02398 //===----------------------------------------------------------------------===//
02399 // Initialization sequence
02400 //===----------------------------------------------------------------------===//
02401 
02402 void InitializationSequence::Step::Destroy() {
02403   switch (Kind) {
02404   case SK_ResolveAddressOfOverloadedFunction:
02405   case SK_CastDerivedToBaseRValue:
02406   case SK_CastDerivedToBaseXValue:
02407   case SK_CastDerivedToBaseLValue:
02408   case SK_BindReference:
02409   case SK_BindReferenceToTemporary:
02410   case SK_ExtraneousCopyToTemporary:
02411   case SK_UserConversion:
02412   case SK_QualificationConversionRValue:
02413   case SK_QualificationConversionXValue:
02414   case SK_QualificationConversionLValue:
02415   case SK_ListInitialization:
02416   case SK_ListConstructorCall:
02417   case SK_UnwrapInitList:
02418   case SK_RewrapInitList:
02419   case SK_ConstructorInitialization:
02420   case SK_ZeroInitialization:
02421   case SK_CAssignment:
02422   case SK_StringInit:
02423   case SK_ObjCObjectConversion:
02424   case SK_ArrayInit:
02425   case SK_ParenthesizedArrayInit:
02426   case SK_PassByIndirectCopyRestore:
02427   case SK_PassByIndirectRestore:
02428   case SK_ProduceObjCObject:
02429   case SK_StdInitializerList:
02430     break;
02431 
02432   case SK_ConversionSequence:
02433     delete ICS;
02434   }
02435 }
02436 
02437 bool InitializationSequence::isDirectReferenceBinding() const {
02438   return !Steps.empty() && Steps.back().Kind == SK_BindReference;
02439 }
02440 
02441 bool InitializationSequence::isAmbiguous() const {
02442   if (!Failed())
02443     return false;
02444 
02445   switch (getFailureKind()) {
02446   case FK_TooManyInitsForReference:
02447   case FK_ArrayNeedsInitList:
02448   case FK_ArrayNeedsInitListOrStringLiteral:
02449   case FK_AddressOfOverloadFailed: // FIXME: Could do better
02450   case FK_NonConstLValueReferenceBindingToTemporary:
02451   case FK_NonConstLValueReferenceBindingToUnrelated:
02452   case FK_RValueReferenceBindingToLValue:
02453   case FK_ReferenceInitDropsQualifiers:
02454   case FK_ReferenceInitFailed:
02455   case FK_ConversionFailed:
02456   case FK_ConversionFromPropertyFailed:
02457   case FK_TooManyInitsForScalar:
02458   case FK_ReferenceBindingToInitList:
02459   case FK_InitListBadDestinationType:
02460   case FK_DefaultInitOfConst:
02461   case FK_Incomplete:
02462   case FK_ArrayTypeMismatch:
02463   case FK_NonConstantArrayInit:
02464   case FK_ListInitializationFailed:
02465   case FK_VariableLengthArrayHasInitializer:
02466   case FK_PlaceholderType:
02467   case FK_InitListElementCopyFailure:
02468   case FK_ExplicitConstructor:
02469     return false;
02470 
02471   case FK_ReferenceInitOverloadFailed:
02472   case FK_UserConversionOverloadFailed:
02473   case FK_ConstructorOverloadFailed:
02474   case FK_ListConstructorOverloadFailed:
02475     return FailedOverloadResult == OR_Ambiguous;
02476   }
02477 
02478   llvm_unreachable("Invalid EntityKind!");
02479 }
02480 
02481 bool InitializationSequence::isConstructorInitialization() const {
02482   return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
02483 }
02484 
02485 void
02486 InitializationSequence
02487 ::AddAddressOverloadResolutionStep(FunctionDecl *Function,
02488                                    DeclAccessPair Found,
02489                                    bool HadMultipleCandidates) {
02490   Step S;
02491   S.Kind = SK_ResolveAddressOfOverloadedFunction;
02492   S.Type = Function->getType();
02493   S.Function.HadMultipleCandidates = HadMultipleCandidates;
02494   S.Function.Function = Function;
02495   S.Function.FoundDecl = Found;
02496   Steps.push_back(S);
02497 }
02498 
02499 void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
02500                                                       ExprValueKind VK) {
02501   Step S;
02502   switch (VK) {
02503   case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
02504   case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
02505   case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
02506   }
02507   S.Type = BaseType;
02508   Steps.push_back(S);
02509 }
02510 
02511 void InitializationSequence::AddReferenceBindingStep(QualType T,
02512                                                      bool BindingTemporary) {
02513   Step S;
02514   S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
02515   S.Type = T;
02516   Steps.push_back(S);
02517 }
02518 
02519 void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
02520   Step S;
02521   S.Kind = SK_ExtraneousCopyToTemporary;
02522   S.Type = T;
02523   Steps.push_back(S);
02524 }
02525 
02526 void
02527 InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
02528                                               DeclAccessPair FoundDecl,
02529                                               QualType T,
02530                                               bool HadMultipleCandidates) {
02531   Step S;
02532   S.Kind = SK_UserConversion;
02533   S.Type = T;
02534   S.Function.HadMultipleCandidates = HadMultipleCandidates;
02535   S.Function.Function = Function;
02536   S.Function.FoundDecl = FoundDecl;
02537   Steps.push_back(S);
02538 }
02539 
02540 void InitializationSequence::AddQualificationConversionStep(QualType Ty,
02541                                                             ExprValueKind VK) {
02542   Step S;
02543   S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
02544   switch (VK) {
02545   case VK_RValue:
02546     S.Kind = SK_QualificationConversionRValue;
02547     break;
02548   case VK_XValue:
02549     S.Kind = SK_QualificationConversionXValue;
02550     break;
02551   case VK_LValue:
02552     S.Kind = SK_QualificationConversionLValue;
02553     break;
02554   }
02555   S.Type = Ty;
02556   Steps.push_back(S);
02557 }
02558 
02559 void InitializationSequence::AddConversionSequenceStep(
02560                                        const ImplicitConversionSequence &ICS,
02561                                                        QualType T) {
02562   Step S;
02563   S.Kind = SK_ConversionSequence;
02564   S.Type = T;
02565   S.ICS = new ImplicitConversionSequence(ICS);
02566   Steps.push_back(S);
02567 }
02568 
02569 void InitializationSequence::AddListInitializationStep(QualType T) {
02570   Step S;
02571   S.Kind = SK_ListInitialization;
02572   S.Type = T;
02573   Steps.push_back(S);
02574 }
02575 
02576 void
02577 InitializationSequence
02578 ::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
02579                                    AccessSpecifier Access,
02580                                    QualType T,
02581                                    bool HadMultipleCandidates,
02582                                    bool FromInitList, bool AsInitList) {
02583   Step S;
02584   S.Kind = FromInitList && !AsInitList ? SK_ListConstructorCall
02585                                        : SK_ConstructorInitialization;
02586   S.Type = T;
02587   S.Function.HadMultipleCandidates = HadMultipleCandidates;
02588   S.Function.Function = Constructor;
02589   S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
02590   Steps.push_back(S);
02591 }
02592 
02593 void InitializationSequence::AddZeroInitializationStep(QualType T) {
02594   Step S;
02595   S.Kind = SK_ZeroInitialization;
02596   S.Type = T;
02597   Steps.push_back(S);
02598 }
02599 
02600 void InitializationSequence::AddCAssignmentStep(QualType T) {
02601   Step S;
02602   S.Kind = SK_CAssignment;
02603   S.Type = T;
02604   Steps.push_back(S);
02605 }
02606 
02607 void InitializationSequence::AddStringInitStep(QualType T) {
02608   Step S;
02609   S.Kind = SK_StringInit;
02610   S.Type = T;
02611   Steps.push_back(S);
02612 }
02613 
02614 void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
02615   Step S;
02616   S.Kind = SK_ObjCObjectConversion;
02617   S.Type = T;
02618   Steps.push_back(S);
02619 }
02620 
02621 void InitializationSequence::AddArrayInitStep(QualType T) {
02622   Step S;
02623   S.Kind = SK_ArrayInit;
02624   S.Type = T;
02625   Steps.push_back(S);
02626 }
02627 
02628 void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
02629   Step S;
02630   S.Kind = SK_ParenthesizedArrayInit;
02631   S.Type = T;
02632   Steps.push_back(S);
02633 }
02634 
02635 void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
02636                                                               bool shouldCopy) {
02637   Step s;
02638   s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
02639                        : SK_PassByIndirectRestore);
02640   s.Type = type;
02641   Steps.push_back(s);
02642 }
02643 
02644 void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
02645   Step S;
02646   S.Kind = SK_ProduceObjCObject;
02647   S.Type = T;
02648   Steps.push_back(S);
02649 }
02650 
02651 void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
02652   Step S;
02653   S.Kind = SK_StdInitializerList;
02654   S.Type = T;
02655   Steps.push_back(S);
02656 }
02657 
02658 void InitializationSequence::RewrapReferenceInitList(QualType T,
02659                                                      InitListExpr *Syntactic) {
02660   assert(Syntactic->getNumInits() == 1 &&
02661          "Can only rewrap trivial init lists.");
02662   Step S;
02663   S.Kind = SK_UnwrapInitList;
02664   S.Type = Syntactic->getInit(0)->getType();
02665   Steps.insert(Steps.begin(), S);
02666 
02667   S.Kind = SK_RewrapInitList;
02668   S.Type = T;
02669   S.WrappingSyntacticList = Syntactic;
02670   Steps.push_back(S);
02671 }
02672 
02673 void InitializationSequence::SetOverloadFailure(FailureKind Failure,
02674                                                 OverloadingResult Result) {
02675   setSequenceKind(FailedSequence);
02676   this->Failure = Failure;
02677   this->FailedOverloadResult = Result;
02678 }
02679 
02680 //===----------------------------------------------------------------------===//
02681 // Attempt initialization
02682 //===----------------------------------------------------------------------===//
02683 
02684 static void MaybeProduceObjCObject(Sema &S,
02685                                    InitializationSequence &Sequence,
02686                                    const InitializedEntity &Entity) {
02687   if (!S.getLangOpts().ObjCAutoRefCount) return;
02688 
02689   /// When initializing a parameter, produce the value if it's marked
02690   /// __attribute__((ns_consumed)).
02691   if (Entity.getKind() == InitializedEntity::EK_Parameter) {
02692     if (!Entity.isParameterConsumed())
02693       return;
02694 
02695     assert(Entity.getType()->isObjCRetainableType() &&
02696            "consuming an object of unretainable type?");
02697     Sequence.AddProduceObjCObjectStep(Entity.getType());
02698 
02699   /// When initializing a return value, if the return type is a
02700   /// retainable type, then returns need to immediately retain the
02701   /// object.  If an autorelease is required, it will be done at the
02702   /// last instant.
02703   } else if (Entity.getKind() == InitializedEntity::EK_Result) {
02704     if (!Entity.getType()->isObjCRetainableType())
02705       return;
02706 
02707     Sequence.AddProduceObjCObjectStep(Entity.getType());
02708   }
02709 }
02710 
02711 /// \brief When initializing from init list via constructor, deal with the
02712 /// empty init list and std::initializer_list special cases.
02713 ///
02714 /// \return True if this was a special case, false otherwise.
02715 static bool TryListConstructionSpecialCases(Sema &S,
02716                                             InitListExpr *List,
02717                                             CXXRecordDecl *DestRecordDecl,
02718                                             QualType DestType,
02719                                             InitializationSequence &Sequence) {
02720   // C++11 [dcl.init.list]p3:
02721   //   List-initialization of an object or reference of type T is defined as
02722   //   follows:
02723   //   - If T is an aggregate, aggregate initialization is performed.
02724   if (DestType->isAggregateType())
02725     return false;
02726 
02727   //   - Otherwise, if the initializer list has no elements and T is a class
02728   //     type with a default constructor, the object is value-initialized.
02729   if (List->getNumInits() == 0) {
02730     if (CXXConstructorDecl *DefaultConstructor =
02731             S.LookupDefaultConstructor(DestRecordDecl)) {
02732       if (DefaultConstructor->isDeleted() ||
02733           S.isFunctionConsideredUnavailable(DefaultConstructor)) {
02734         // Fake an overload resolution failure.
02735         OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
02736         DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
02737                                               DefaultConstructor->getAccess());
02738         if (FunctionTemplateDecl *ConstructorTmpl =
02739                 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
02740           S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
02741                                          /*ExplicitArgs*/ 0,
02742                                          ArrayRef<Expr*>(), CandidateSet,
02743                                          /*SuppressUserConversions*/ false);
02744         else
02745           S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
02746                                  ArrayRef<Expr*>(), CandidateSet,
02747                                  /*SuppressUserConversions*/ false);
02748         Sequence.SetOverloadFailure(
02749                        InitializationSequence::FK_ListConstructorOverloadFailed,
02750                        OR_Deleted);
02751       } else
02752         Sequence.AddConstructorInitializationStep(DefaultConstructor,
02753                                                 DefaultConstructor->getAccess(),
02754                                                   DestType,
02755                                                   /*MultipleCandidates=*/false,
02756                                                   /*FromInitList=*/true,
02757                                                   /*AsInitList=*/false);
02758       return true;
02759     }
02760   }
02761 
02762   //   - Otherwise, if T is a specialization of std::initializer_list, [...]
02763   QualType E;
02764   if (S.isStdInitializerList(DestType, &E)) {
02765     // Check that each individual element can be copy-constructed. But since we
02766     // have no place to store further information, we'll recalculate everything
02767     // later.
02768     InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
02769         S.Context.getConstantArrayType(E,
02770             llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
02771                         List->getNumInits()),
02772             ArrayType::Normal, 0));
02773     InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
02774         0, HiddenArray);
02775     for (unsigned i = 0, n = List->getNumInits(); i < n; ++i) {
02776       Element.setElementIndex(i);
02777       if (!S.CanPerformCopyInitialization(Element, List->getInit(i))) {
02778         Sequence.SetFailed(
02779             InitializationSequence::FK_InitListElementCopyFailure);
02780         return true;
02781       }
02782     }
02783     Sequence.AddStdInitializerListConstructionStep(DestType);
02784     return true;
02785   }
02786 
02787   // Not a special case.
02788   return false;
02789 }
02790 
02791 static OverloadingResult
02792 ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
02793                            Expr **Args, unsigned NumArgs,
02794                            OverloadCandidateSet &CandidateSet,
02795                            DeclContext::lookup_iterator Con,
02796                            DeclContext::lookup_iterator ConEnd,
02797                            OverloadCandidateSet::iterator &Best,
02798                            bool CopyInitializing, bool AllowExplicit,
02799                            bool OnlyListConstructors, bool InitListSyntax) {
02800   CandidateSet.clear();
02801 
02802   for (; Con != ConEnd; ++Con) {
02803     NamedDecl *D = *Con;
02804     DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
02805     bool SuppressUserConversions = false;
02806 
02807     // Find the constructor (which may be a template).
02808     CXXConstructorDecl *Constructor = 0;
02809     FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
02810     if (ConstructorTmpl)
02811       Constructor = cast<CXXConstructorDecl>(
02812                                            ConstructorTmpl->getTemplatedDecl());
02813     else {
02814       Constructor = cast<CXXConstructorDecl>(D);
02815 
02816       // If we're performing copy initialization using a copy constructor, we
02817       // suppress user-defined conversions on the arguments. We do the same for
02818       // move constructors.
02819       if ((CopyInitializing || (InitListSyntax && NumArgs == 1)) &&
02820           Constructor->isCopyOrMoveConstructor())
02821         SuppressUserConversions = true;
02822     }
02823 
02824     if (!Constructor->isInvalidDecl() &&
02825         (AllowExplicit || !Constructor->isExplicit()) &&
02826         (!OnlyListConstructors || S.isInitListConstructor(Constructor))) {
02827       if (ConstructorTmpl)
02828         S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
02829                                        /*ExplicitArgs*/ 0,
02830                                        llvm::makeArrayRef(Args, NumArgs),
02831                                        CandidateSet, SuppressUserConversions);
02832       else {
02833         // C++ [over.match.copy]p1:
02834         //   - When initializing a temporary to be bound to the first parameter 
02835         //     of a constructor that takes a reference to possibly cv-qualified 
02836         //     T as its first argument, called with a single argument in the 
02837         //     context of direct-initialization, explicit conversion functions
02838         //     are also considered.
02839         bool AllowExplicitConv = AllowExplicit && !CopyInitializing && 
02840                                  NumArgs == 1 &&
02841                                  Constructor->isCopyOrMoveConstructor();
02842         S.AddOverloadCandidate(Constructor, FoundDecl,
02843                                llvm::makeArrayRef(Args, NumArgs), CandidateSet,
02844                                SuppressUserConversions,
02845                                /*PartialOverloading=*/false,
02846                                /*AllowExplicit=*/AllowExplicitConv);
02847       }
02848     }
02849   }
02850 
02851   // Perform overload resolution and return the result.
02852   return CandidateSet.BestViableFunction(S, DeclLoc, Best);
02853 }
02854 
02855 /// \brief Attempt initialization by constructor (C++ [dcl.init]), which
02856 /// enumerates the constructors of the initialized entity and performs overload
02857 /// resolution to select the best.
02858 /// If InitListSyntax is true, this is list-initialization of a non-aggregate
02859 /// class type.
02860 static void TryConstructorInitialization(Sema &S,
02861                                          const InitializedEntity &Entity,
02862                                          const InitializationKind &Kind,
02863                                          Expr **Args, unsigned NumArgs,
02864                                          QualType DestType,
02865                                          InitializationSequence &Sequence,
02866                                          bool InitListSyntax = false) {
02867   assert((!InitListSyntax || (NumArgs == 1 && isa<InitListExpr>(Args[0]))) &&
02868          "InitListSyntax must come with a single initializer list argument.");
02869 
02870   // Check constructor arguments for self reference.
02871   if (DeclaratorDecl *DD = Entity.getDecl())
02872     // Parameters arguments are occassionially constructed with itself,
02873     // for instance, in recursive functions.  Skip them.
02874     if (!isa<ParmVarDecl>(DD))
02875       for (unsigned i = 0; i < NumArgs; ++i)
02876         S.CheckSelfReference(DD, Args[i]);
02877 
02878   // The type we're constructing needs to be complete.
02879   if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
02880     Sequence.setIncompleteTypeFailure(DestType);
02881     return;
02882   }
02883 
02884   const RecordType *DestRecordType = DestType->getAs<RecordType>();
02885   assert(DestRecordType && "Constructor initialization requires record type");
02886   CXXRecordDecl *DestRecordDecl
02887     = cast<CXXRecordDecl>(DestRecordType->getDecl());
02888 
02889   if (InitListSyntax &&
02890       TryListConstructionSpecialCases(S, cast<InitListExpr>(Args[0]),
02891                                       DestRecordDecl, DestType, Sequence))
02892     return;
02893 
02894   // Build the candidate set directly in the initialization sequence
02895   // structure, so that it will persist if we fail.
02896   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
02897 
02898   // Determine whether we are allowed to call explicit constructors or
02899   // explicit conversion operators.
02900   bool AllowExplicit = Kind.AllowExplicit() || InitListSyntax;
02901   bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
02902 
02903   //   - Otherwise, if T is a class type, constructors are considered. The
02904   //     applicable constructors are enumerated, and the best one is chosen
02905   //     through overload resolution.
02906   DeclContext::lookup_iterator ConStart, ConEnd;
02907   llvm::tie(ConStart, ConEnd) = S.LookupConstructors(DestRecordDecl);
02908 
02909   OverloadingResult Result = OR_No_Viable_Function;
02910   OverloadCandidateSet::iterator Best;
02911   bool AsInitializerList = false;
02912 
02913   // C++11 [over.match.list]p1:
02914   //   When objects of non-aggregate type T are list-initialized, overload
02915   //   resolution selects the constructor in two phases:
02916   //   - Initially, the candidate functions are the initializer-list
02917   //     constructors of the class T and the argument list consists of the
02918   //     initializer list as a single argument.
02919   if (InitListSyntax) {
02920     AsInitializerList = true;
02921     Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
02922                                         CandidateSet, ConStart, ConEnd, Best,
02923                                         CopyInitialization, AllowExplicit,
02924                                         /*OnlyListConstructor=*/true,
02925                                         InitListSyntax);
02926 
02927     // Time to unwrap the init list.
02928     InitListExpr *ILE = cast<InitListExpr>(Args[0]);
02929     Args = ILE->getInits();
02930     NumArgs = ILE->getNumInits();
02931   }
02932 
02933   // C++11 [over.match.list]p1:
02934   //   - If no viable initializer-list constructor is found, overload resolution
02935   //     is performed again, where the candidate functions are all the
02936   //     constructors of the class T nad the argument list consists of the
02937   //     elements of the initializer list.
02938   if (Result == OR_No_Viable_Function) {
02939     AsInitializerList = false;
02940     Result = ResolveConstructorOverload(S, Kind.getLocation(), Args, NumArgs,
02941                                         CandidateSet, ConStart, ConEnd, Best,
02942                                         CopyInitialization, AllowExplicit,
02943                                         /*OnlyListConstructors=*/false,
02944                                         InitListSyntax);
02945   }
02946   if (Result) {
02947     Sequence.SetOverloadFailure(InitListSyntax ?
02948                       InitializationSequence::FK_ListConstructorOverloadFailed :
02949                       InitializationSequence::FK_ConstructorOverloadFailed,
02950                                 Result);
02951     return;
02952   }
02953 
02954   // C++0x [dcl.init]p6:
02955   //   If a program calls for the default initialization of an object
02956   //   of a const-qualified type T, T shall be a class type with a
02957   //   user-provided default constructor.
02958   if (Kind.getKind() == InitializationKind::IK_Default &&
02959       Entity.getType().isConstQualified() &&
02960       cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
02961     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
02962     return;
02963   }
02964 
02965   // C++11 [over.match.list]p1:
02966   //   In copy-list-initialization, if an explicit constructor is chosen, the
02967   //   initializer is ill-formed.
02968   CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
02969   if (InitListSyntax && !Kind.AllowExplicit() && CtorDecl->isExplicit()) {
02970     Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
02971     return;
02972   }
02973 
02974   // Add the constructor initialization step. Any cv-qualification conversion is
02975   // subsumed by the initialization.
02976   bool HadMultipleCandidates = (CandidateSet.size() > 1);
02977   Sequence.AddConstructorInitializationStep(CtorDecl,
02978                                             Best->FoundDecl.getAccess(),
02979                                             DestType, HadMultipleCandidates,
02980                                             InitListSyntax, AsInitializerList);
02981 }
02982 
02983 static bool
02984 ResolveOverloadedFunctionForReferenceBinding(Sema &S,
02985                                              Expr *Initializer,
02986                                              QualType &SourceType,
02987                                              QualType &UnqualifiedSourceType,
02988                                              QualType UnqualifiedTargetType,
02989                                              InitializationSequence &Sequence) {
02990   if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
02991         S.Context.OverloadTy) {
02992     DeclAccessPair Found;
02993     bool HadMultipleCandidates = false;
02994     if (FunctionDecl *Fn
02995         = S.ResolveAddressOfOverloadedFunction(Initializer,
02996                                                UnqualifiedTargetType,
02997                                                false, Found,
02998                                                &HadMultipleCandidates)) {
02999       Sequence.AddAddressOverloadResolutionStep(Fn, Found,
03000                                                 HadMultipleCandidates);
03001       SourceType = Fn->getType();
03002       UnqualifiedSourceType = SourceType.getUnqualifiedType();
03003     } else if (!UnqualifiedTargetType->isRecordType()) {
03004       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
03005       return true;
03006     }
03007   }
03008   return false;
03009 }
03010 
03011 static void TryReferenceInitializationCore(Sema &S,
03012                                            const InitializedEntity &Entity,
03013                                            const InitializationKind &Kind,
03014                                            Expr *Initializer,
03015                                            QualType cv1T1, QualType T1,
03016                                            Qualifiers T1Quals,
03017                                            QualType cv2T2, QualType T2,
03018                                            Qualifiers T2Quals,
03019                                            InitializationSequence &Sequence);
03020 
03021 static void TryListInitialization(Sema &S,
03022                                   const InitializedEntity &Entity,
03023                                   const InitializationKind &Kind,
03024                                   InitListExpr *InitList,
03025                                   InitializationSequence &Sequence);
03026 
03027 /// \brief Attempt list initialization of a reference.
03028 static void TryReferenceListInitialization(Sema &S,
03029                                            const InitializedEntity &Entity,
03030                                            const InitializationKind &Kind,
03031                                            InitListExpr *InitList,
03032                                            InitializationSequence &Sequence)
03033 {
03034   // First, catch C++03 where this isn't possible.
03035   if (!S.getLangOpts().CPlusPlus0x) {
03036     Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
03037     return;
03038   }
03039 
03040   QualType DestType = Entity.getType();
03041   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
03042   Qualifiers T1Quals;
03043   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
03044 
03045   // Reference initialization via an initializer list works thus:
03046   // If the initializer list consists of a single element that is
03047   // reference-related to the referenced type, bind directly to that element
03048   // (possibly creating temporaries).
03049   // Otherwise, initialize a temporary with the initializer list and
03050   // bind to that.
03051   if (InitList->getNumInits() == 1) {
03052     Expr *Initializer = InitList->getInit(0);
03053     QualType cv2T2 = Initializer->getType();
03054     Qualifiers T2Quals;
03055     QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
03056 
03057     // If this fails, creating a temporary wouldn't work either.
03058     if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
03059                                                      T1, Sequence))
03060       return;
03061 
03062     SourceLocation DeclLoc = Initializer->getLocStart();
03063     bool dummy1, dummy2, dummy3;
03064     Sema::ReferenceCompareResult RefRelationship
03065       = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
03066                                        dummy2, dummy3);
03067     if (RefRelationship >= Sema::Ref_Related) {
03068       // Try to bind the reference here.
03069       TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
03070                                      T1Quals, cv2T2, T2, T2Quals, Sequence);
03071       if (Sequence)
03072         Sequence.RewrapReferenceInitList(cv1T1, InitList);
03073       return;
03074     }
03075   }
03076 
03077   // Not reference-related. Create a temporary and bind to that.
03078   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
03079 
03080   TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
03081   if (Sequence) {
03082     if (DestType->isRValueReferenceType() ||
03083         (T1Quals.hasConst() && !T1Quals.hasVolatile()))
03084       Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
03085     else
03086       Sequence.SetFailed(
03087           InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
03088   }
03089 }
03090 
03091 /// \brief Attempt list initialization (C++0x [dcl.init.list])
03092 static void TryListInitialization(Sema &S,
03093                                   const InitializedEntity &Entity,
03094                                   const InitializationKind &Kind,
03095                                   InitListExpr *InitList,
03096                                   InitializationSequence &Sequence) {
03097   QualType DestType = Entity.getType();
03098 
03099   // C++ doesn't allow scalar initialization with more than one argument.
03100   // But C99 complex numbers are scalars and it makes sense there.
03101   if (S.getLangOpts().CPlusPlus && DestType->isScalarType() &&
03102       !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
03103     Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
03104     return;
03105   }
03106   if (DestType->isReferenceType()) {
03107     TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
03108     return;
03109   }
03110   if (DestType->isRecordType()) {
03111     if (S.RequireCompleteType(InitList->getLocStart(), DestType, 0)) {
03112       Sequence.setIncompleteTypeFailure(DestType);
03113       return;
03114     }
03115 
03116     if (!DestType->isAggregateType()) {
03117       if (S.getLangOpts().CPlusPlus0x) {
03118         Expr *Arg = InitList;
03119         // A direct-initializer is not list-syntax, i.e. there's no special
03120         // treatment of "A a({1, 2});".
03121         TryConstructorInitialization(S, Entity, Kind, &Arg, 1, DestType, 
03122                                      Sequence,
03123                                Kind.getKind() != InitializationKind::IK_Direct);
03124       } else
03125         Sequence.SetFailed(
03126             InitializationSequence::FK_InitListBadDestinationType);
03127       return;
03128     }
03129   }
03130 
03131   InitListChecker CheckInitList(S, Entity, InitList,
03132           DestType, /*VerifyOnly=*/true,
03133           Kind.getKind() != InitializationKind::IK_DirectList ||
03134             !S.getLangOpts().CPlusPlus0x);
03135   if (CheckInitList.HadError()) {
03136     Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
03137     return;
03138   }
03139 
03140   // Add the list initialization step with the built init list.
03141   Sequence.AddListInitializationStep(DestType);
03142 }
03143 
03144 /// \brief Try a reference initialization that involves calling a conversion
03145 /// function.
03146 static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
03147                                              const InitializedEntity &Entity,
03148                                              const InitializationKind &Kind,
03149                                              Expr *Initializer,
03150                                              bool AllowRValues,
03151                                              InitializationSequence &Sequence) {
03152   QualType DestType = Entity.getType();
03153   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
03154   QualType T1 = cv1T1.getUnqualifiedType();
03155   QualType cv2T2 = Initializer->getType();
03156   QualType T2 = cv2T2.getUnqualifiedType();
03157 
03158   bool DerivedToBase;
03159   bool ObjCConversion;
03160   bool ObjCLifetimeConversion;
03161   assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
03162                                          T1, T2, DerivedToBase,
03163                                          ObjCConversion,
03164                                          ObjCLifetimeConversion) &&
03165          "Must have incompatible references when binding via conversion");
03166   (void)DerivedToBase;
03167   (void)ObjCConversion;
03168   (void)ObjCLifetimeConversion;
03169   
03170   // Build the candidate set directly in the initialization sequence
03171   // structure, so that it will persist if we fail.
03172   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
03173   CandidateSet.clear();
03174 
03175   // Determine whether we are allowed to call explicit constructors or
03176   // explicit conversion operators.
03177   bool AllowExplicit = Kind.AllowExplicit();
03178   bool AllowExplicitConvs = Kind.allowExplicitConversionFunctions();
03179   
03180   const RecordType *T1RecordType = 0;
03181   if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
03182       !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
03183     // The type we're converting to is a class type. Enumerate its constructors
03184     // to see if there is a suitable conversion.
03185     CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
03186 
03187     DeclContext::lookup_iterator Con, ConEnd;
03188     for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
03189          Con != ConEnd; ++Con) {
03190       NamedDecl *D = *Con;
03191       DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
03192 
03193       // Find the constructor (which may be a template).
03194       CXXConstructorDecl *Constructor = 0;
03195       FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
03196       if (ConstructorTmpl)
03197         Constructor = cast<CXXConstructorDecl>(
03198                                          ConstructorTmpl->getTemplatedDecl());
03199       else
03200         Constructor = cast<CXXConstructorDecl>(D);
03201 
03202       if (!Constructor->isInvalidDecl() &&
03203           Constructor->isConvertingConstructor(AllowExplicit)) {
03204         if (ConstructorTmpl)
03205           S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
03206                                          /*ExplicitArgs*/ 0,
03207                                          Initializer, CandidateSet,
03208                                          /*SuppressUserConversions=*/true);
03209         else
03210           S.AddOverloadCandidate(Constructor, FoundDecl,
03211                                  Initializer, CandidateSet,
03212                                  /*SuppressUserConversions=*/true);
03213       }
03214     }
03215   }
03216   if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
03217     return OR_No_Viable_Function;
03218 
03219   const RecordType *T2RecordType = 0;
03220   if ((T2RecordType = T2->getAs<RecordType>()) &&
03221       !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
03222     // The type we're converting from is a class type, enumerate its conversion
03223     // functions.
03224     CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
03225 
03226     const UnresolvedSetImpl *Conversions
03227       = T2RecordDecl->getVisibleConversionFunctions();
03228     for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
03229            E = Conversions->end(); I != E; ++I) {
03230       NamedDecl *D = *I;
03231       CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
03232       if (isa<UsingShadowDecl>(D))
03233         D = cast<UsingShadowDecl>(D)->getTargetDecl();
03234 
03235       FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
03236       CXXConversionDecl *Conv;
03237       if (ConvTemplate)
03238         Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
03239       else
03240         Conv = cast<CXXConversionDecl>(D);
03241 
03242       // If the conversion function doesn't return a reference type,
03243       // it can't be considered for this conversion unless we're allowed to
03244       // consider rvalues.
03245       // FIXME: Do we need to make sure that we only consider conversion
03246       // candidates with reference-compatible results? That might be needed to
03247       // break recursion.
03248       if ((AllowExplicitConvs || !Conv->isExplicit()) &&
03249           (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
03250         if (ConvTemplate)
03251           S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
03252                                            ActingDC, Initializer,
03253                                            DestType, CandidateSet);
03254         else
03255           S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
03256                                    Initializer, DestType, CandidateSet);
03257       }
03258     }
03259   }
03260   if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
03261     return OR_No_Viable_Function;
03262 
03263   SourceLocation DeclLoc = Initializer->getLocStart();
03264 
03265   // Perform overload resolution. If it fails, return the failed result.
03266   OverloadCandidateSet::iterator Best;
03267   if (OverloadingResult Result
03268         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
03269     return Result;
03270 
03271   FunctionDecl *Function = Best->Function;
03272 
03273   // This is the overload that will actually be used for the initialization, so
03274   // mark it as used.
03275   S.MarkFunctionReferenced(DeclLoc, Function);
03276 
03277   // Compute the returned type of the conversion.
03278   if (isa<CXXConversionDecl>(Function))
03279     T2 = Function->getResultType();
03280   else
03281     T2 = cv1T1;
03282 
03283   // Add the user-defined conversion step.
03284   bool HadMultipleCandidates = (CandidateSet.size() > 1);
03285   Sequence.AddUserConversionStep(Function, Best->FoundDecl,
03286                                  T2.getNonLValueExprType(S.Context),
03287                                  HadMultipleCandidates);
03288 
03289   // Determine whether we need to perform derived-to-base or
03290   // cv-qualification adjustments.
03291   ExprValueKind VK = VK_RValue;
03292   if (T2->isLValueReferenceType())
03293     VK = VK_LValue;
03294   else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
03295     VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
03296 
03297   bool NewDerivedToBase = false;
03298   bool NewObjCConversion = false;
03299   bool NewObjCLifetimeConversion = false;
03300   Sema::ReferenceCompareResult NewRefRelationship
03301     = S.CompareReferenceRelationship(DeclLoc, T1,
03302                                      T2.getNonLValueExprType(S.Context),
03303                                      NewDerivedToBase, NewObjCConversion,
03304                                      NewObjCLifetimeConversion);
03305   if (NewRefRelationship == Sema::Ref_Incompatible) {
03306     // If the type we've converted to is not reference-related to the
03307     // type we're looking for, then there is another conversion step
03308     // we need to perform to produce a temporary of the right type
03309     // that we'll be binding to.
03310     ImplicitConversionSequence ICS;
03311     ICS.setStandard();
03312     ICS.Standard = Best->FinalConversion;
03313     T2 = ICS.Standard.getToType(2);
03314     Sequence.AddConversionSequenceStep(ICS, T2);
03315   } else if (NewDerivedToBase)
03316     Sequence.AddDerivedToBaseCastStep(
03317                                 S.Context.getQualifiedType(T1,
03318                                   T2.getNonReferenceType().getQualifiers()),
03319                                       VK);
03320   else if (NewObjCConversion)
03321     Sequence.AddObjCObjectConversionStep(
03322                                 S.Context.getQualifiedType(T1,
03323                                   T2.getNonReferenceType().getQualifiers()));
03324 
03325   if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
03326     Sequence.AddQualificationConversionStep(cv1T1, VK);
03327 
03328   Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
03329   return OR_Success;
03330 }
03331 
03332 static void CheckCXX98CompatAccessibleCopy(Sema &S,
03333                                            const InitializedEntity &Entity,
03334                                            Expr *CurInitExpr);
03335 
03336 /// \brief Attempt reference initialization (C++0x [dcl.init.ref])
03337 static void TryReferenceInitialization(Sema &S,
03338                                        const InitializedEntity &Entity,
03339                                        const InitializationKind &Kind,
03340                                        Expr *Initializer,
03341                                        InitializationSequence &Sequence) {
03342   QualType DestType = Entity.getType();
03343   QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
03344   Qualifiers T1Quals;
03345   QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
03346   QualType cv2T2 = Initializer->getType();
03347   Qualifiers T2Quals;
03348   QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
03349 
03350   // If the initializer is the address of an overloaded function, try
03351   // to resolve the overloaded function. If all goes well, T2 is the
03352   // type of the resulting function.
03353   if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
03354                                                    T1, Sequence))
03355     return;
03356 
03357   // Delegate everything else to a subfunction.
03358   TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
03359                                  T1Quals, cv2T2, T2, T2Quals, Sequence);
03360 }
03361 
03362 /// \brief Reference initialization without resolving overloaded functions.
03363 static void TryReferenceInitializationCore(Sema &S,
03364                                            const InitializedEntity &Entity,
03365                                            const InitializationKind &Kind,
03366                                            Expr *Initializer,
03367                                            QualType cv1T1, QualType T1,
03368                                            Qualifiers T1Quals,
03369                                            QualType cv2T2, QualType T2,
03370                                            Qualifiers T2Quals,
03371                                            InitializationSequence &Sequence) {
03372   QualType DestType = Entity.getType();
03373   SourceLocation DeclLoc = Initializer->getLocStart();
03374   // Compute some basic properties of the types and the initializer.
03375   bool isLValueRef = DestType->isLValueReferenceType();
03376   bool isRValueRef = !isLValueRef;
03377   bool DerivedToBase = false;
03378   bool ObjCConversion = false;
03379   bool ObjCLifetimeConversion = false;
03380   Expr::Classification InitCategory = Initializer->Classify(S.Context);
03381   Sema::ReferenceCompareResult RefRelationship
03382     = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
03383                                      ObjCConversion, ObjCLifetimeConversion);
03384 
03385   // C++0x [dcl.init.ref]p5:
03386   //   A reference to type "cv1 T1" is initialized by an expression of type
03387   //   "cv2 T2" as follows:
03388   //
03389   //     - If the reference is an lvalue reference and the initializer
03390   //       expression
03391   // Note the analogous bullet points for rvlaue refs to functions. Because
03392   // there are no function rvalues in C++, rvalue refs to functions are treated
03393   // like lvalue refs.
03394   OverloadingResult ConvOvlResult = OR_Success;
03395   bool T1Function = T1->isFunctionType();
03396   if (isLValueRef || T1Function) {
03397     if (InitCategory.isLValue() &&
03398         (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
03399          (Kind.isCStyleOrFunctionalCast() &&
03400           RefRelationship == Sema::Ref_Related))) {
03401       //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
03402       //     reference-compatible with "cv2 T2," or
03403       //
03404       // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
03405       // bit-field when we're determining whether the reference initialization
03406       // can occur. However, we do pay attention to whether it is a bit-field
03407       // to decide whether we're actually binding to a temporary created from
03408       // the bit-field.
03409       if (DerivedToBase)
03410         Sequence.AddDerivedToBaseCastStep(
03411                          S.Context.getQualifiedType(T1, T2Quals),
03412                          VK_LValue);
03413       else if (ObjCConversion)
03414         Sequence.AddObjCObjectConversionStep(
03415                                      S.Context.getQualifiedType(T1, T2Quals));
03416 
03417       if (T1Quals != T2Quals)
03418         Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
03419       bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
03420         (Initializer->getBitField() || Initializer->refersToVectorElement());
03421       Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
03422       return;
03423     }
03424 
03425     //     - has a class type (i.e., T2 is a class type), where T1 is not
03426     //       reference-related to T2, and can be implicitly converted to an
03427     //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
03428     //       with "cv3 T3" (this conversion is selected by enumerating the
03429     //       applicable conversion functions (13.3.1.6) and choosing the best
03430     //       one through overload resolution (13.3)),
03431     // If we have an rvalue ref to function type here, the rhs must be
03432     // an rvalue.
03433     if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
03434         (isLValueRef || InitCategory.isRValue())) {
03435       ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
03436                                                        Initializer,
03437                                                    /*AllowRValues=*/isRValueRef,
03438                                                        Sequence);
03439       if (ConvOvlResult == OR_Success)
03440         return;
03441       if (ConvOvlResult != OR_No_Viable_Function) {
03442         Sequence.SetOverloadFailure(
03443                       InitializationSequence::FK_ReferenceInitOverloadFailed,
03444                                     ConvOvlResult);
03445       }
03446     }
03447   }
03448 
03449   //     - Otherwise, the reference shall be an lvalue reference to a
03450   //       non-volatile const type (i.e., cv1 shall be const), or the reference
03451   //       shall be an rvalue reference.
03452   if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
03453     if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
03454       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
03455     else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
03456       Sequence.SetOverloadFailure(
03457                         InitializationSequence::FK_ReferenceInitOverloadFailed,
03458                                   ConvOvlResult);
03459     else
03460       Sequence.SetFailed(InitCategory.isLValue()
03461         ? (RefRelationship == Sema::Ref_Related
03462              ? InitializationSequence::FK_ReferenceInitDropsQualifiers
03463              : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
03464         : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
03465 
03466     return;
03467   }
03468 
03469   //    - If the initializer expression
03470   //      - is an xvalue, class prvalue, array prvalue, or function lvalue and
03471   //        "cv1 T1" is reference-compatible with "cv2 T2"
03472   // Note: functions are handled below.
03473   if (!T1Function &&
03474       (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
03475        (Kind.isCStyleOrFunctionalCast() &&
03476         RefRelationship == Sema::Ref_Related)) &&
03477       (InitCategory.isXValue() ||
03478        (InitCategory.isPRValue() && T2->isRecordType()) ||
03479        (InitCategory.isPRValue() && T2->isArrayType()))) {
03480     ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
03481     if (InitCategory.isPRValue() && T2->isRecordType()) {
03482       // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
03483       // compiler the freedom to perform a copy here or bind to the
03484       // object, while C++0x requires that we bind directly to the
03485       // object. Hence, we always bind to the object without making an
03486       // extra copy. However, in C++03 requires that we check for the
03487       // presence of a suitable copy constructor:
03488       //
03489       //   The constructor that would be used to make the copy shall
03490       //   be callable whether or not the copy is actually done.
03491       if (!S.getLangOpts().CPlusPlus0x && !S.getLangOpts().MicrosoftExt)
03492         Sequence.AddExtraneousCopyToTemporary(cv2T2);
03493       else if (S.getLangOpts().CPlusPlus0x)
03494         CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
03495     }
03496 
03497     if (DerivedToBase)
03498       Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
03499                                         ValueKind);
03500     else if (ObjCConversion)
03501       Sequence.AddObjCObjectConversionStep(
03502                                        S.Context.getQualifiedType(T1, T2Quals));
03503 
03504     if (T1Quals != T2Quals)
03505       Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
03506     Sequence.AddReferenceBindingStep(cv1T1,
03507                                  /*bindingTemporary=*/InitCategory.isPRValue());
03508     return;
03509   }
03510 
03511   //       - has a class type (i.e., T2 is a class type), where T1 is not
03512   //         reference-related to T2, and can be implicitly converted to an
03513   //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
03514   //         where "cv1 T1" is reference-compatible with "cv3 T3",
03515   if (T2->isRecordType()) {
03516     if (RefRelationship == Sema::Ref_Incompatible) {
03517       ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
03518                                                        Kind, Initializer,
03519                                                        /*AllowRValues=*/true,
03520                                                        Sequence);
03521       if (ConvOvlResult)
03522         Sequence.SetOverloadFailure(
03523                       InitializationSequence::FK_ReferenceInitOverloadFailed,
03524                                     ConvOvlResult);
03525 
03526       return;
03527     }
03528 
03529     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
03530     return;
03531   }
03532 
03533   //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
03534   //        from the initializer expression using the rules for a non-reference
03535   //        copy initialization (8.5). The reference is then bound to the
03536   //        temporary. [...]
03537 
03538   // Determine whether we are allowed to call explicit constructors or
03539   // explicit conversion operators.
03540   bool AllowExplicit = Kind.AllowExplicit();
03541 
03542   InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
03543 
03544   ImplicitConversionSequence ICS
03545     = S.TryImplicitConversion(Initializer, TempEntity.getType(),
03546                               /*SuppressUserConversions*/ false,
03547                               AllowExplicit,
03548                               /*FIXME:InOverloadResolution=*/false,
03549                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
03550                               /*AllowObjCWritebackConversion=*/false);
03551   
03552   if (ICS.isBad()) {
03553     // FIXME: Use the conversion function set stored in ICS to turn
03554     // this into an overloading ambiguity diagnostic. However, we need
03555     // to keep that set as an OverloadCandidateSet rather than as some
03556     // other kind of set.
03557     if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
03558       Sequence.SetOverloadFailure(
03559                         InitializationSequence::FK_ReferenceInitOverloadFailed,
03560                                   ConvOvlResult);
03561     else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
03562       Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
03563     else
03564       Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
03565     return;
03566   } else {
03567     Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
03568   }
03569 
03570   //        [...] If T1 is reference-related to T2, cv1 must be the
03571   //        same cv-qualification as, or greater cv-qualification
03572   //        than, cv2; otherwise, the program is ill-formed.
03573   unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
03574   unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
03575   if (RefRelationship == Sema::Ref_Related &&
03576       (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
03577     Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
03578     return;
03579   }
03580 
03581   //   [...] If T1 is reference-related to T2 and the reference is an rvalue
03582   //   reference, the initializer expression shall not be an lvalue.
03583   if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
03584       InitCategory.isLValue()) {
03585     Sequence.SetFailed(
03586                     InitializationSequence::FK_RValueReferenceBindingToLValue);
03587     return;
03588   }
03589 
03590   Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
03591   return;
03592 }
03593 
03594 /// \brief Attempt character array initialization from a string literal
03595 /// (C++ [dcl.init.string], C99 6.7.8).
03596 static void TryStringLiteralInitialization(Sema &S,
03597                                            const InitializedEntity &Entity,
03598                                            const InitializationKind &Kind,
03599                                            Expr *Initializer,
03600                                        InitializationSequence &Sequence) {
03601   Sequence.AddStringInitStep(Entity.getType());
03602 }
03603 
03604 /// \brief Attempt value initialization (C++ [dcl.init]p7).
03605 static void TryValueInitialization(Sema &S,
03606                                    const InitializedEntity &Entity,
03607                                    const InitializationKind &Kind,
03608                                    InitializationSequence &Sequence) {
03609   // C++98 [dcl.init]p5, C++11 [dcl.init]p7:
03610   //
03611   //   To value-initialize an object of type T means:
03612   QualType T = Entity.getType();
03613 
03614   //     -- if T is an array type, then each element is value-initialized;
03615   T = S.Context.getBaseElementType(T);
03616 
03617   if (const RecordType *RT = T->getAs<RecordType>()) {
03618     if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
03619       // C++98:
03620       // -- if T is a class type (clause 9) with a user-declared
03621       //    constructor (12.1), then the default constructor for T is
03622       //    called (and the initialization is ill-formed if T has no
03623       //    accessible default constructor);
03624       if (!S.getLangOpts().CPlusPlus0x) {
03625         if (ClassDecl->hasUserDeclaredConstructor())
03626           // FIXME: we really want to refer to a single subobject of the array,
03627           // but Entity doesn't have a way to capture that (yet).
03628           return TryConstructorInitialization(S, Entity, Kind, 0, 0,
03629                                               T, Sequence);
03630       } else {
03631         // C++11:
03632         // -- if T is a class type (clause 9) with either no default constructor
03633         //    (12.1 [class.ctor]) or a default constructor that is user-provided
03634         //    or deleted, then the object is default-initialized;
03635         CXXConstructorDecl *CD = S.LookupDefaultConstructor(ClassDecl);
03636         if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted())
03637           return TryConstructorInitialization(S, Entity, Kind, 0, 0,
03638                                               T, Sequence);
03639       }
03640 
03641       // -- if T is a (possibly cv-qualified) non-union class type without a
03642       //    user-provided or deleted default constructor, then the object is
03643       //    zero-initialized and, if T has a non-trivial default constructor,
03644       //    default-initialized;
03645       // FIXME: The 'non-union' here is a defect (not yet assigned an issue
03646       // number). Update the quotation when the defect is resolved.
03647       Sequence.AddZeroInitializationStep(Entity.getType());
03648       return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
03649     }
03650   }
03651 
03652   Sequence.AddZeroInitializationStep(Entity.getType());
03653 }
03654 
03655 /// \brief Attempt default initialization (C++ [dcl.init]p6).
03656 static void TryDefaultInitialization(Sema &S,
03657                                      const InitializedEntity &Entity,
03658                                      const InitializationKind &Kind,
03659                                      InitializationSequence &Sequence) {
03660   assert(Kind.getKind() == InitializationKind::IK_Default);
03661 
03662   // C++ [dcl.init]p6:
03663   //   To default-initialize an object of type T means:
03664   //     - if T is an array type, each element is default-initialized;
03665   QualType DestType = S.Context.getBaseElementType(Entity.getType());
03666          
03667   //     - if T is a (possibly cv-qualified) class type (Clause 9), the default
03668   //       constructor for T is called (and the initialization is ill-formed if
03669   //       T has no accessible default constructor);
03670   if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) {
03671     TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
03672     return;
03673   }
03674 
03675   //     - otherwise, no initialization is performed.
03676 
03677   //   If a program calls for the default initialization of an object of
03678   //   a const-qualified type T, T shall be a class type with a user-provided
03679   //   default constructor.
03680   if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) {
03681     Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
03682     return;
03683   }
03684 
03685   // If the destination type has a lifetime property, zero-initialize it.
03686   if (DestType.getQualifiers().hasObjCLifetime()) {
03687     Sequence.AddZeroInitializationStep(Entity.getType());
03688     return;
03689   }
03690 }
03691 
03692 /// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
03693 /// which enumerates all conversion functions and performs overload resolution
03694 /// to select the best.
03695 static void TryUserDefinedConversion(Sema &S,
03696                                      const InitializedEntity &Entity,
03697                                      const InitializationKind &Kind,
03698                                      Expr *Initializer,
03699                                      InitializationSequence &Sequence) {
03700   QualType DestType = Entity.getType();
03701   assert(!DestType->isReferenceType() && "References are handled elsewhere");
03702   QualType SourceType = Initializer->getType();
03703   assert((DestType->isRecordType() || SourceType->isRecordType()) &&
03704          "Must have a class type to perform a user-defined conversion");
03705 
03706   // Build the candidate set directly in the initialization sequence
03707   // structure, so that it will persist if we fail.
03708   OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
03709   CandidateSet.clear();
03710 
03711   // Determine whether we are allowed to call explicit constructors or
03712   // explicit conversion operators.
03713   bool AllowExplicit = Kind.AllowExplicit();
03714 
03715   if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
03716     // The type we're converting to is a class type. Enumerate its constructors
03717     // to see if there is a suitable conversion.
03718     CXXRecordDecl *DestRecordDecl
03719       = cast<CXXRecordDecl>(DestRecordType->getDecl());
03720 
03721     // Try to complete the type we're converting to.
03722     if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
03723       DeclContext::lookup_iterator Con, ConEnd;
03724       for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
03725            Con != ConEnd; ++Con) {
03726         NamedDecl *D = *Con;
03727         DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
03728 
03729         // Find the constructor (which may be a template).
03730         CXXConstructorDecl *Constructor = 0;
03731         FunctionTemplateDecl *ConstructorTmpl
03732           = dyn_cast<FunctionTemplateDecl>(D);
03733         if (ConstructorTmpl)
03734           Constructor = cast<CXXConstructorDecl>(
03735                                            ConstructorTmpl->getTemplatedDecl());
03736         else
03737           Constructor = cast<CXXConstructorDecl>(D);
03738 
03739         if (!Constructor->isInvalidDecl() &&
03740             Constructor->isConvertingConstructor(AllowExplicit)) {
03741           if (ConstructorTmpl)
03742             S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
03743                                            /*ExplicitArgs*/ 0,
03744                                            Initializer, CandidateSet,
03745                                            /*SuppressUserConversions=*/true);
03746           else
03747             S.AddOverloadCandidate(Constructor, FoundDecl,
03748                                    Initializer, CandidateSet,
03749                                    /*SuppressUserConversions=*/true);
03750         }
03751       }
03752     }
03753   }
03754 
03755   SourceLocation DeclLoc = Initializer->getLocStart();
03756 
03757   if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
03758     // The type we're converting from is a class type, enumerate its conversion
03759     // functions.
03760 
03761     // We can only enumerate the conversion functions for a complete type; if
03762     // the type isn't complete, simply skip this step.
03763     if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
03764       CXXRecordDecl *SourceRecordDecl
03765         = cast<CXXRecordDecl>(SourceRecordType->getDecl());
03766 
03767       const UnresolvedSetImpl *Conversions
03768         = SourceRecordDecl->getVisibleConversionFunctions();
03769       for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
03770            E = Conversions->end();
03771            I != E; ++I) {
03772         NamedDecl *D = *I;
03773         CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
03774         if (isa<UsingShadowDecl>(D))
03775           D = cast<UsingShadowDecl>(D)->getTargetDecl();
03776 
03777         FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
03778         CXXConversionDecl *Conv;
03779         if (ConvTemplate)
03780           Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
03781         else
03782           Conv = cast<CXXConversionDecl>(D);
03783 
03784         if (AllowExplicit || !Conv->isExplicit()) {
03785           if (ConvTemplate)
03786             S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
03787                                              ActingDC, Initializer, DestType,
03788                                              CandidateSet);
03789           else
03790             S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
03791                                      Initializer, DestType, CandidateSet);
03792         }
03793       }
03794     }
03795   }
03796 
03797   // Perform overload resolution. If it fails, return the failed result.
03798   OverloadCandidateSet::iterator Best;
03799   if (OverloadingResult Result
03800         = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
03801     Sequence.SetOverloadFailure(
03802                         InitializationSequence::FK_UserConversionOverloadFailed,
03803                                 Result);
03804     return;
03805   }
03806 
03807   FunctionDecl *Function = Best->Function;
03808   S.MarkFunctionReferenced(DeclLoc, Function);
03809   bool HadMultipleCandidates = (CandidateSet.size() > 1);
03810 
03811   if (isa<CXXConstructorDecl>(Function)) {
03812     // Add the user-defined conversion step. Any cv-qualification conversion is
03813     // subsumed by the initialization. Per DR5, the created temporary is of the
03814     // cv-unqualified type of the destination.
03815     Sequence.AddUserConversionStep(Function, Best->FoundDecl,
03816                                    DestType.getUnqualifiedType(),
03817                                    HadMultipleCandidates);
03818     return;
03819   }
03820 
03821   // Add the user-defined conversion step that calls the conversion function.
03822   QualType ConvType = Function->getCallResultType();
03823   if (ConvType->getAs<RecordType>()) {
03824     // If we're converting to a class type, there may be an copy of
03825     // the resulting temporary object (possible to create an object of
03826     // a base class type). That copy is not a separate conversion, so
03827     // we just make a note of the actual destination type (possibly a
03828     // base class of the type returned by the conversion function) and
03829     // let the user-defined conversion step handle the conversion.
03830     Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
03831                                    HadMultipleCandidates);
03832     return;
03833   }
03834 
03835   Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
03836                                  HadMultipleCandidates);
03837 
03838   // If the conversion following the call to the conversion function
03839   // is interesting, add it as a separate step.
03840   if (Best->FinalConversion.First || Best->FinalConversion.Second ||
03841       Best->FinalConversion.Third) {
03842     ImplicitConversionSequence ICS;
03843     ICS.setStandard();
03844     ICS.Standard = Best->FinalConversion;
03845     Sequence.AddConversionSequenceStep(ICS, DestType);
03846   }
03847 }
03848 
03849 /// The non-zero enum values here are indexes into diagnostic alternatives.
03850 enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
03851 
03852 /// Determines whether this expression is an acceptable ICR source.
03853 static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
03854                                          bool isAddressOf) {
03855   // Skip parens.
03856   e = e->IgnoreParens();
03857 
03858   // Skip address-of nodes.
03859   if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
03860     if (op->getOpcode() == UO_AddrOf)
03861       return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
03862 
03863   // Skip certain casts.
03864   } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
03865     switch (ce->getCastKind()) {
03866     case CK_Dependent:
03867     case CK_BitCast:
03868     case CK_LValueBitCast:
03869     case CK_NoOp:
03870       return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
03871 
03872     case CK_ArrayToPointerDecay:
03873       return IIK_nonscalar;
03874 
03875     case CK_NullToPointer:
03876       return IIK_okay;
03877 
03878     default:
03879       break;
03880     }
03881 
03882   // If we have a declaration reference, it had better be a local variable.
03883   } else if (isa<DeclRefExpr>(e)) {
03884     if (!isAddressOf) return IIK_nonlocal;
03885 
03886     VarDecl *var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
03887     if (!var) return IIK_nonlocal;
03888 
03889     return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
03890 
03891   // If we have a conditional operator, check both sides.
03892   } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
03893     if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
03894       return iik;
03895 
03896     return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
03897 
03898   // These are never scalar.
03899   } else if (isa<ArraySubscriptExpr>(e)) {
03900     return IIK_nonscalar;
03901 
03902   // Otherwise, it needs to be a null pointer constant.
03903   } else {
03904     return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
03905             ? IIK_okay : IIK_nonlocal);
03906   }
03907 
03908   return IIK_nonlocal;
03909 }
03910 
03911 /// Check whether the given expression is a valid operand for an
03912 /// indirect copy/restore.
03913 static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
03914   assert(src->isRValue());
03915 
03916   InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
03917   if (iik == IIK_okay) return;
03918 
03919   S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
03920     << ((unsigned) iik - 1)  // shift index into diagnostic explanations
03921     << src->getSourceRange();
03922 }
03923 
03924 /// \brief Determine whether we have compatible array types for the
03925 /// purposes of GNU by-copy array initialization.
03926 static bool hasCompatibleArrayTypes(ASTContext &Context,
03927                                     const ArrayType *Dest, 
03928                                     const ArrayType *Source) {
03929   // If the source and destination array types are equivalent, we're
03930   // done.
03931   if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
03932     return true;
03933 
03934   // Make sure that the element types are the same.
03935   if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
03936     return false;
03937 
03938   // The only mismatch we allow is when the destination is an
03939   // incomplete array type and the source is a constant array type.
03940   return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
03941 }
03942 
03943 static bool tryObjCWritebackConversion(Sema &S,
03944                                        InitializationSequence &Sequence,
03945                                        const InitializedEntity &Entity,
03946                                        Expr *Initializer) {
03947   bool ArrayDecay = false;
03948   QualType ArgType = Initializer->getType();
03949   QualType ArgPointee;
03950   if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
03951     ArrayDecay = true;
03952     ArgPointee = ArgArrayType->getElementType();
03953     ArgType = S.Context.getPointerType(ArgPointee);
03954   }
03955       
03956   // Handle write-back conversion.
03957   QualType ConvertedArgType;
03958   if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
03959                                    ConvertedArgType))
03960     return false;
03961 
03962   // We should copy unless we're passing to an argument explicitly
03963   // marked 'out'.
03964   bool ShouldCopy = true;
03965   if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
03966     ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
03967 
03968   // Do we need an lvalue conversion?
03969   if (ArrayDecay || Initializer->isGLValue()) {
03970     ImplicitConversionSequence ICS;
03971     ICS.setStandard();
03972     ICS.Standard.setAsIdentityConversion();
03973 
03974     QualType ResultType;
03975     if (ArrayDecay) {
03976       ICS.Standard.First = ICK_Array_To_Pointer;
03977       ResultType = S.Context.getPointerType(ArgPointee);
03978     } else {
03979       ICS.Standard.First = ICK_Lvalue_To_Rvalue;
03980       ResultType = Initializer->getType().getNonLValueExprType(S.Context);
03981     }
03982           
03983     Sequence.AddConversionSequenceStep(ICS, ResultType);
03984   }
03985         
03986   Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
03987   return true;
03988 }
03989 
03990 InitializationSequence::InitializationSequence(Sema &S,
03991                                                const InitializedEntity &Entity,
03992                                                const InitializationKind &Kind,
03993                                                Expr **Args,
03994                                                unsigned NumArgs)
03995     : FailedCandidateSet(Kind.getLocation()) {
03996   ASTContext &Context = S.Context;
03997 
03998   // C++0x [dcl.init]p16:
03999   //   The semantics of initializers are as follows. The destination type is
04000   //   the type of the object or reference being initialized and the source
04001   //   type is the type of the initializer expression. The source type is not
04002   //   defined when the initializer is a braced-init-list or when it is a
04003   //   parenthesized list of expressions.
04004   QualType DestType = Entity.getType();
04005 
04006   if (DestType->isDependentType() ||
04007       Expr::hasAnyTypeDependentArguments(llvm::makeArrayRef(Args, NumArgs))) {
04008     SequenceKind = DependentSequence;
04009     return;
04010   }
04011 
04012   // Almost everything is a normal sequence.
04013   setSequenceKind(NormalSequence);
04014 
04015   for (unsigned I = 0; I != NumArgs; ++I)
04016     if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
04017       // FIXME: should we be doing this here?
04018       ExprResult result = S.CheckPlaceholderExpr(Args[I]);
04019       if (result.isInvalid()) {
04020         SetFailed(FK_PlaceholderType);
04021         return;
04022       }
04023       Args[I] = result.take();
04024     }
04025 
04026 
04027   QualType SourceType;
04028   Expr *Initializer = 0;
04029   if (NumArgs == 1) {
04030     Initializer = Args[0];
04031     if (!isa<InitListExpr>(Initializer))
04032       SourceType = Initializer->getType();
04033   }
04034 
04035   //     - If the initializer is a (non-parenthesized) braced-init-list, the
04036   //       object is list-initialized (8.5.4).
04037   if (Kind.getKind() != InitializationKind::IK_Direct) {
04038     if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
04039       TryListInitialization(S, Entity, Kind, InitList, *this);
04040       return;
04041     }
04042   }
04043 
04044   //     - If the destination type is a reference type, see 8.5.3.
04045   if (DestType->isReferenceType()) {
04046     // C++0x [dcl.init.ref]p1:
04047     //   A variable declared to be a T& or T&&, that is, "reference to type T"
04048     //   (8.3.2), shall be initialized by an object, or function, of type T or
04049     //   by an object that can be converted into a T.
04050     // (Therefore, multiple arguments are not permitted.)
04051     if (NumArgs != 1)
04052       SetFailed(FK_TooManyInitsForReference);
04053     else
04054       TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
04055     return;
04056   }
04057 
04058   //     - If the initializer is (), the object is value-initialized.
04059   if (Kind.getKind() == InitializationKind::IK_Value ||
04060       (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
04061     TryValueInitialization(S, Entity, Kind, *this);
04062     return;
04063   }
04064 
04065   // Handle default initialization.
04066   if (Kind.getKind() == InitializationKind::IK_Default) {
04067     TryDefaultInitialization(S, Entity, Kind, *this);
04068     return;
04069   }
04070 
04071   //     - If the destination type is an array of characters, an array of
04072   //       char16_t, an array of char32_t, or an array of wchar_t, and the
04073   //       initializer is a string literal, see 8.5.2.
04074   //     - Otherwise, if the destination type is an array, the program is
04075   //       ill-formed.
04076   if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
04077     if (Initializer && isa<VariableArrayType>(DestAT)) {
04078       SetFailed(FK_VariableLengthArrayHasInitializer);
04079       return;
04080     }
04081 
04082     if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
04083       TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
04084       return;
04085     }
04086 
04087     // Note: as an GNU C extension, we allow initialization of an
04088     // array from a compound literal that creates an array of the same
04089     // type, so long as the initializer has no side effects.
04090     if (!S.getLangOpts().CPlusPlus && Initializer &&
04091         isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
04092         Initializer->getType()->isArrayType()) {
04093       const ArrayType *SourceAT
04094         = Context.getAsArrayType(Initializer->getType());
04095       if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
04096         SetFailed(FK_ArrayTypeMismatch);
04097       else if (Initializer->HasSideEffects(S.Context))
04098         SetFailed(FK_NonConstantArrayInit);
04099       else {
04100         AddArrayInitStep(DestType);
04101       }
04102     }
04103     // Note: as a GNU C++ extension, we allow initialization of a
04104     // class member from a parenthesized initializer list.
04105     else if (S.getLangOpts().CPlusPlus &&
04106              Entity.getKind() == InitializedEntity::EK_Member &&
04107              Initializer && isa<InitListExpr>(Initializer)) {
04108       TryListInitialization(S, Entity, Kind, cast<InitListExpr>(Initializer),
04109                             *this);
04110       AddParenthesizedArrayInitStep(DestType);
04111     } else if (DestAT->getElementType()->isAnyCharacterType())
04112       SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
04113     else
04114       SetFailed(FK_ArrayNeedsInitList);
04115 
04116     return;
04117   }
04118 
04119   // Determine whether we should consider writeback conversions for 
04120   // Objective-C ARC.
04121   bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount &&
04122     Entity.getKind() == InitializedEntity::EK_Parameter;
04123 
04124   // We're at the end of the line for C: it's either a write-back conversion
04125   // or it's a C assignment. There's no need to check anything else.
04126   if (!S.getLangOpts().CPlusPlus) {
04127     // If allowed, check whether this is an Objective-C writeback conversion.
04128     if (allowObjCWritebackConversion &&
04129         tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
04130       return;
04131     }
04132     
04133     // Handle initialization in C
04134     AddCAssignmentStep(DestType);
04135     MaybeProduceObjCObject(S, *this, Entity);
04136     return;
04137   }
04138 
04139   assert(S.getLangOpts().CPlusPlus);
04140       
04141   //     - If the destination type is a (possibly cv-qualified) class type:
04142   if (DestType->isRecordType()) {
04143     //     - If the initialization is direct-initialization, or if it is
04144     //       copy-initialization where the cv-unqualified version of the
04145     //       source type is the same class as, or a derived class of, the
04146     //       class of the destination, constructors are considered. [...]
04147     if (Kind.getKind() == InitializationKind::IK_Direct ||
04148         (Kind.getKind() == InitializationKind::IK_Copy &&
04149          (Context.hasSameUnqualifiedType(SourceType, DestType) ||
04150           S.IsDerivedFrom(SourceType, DestType))))
04151       TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
04152                                    Entity.getType(), *this);
04153     //     - Otherwise (i.e., for the remaining copy-initialization cases),
04154     //       user-defined conversion sequences that can convert from the source
04155     //       type to the destination type or (when a conversion function is
04156     //       used) to a derived class thereof are enumerated as described in
04157     //       13.3.1.4, and the best one is chosen through overload resolution
04158     //       (13.3).
04159     else
04160       TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
04161     return;
04162   }
04163 
04164   if (NumArgs > 1) {
04165     SetFailed(FK_TooManyInitsForScalar);
04166     return;
04167   }
04168   assert(NumArgs == 1 && "Zero-argument case handled above");
04169 
04170   //    - Otherwise, if the source type is a (possibly cv-qualified) class
04171   //      type, conversion functions are considered.
04172   if (!SourceType.isNull() && SourceType->isRecordType()) {
04173     TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
04174     MaybeProduceObjCObject(S, *this, Entity);
04175     return;
04176   }
04177 
04178   //    - Otherwise, the initial value of the object being initialized is the
04179   //      (possibly converted) value of the initializer expression. Standard
04180   //      conversions (Clause 4) will be used, if necessary, to convert the
04181   //      initializer expression to the cv-unqualified version of the
04182   //      destination type; no user-defined conversions are considered.
04183       
04184   ImplicitConversionSequence ICS
04185     = S.TryImplicitConversion(Initializer, Entity.getType(),
04186                               /*SuppressUserConversions*/true,
04187                               /*AllowExplicitConversions*/ false,
04188                               /*InOverloadResolution*/ false,
04189                               /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
04190                               allowObjCWritebackConversion);
04191       
04192   if (ICS.isStandard() && 
04193       ICS.Standard.Second == ICK_Writeback_Conversion) {
04194     // Objective-C ARC writeback conversion.
04195     
04196     // We should copy unless we're passing to an argument explicitly
04197     // marked 'out'.
04198     bool ShouldCopy = true;
04199     if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
04200       ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
04201     
04202     // If there was an lvalue adjustment, add it as a separate conversion.
04203     if (ICS.Standard.First == ICK_Array_To_Pointer ||
04204         ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
04205       ImplicitConversionSequence LvalueICS;
04206       LvalueICS.setStandard();
04207       LvalueICS.Standard.setAsIdentityConversion();
04208       LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
04209       LvalueICS.Standard.First = ICS.Standard.First;
04210       AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
04211     }
04212     
04213     AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
04214   } else if (ICS.isBad()) {
04215     DeclAccessPair dap;
04216     if (Initializer->getType() == Context.OverloadTy && 
04217           !S.ResolveAddressOfOverloadedFunction(Initializer
04218                       , DestType, false, dap))
04219       SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
04220     else
04221       SetFailed(InitializationSequence::FK_ConversionFailed);
04222   } else {
04223     AddConversionSequenceStep(ICS, Entity.getType());
04224 
04225     MaybeProduceObjCObject(S, *this, Entity);
04226   }
04227 }
04228 
04229 InitializationSequence::~InitializationSequence() {
04230   for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
04231                                           StepEnd = Steps.end();
04232        Step != StepEnd; ++Step)
04233     Step->Destroy();
04234 }
04235 
04236 //===----------------------------------------------------------------------===//
04237 // Perform initialization
04238 //===----------------------------------------------------------------------===//
04239 static Sema::AssignmentAction
04240 getAssignmentAction(const InitializedEntity &Entity) {
04241   switch(Entity.getKind()) {
04242   case InitializedEntity::EK_Variable:
04243   case InitializedEntity::EK_New:
04244   case InitializedEntity::EK_Exception:
04245   case InitializedEntity::EK_Base:
04246   case InitializedEntity::EK_Delegating:
04247     return Sema::AA_Initializing;
04248 
04249   case InitializedEntity::EK_Parameter:
04250     if (Entity.getDecl() &&
04251         isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
04252       return Sema::AA_Sending;
04253 
04254     return Sema::AA_Passing;
04255 
04256   case InitializedEntity::EK_Result:
04257     return Sema::AA_Returning;
04258 
04259   case InitializedEntity::EK_Temporary:
04260     // FIXME: Can we tell apart casting vs. converting?
04261     return Sema::AA_Casting;
04262 
04263   case InitializedEntity::EK_Member:
04264   case InitializedEntity::EK_ArrayElement:
04265   case InitializedEntity::EK_VectorElement:
04266   case InitializedEntity::EK_ComplexElement:
04267   case InitializedEntity::EK_BlockElement:
04268   case InitializedEntity::EK_LambdaCapture:
04269     return Sema::AA_Initializing;
04270   }
04271 
04272   llvm_unreachable("Invalid EntityKind!");
04273 }
04274 
04275 /// \brief Whether we should binding a created object as a temporary when
04276 /// initializing the given entity.
04277 static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
04278   switch (Entity.getKind()) {
04279   case InitializedEntity::EK_ArrayElement:
04280   case InitializedEntity::EK_Member:
04281   case InitializedEntity::EK_Result:
04282   case InitializedEntity::EK_New:
04283   case InitializedEntity::EK_Variable:
04284   case InitializedEntity::EK_Base:
04285   case InitializedEntity::EK_Delegating:
04286   case InitializedEntity::EK_VectorElement:
04287   case InitializedEntity::EK_ComplexElement:
04288   case InitializedEntity::EK_Exception:
04289   case InitializedEntity::EK_BlockElement:
04290   case InitializedEntity::EK_LambdaCapture:
04291     return false;
04292 
04293   case InitializedEntity::EK_Parameter:
04294   case InitializedEntity::EK_Temporary:
04295     return true;
04296   }
04297 
04298   llvm_unreachable("missed an InitializedEntity kind?");
04299 }
04300 
04301 /// \brief Whether the given entity, when initialized with an object
04302 /// created for that initialization, requires destruction.
04303 static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
04304   switch (Entity.getKind()) {
04305     case InitializedEntity::EK_Member:
04306     case InitializedEntity::EK_Result:
04307     case InitializedEntity::EK_New:
04308     case InitializedEntity::EK_Base:
04309     case InitializedEntity::EK_Delegating:
04310     case InitializedEntity::EK_VectorElement:
04311     case InitializedEntity::EK_ComplexElement:
04312     case InitializedEntity::EK_BlockElement:
04313     case InitializedEntity::EK_LambdaCapture:
04314       return false;
04315 
04316     case InitializedEntity::EK_Variable:
04317     case InitializedEntity::EK_Parameter:
04318     case InitializedEntity::EK_Temporary:
04319     case InitializedEntity::EK_ArrayElement:
04320     case InitializedEntity::EK_Exception:
04321       return true;
04322   }
04323 
04324   llvm_unreachable("missed an InitializedEntity kind?");
04325 }
04326 
04327 /// \brief Look for copy and move constructors and constructor templates, for
04328 /// copying an object via direct-initialization (per C++11 [dcl.init]p16).
04329 static void LookupCopyAndMoveConstructors(Sema &S,
04330                                           OverloadCandidateSet &CandidateSet,
04331                                           CXXRecordDecl *Class,
04332                                           Expr *CurInitExpr) {
04333   DeclContext::lookup_iterator Con, ConEnd;
04334   for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
04335        Con != ConEnd; ++Con) {
04336     CXXConstructorDecl *Constructor = 0;
04337 
04338     if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
04339       // Handle copy/moveconstructors, only.
04340       if (!Constructor || Constructor->isInvalidDecl() ||
04341           !Constructor->isCopyOrMoveConstructor() ||
04342           !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
04343         continue;
04344 
04345       DeclAccessPair FoundDecl
04346         = DeclAccessPair::make(Constructor, Constructor->getAccess());
04347       S.AddOverloadCandidate(Constructor, FoundDecl,
04348                              CurInitExpr, CandidateSet);
04349       continue;
04350     }
04351 
04352     // Handle constructor templates.
04353     FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
04354     if (ConstructorTmpl->isInvalidDecl())
04355       continue;
04356 
04357     Constructor = cast<CXXConstructorDecl>(
04358                                          ConstructorTmpl->getTemplatedDecl());
04359     if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
04360       continue;
04361 
04362     // FIXME: Do we need to limit this to copy-constructor-like
04363     // candidates?
04364     DeclAccessPair FoundDecl
04365       = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
04366     S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
04367                                    CurInitExpr, CandidateSet, true);
04368   }
04369 }
04370 
04371 /// \brief Get the location at which initialization diagnostics should appear.
04372 static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
04373                                            Expr *Initializer) {
04374   switch (Entity.getKind()) {
04375   case InitializedEntity::EK_Result:
04376     return Entity.getReturnLoc();
04377 
04378   case InitializedEntity::EK_Exception:
04379     return Entity.getThrowLoc();
04380 
04381   case InitializedEntity::EK_Variable:
04382     return Entity.getDecl()->getLocation();
04383 
04384   case InitializedEntity::EK_LambdaCapture:
04385     return Entity.getCaptureLoc();
04386       
04387   case InitializedEntity::EK_ArrayElement:
04388   case InitializedEntity::EK_Member:
04389   case InitializedEntity::EK_Parameter:
04390   case InitializedEntity::EK_Temporary:
04391   case InitializedEntity::EK_New:
04392   case InitializedEntity::EK_Base:
04393   case InitializedEntity::EK_Delegating:
04394   case InitializedEntity::EK_VectorElement:
04395   case InitializedEntity::EK_ComplexElement:
04396   case InitializedEntity::EK_BlockElement:
04397     return Initializer->getLocStart();
04398   }
04399   llvm_unreachable("missed an InitializedEntity kind?");
04400 }
04401 
04402 /// \brief Make a (potentially elidable) temporary copy of the object
04403 /// provided by the given initializer by calling the appropriate copy
04404 /// constructor.
04405 ///
04406 /// \param S The Sema object used for type-checking.
04407 ///
04408 /// \param T The type of the temporary object, which must either be
04409 /// the type of the initializer expression or a superclass thereof.
04410 ///
04411 /// \param Enter The entity being initialized.
04412 ///
04413 /// \param CurInit The initializer expression.
04414 ///
04415 /// \param IsExtraneousCopy Whether this is an "extraneous" copy that
04416 /// is permitted in C++03 (but not C++0x) when binding a reference to
04417 /// an rvalue.
04418 ///
04419 /// \returns An expression that copies the initializer expression into
04420 /// a temporary object, or an error expression if a copy could not be
04421 /// created.
04422 static ExprResult CopyObject(Sema &S,
04423                              QualType T,
04424                              const InitializedEntity &Entity,
04425                              ExprResult CurInit,
04426                              bool IsExtraneousCopy) {
04427   // Determine which class type we're copying to.
04428   Expr *CurInitExpr = (Expr *)CurInit.get();
04429   CXXRecordDecl *Class = 0;
04430   if (const RecordType *Record = T->getAs<RecordType>())
04431     Class = cast<CXXRecordDecl>(Record->getDecl());
04432   if (!Class)
04433     return move(CurInit);
04434 
04435   // C++0x [class.copy]p32:
04436   //   When certain criteria are met, an implementation is allowed to
04437   //   omit the copy/move construction of a class object, even if the
04438   //   copy/move constructor and/or destructor for the object have
04439   //   side effects. [...]
04440   //     - when a temporary class object that has not been bound to a
04441   //       reference (12.2) would be copied/moved to a class object
04442   //       with the same cv-unqualified type, the copy/move operation
04443   //       can be omitted by constructing the temporary object
04444   //       directly into the target of the omitted copy/move
04445   //
04446   // Note that the other three bullets are handled elsewhere. Copy
04447   // elision for return statements and throw expressions are handled as part
04448   // of constructor initialization, while copy elision for exception handlers
04449   // is handled by the run-time.
04450   bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
04451   SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
04452 
04453   // Make sure that the type we are copying is complete.
04454   if (S.RequireCompleteType(Loc, T, diag::err_temp_copy_incomplete))
04455     return move(CurInit);
04456 
04457   // Perform overload resolution using the class's copy/move constructors.
04458   // Only consider constructors and constructor templates. Per
04459   // C++0x [dcl.init]p16, second bullet to class types, this initialization
04460   // is direct-initialization.
04461   OverloadCandidateSet CandidateSet(Loc);
04462   LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
04463 
04464   bool HadMultipleCandidates = (CandidateSet.size() > 1);
04465 
04466   OverloadCandidateSet::iterator Best;
04467   switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
04468   case OR_Success:
04469     break;
04470 
04471   case OR_No_Viable_Function:
04472     S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
04473            ? diag::ext_rvalue_to_reference_temp_copy_no_viable
04474            : diag::err_temp_copy_no_viable)
04475       << (int)Entity.getKind() << CurInitExpr->getType()
04476       << CurInitExpr->getSourceRange();
04477     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
04478     if (!IsExtraneousCopy || S.isSFINAEContext())
04479       return ExprError();
04480     return move(CurInit);
04481 
04482   case OR_Ambiguous:
04483     S.Diag(Loc, diag::err_temp_copy_ambiguous)
04484       << (int)Entity.getKind() << CurInitExpr->getType()
04485       << CurInitExpr->getSourceRange();
04486     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
04487     return ExprError();
04488 
04489   case OR_Deleted:
04490     S.Diag(Loc, diag::err_temp_copy_deleted)
04491       << (int)Entity.getKind() << CurInitExpr->getType()
04492       << CurInitExpr->getSourceRange();
04493     S.NoteDeletedFunction(Best->Function);
04494     return ExprError();
04495   }
04496 
04497   CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
04498   ASTOwningVector<Expr*> ConstructorArgs(S);
04499   CurInit.release(); // Ownership transferred into MultiExprArg, below.
04500 
04501   S.CheckConstructorAccess(Loc, Constructor, Entity,
04502                            Best->FoundDecl.getAccess(), IsExtraneousCopy);
04503 
04504   if (IsExtraneousCopy) {
04505     // If this is a totally extraneous copy for C++03 reference
04506     // binding purposes, just return the original initialization
04507     // expression. We don't generate an (elided) copy operation here
04508     // because doing so would require us to pass down a flag to avoid
04509     // infinite recursion, where each step adds another extraneous,
04510     // elidable copy.
04511 
04512     // Instantiate the default arguments of any extra parameters in
04513     // the selected copy constructor, as if we were going to create a
04514     // proper call to the copy constructor.
04515     for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
04516       ParmVarDecl *Parm = Constructor->getParamDecl(I);
04517       if (S.RequireCompleteType(Loc, Parm->getType(),
04518                                 diag::err_call_incomplete_argument))
04519         break;
04520 
04521       // Build the default argument expression; we don't actually care
04522       // if this succeeds or not, because this routine will complain
04523       // if there was a problem.
04524       S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
04525     }
04526 
04527     return S.Owned(CurInitExpr);
04528   }
04529 
04530   S.MarkFunctionReferenced(Loc, Constructor);
04531 
04532   // Determine the arguments required to actually perform the
04533   // constructor call (we might have derived-to-base conversions, or
04534   // the copy constructor may have default arguments).
04535   if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
04536                                 Loc, ConstructorArgs))
04537     return ExprError();
04538 
04539   // Actually perform the constructor call.
04540   CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
04541                                     move_arg(ConstructorArgs),
04542                                     HadMultipleCandidates,
04543                                     /*ZeroInit*/ false,
04544                                     CXXConstructExpr::CK_Complete,
04545                                     SourceRange());
04546 
04547   // If we're supposed to bind temporaries, do so.
04548   if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
04549     CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
04550   return move(CurInit);
04551 }
04552 
04553 /// \brief Check whether elidable copy construction for binding a reference to
04554 /// a temporary would have succeeded if we were building in C++98 mode, for
04555 /// -Wc++98-compat.
04556 static void CheckCXX98CompatAccessibleCopy(Sema &S,
04557                                            const InitializedEntity &Entity,
04558                                            Expr *CurInitExpr) {
04559   assert(S.getLangOpts().CPlusPlus0x);
04560 
04561   const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
04562   if (!Record)
04563     return;
04564 
04565   SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
04566   if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
04567         == DiagnosticsEngine::Ignored)
04568     return;
04569 
04570   // Find constructors which would have been considered.
04571   OverloadCandidateSet CandidateSet(Loc);
04572   LookupCopyAndMoveConstructors(
04573       S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
04574 
04575   // Perform overload resolution.
04576   OverloadCandidateSet::iterator Best;
04577   OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
04578 
04579   PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
04580     << OR << (int)Entity.getKind() << CurInitExpr->getType()
04581     << CurInitExpr->getSourceRange();
04582 
04583   switch (OR) {
04584   case OR_Success:
04585     S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
04586                              Entity, Best->FoundDecl.getAccess(), Diag);
04587     // FIXME: Check default arguments as far as that's possible.
04588     break;
04589 
04590   case OR_No_Viable_Function:
04591     S.Diag(Loc, Diag);
04592     CandidateSet.NoteCandidates(S, OCD_AllCandidates, CurInitExpr);
04593     break;
04594 
04595   case OR_Ambiguous:
04596     S.Diag(Loc, Diag);
04597     CandidateSet.NoteCandidates(S, OCD_ViableCandidates, CurInitExpr);
04598     break;
04599 
04600   case OR_Deleted:
04601     S.Diag(Loc, Diag);
04602     S.NoteDeletedFunction(Best->Function);
04603     break;
04604   }
04605 }
04606 
04607 void InitializationSequence::PrintInitLocationNote(Sema &S,
04608                                               const InitializedEntity &Entity) {
04609   if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
04610     if (Entity.getDecl()->getLocation().isInvalid())
04611       return;
04612 
04613     if (Entity.getDecl()->getDeclName())
04614       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
04615         << Entity.getDecl()->getDeclName();
04616     else
04617       S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
04618   }
04619 }
04620 
04621 static bool isReferenceBinding(const InitializationSequence::Step &s) {
04622   return s.Kind == InitializationSequence::SK_BindReference ||
04623          s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
04624 }
04625 
04626 static ExprResult
04627 PerformConstructorInitialization(Sema &S,
04628                                  const InitializedEntity &Entity,
04629                                  const InitializationKind &Kind,
04630                                  MultiExprArg Args,
04631                                  const InitializationSequence::Step& Step,
04632                                  bool &ConstructorInitRequiresZeroInit) {
04633   unsigned NumArgs = Args.size();
04634   CXXConstructorDecl *Constructor
04635     = cast<CXXConstructorDecl>(Step.Function.Function);
04636   bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
04637 
04638   // Build a call to the selected constructor.
04639   ASTOwningVector<Expr*> ConstructorArgs(S);
04640   SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
04641                          ? Kind.getEqualLoc()
04642                          : Kind.getLocation();
04643 
04644   if (Kind.getKind() == InitializationKind::IK_Default) {
04645     // Force even a trivial, implicit default constructor to be
04646     // semantically checked. We do this explicitly because we don't build
04647     // the definition for completely trivial constructors.
04648     assert(Constructor->getParent() && "No parent class for constructor.");
04649     if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
04650         Constructor->isTrivial() && !Constructor->isUsed(false))
04651       S.DefineImplicitDefaultConstructor(Loc, Constructor);
04652   }
04653 
04654   ExprResult CurInit = S.Owned((Expr *)0);
04655 
04656   // C++ [over.match.copy]p1:
04657   //   - When initializing a temporary to be bound to the first parameter 
04658   //     of a constructor that takes a reference to possibly cv-qualified 
04659   //     T as its first argument, called with a single argument in the 
04660   //     context of direct-initialization, explicit conversion functions
04661   //     are also considered.
04662   bool AllowExplicitConv = Kind.AllowExplicit() && !Kind.isCopyInit() &&
04663                            Args.size() == 1 && 
04664                            Constructor->isCopyOrMoveConstructor();
04665 
04666   // Determine the arguments required to actually perform the constructor
04667   // call.
04668   if (S.CompleteConstructorCall(Constructor, move(Args),
04669                                 Loc, ConstructorArgs,
04670                                 AllowExplicitConv))
04671     return ExprError();
04672 
04673 
04674   if (Entity.getKind() == InitializedEntity::EK_Temporary &&
04675       (Kind.getKind() == InitializationKind::IK_DirectList ||
04676        (NumArgs != 1 && // FIXME: Hack to work around cast weirdness
04677         (Kind.getKind() == InitializationKind::IK_Direct ||
04678          Kind.getKind() == InitializationKind::IK_Value)))) {
04679     // An explicitly-constructed temporary, e.g., X(1, 2).
04680     unsigned NumExprs = ConstructorArgs.size();
04681     Expr **Exprs = (Expr **)ConstructorArgs.take();
04682     S.MarkFunctionReferenced(Loc, Constructor);
04683     S.DiagnoseUseOfDecl(Constructor, Loc);
04684 
04685     TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
04686     if (!TSInfo)
04687       TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
04688     SourceRange ParenRange;
04689     if (Kind.getKind() != InitializationKind::IK_DirectList)
04690       ParenRange = Kind.getParenRange();
04691 
04692     CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
04693                                                              Constructor,
04694                                                              TSInfo,
04695                                                              Exprs,
04696                                                              NumExprs,
04697                                                              ParenRange,
04698                                                      HadMultipleCandidates,
04699                                          ConstructorInitRequiresZeroInit));
04700   } else {
04701     CXXConstructExpr::ConstructionKind ConstructKind =
04702       CXXConstructExpr::CK_Complete;
04703 
04704     if (Entity.getKind() == InitializedEntity::EK_Base) {
04705       ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
04706         CXXConstructExpr::CK_VirtualBase :
04707         CXXConstructExpr::CK_NonVirtualBase;
04708     } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
04709       ConstructKind = CXXConstructExpr::CK_Delegating;
04710     }
04711 
04712     // Only get the parenthesis range if it is a direct construction.
04713     SourceRange parenRange =
04714         Kind.getKind() == InitializationKind::IK_Direct ?
04715         Kind.getParenRange() : SourceRange();
04716 
04717     // If the entity allows NRVO, mark the construction as elidable
04718     // unconditionally.
04719     if (Entity.allowsNRVO())
04720       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
04721                                         Constructor, /*Elidable=*/true,
04722                                         move_arg(ConstructorArgs),
04723                                         HadMultipleCandidates,
04724                                         ConstructorInitRequiresZeroInit,
04725                                         ConstructKind,
04726                                         parenRange);
04727     else
04728       CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
04729                                         Constructor,
04730                                         move_arg(ConstructorArgs),
04731                                         HadMultipleCandidates,
04732                                         ConstructorInitRequiresZeroInit,
04733                                         ConstructKind,
04734                                         parenRange);
04735   }
04736   if (CurInit.isInvalid())
04737     return ExprError();
04738 
04739   // Only check access if all of that succeeded.
04740   S.CheckConstructorAccess(Loc, Constructor, Entity,
04741                            Step.Function.FoundDecl.getAccess());
04742   S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
04743 
04744   if (shouldBindAsTemporary(Entity))
04745     CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
04746 
04747   return move(CurInit);
04748 }
04749 
04750 ExprResult
04751 InitializationSequence::Perform(Sema &S,
04752                                 const InitializedEntity &Entity,
04753                                 const InitializationKind &Kind,
04754                                 MultiExprArg Args,
04755                                 QualType *ResultType) {
04756   if (Failed()) {
04757     unsigned NumArgs = Args.size();
04758     Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
04759     return ExprError();
04760   }
04761 
04762   if (getKind() == DependentSequence) {
04763     // If the declaration is a non-dependent, incomplete array type
04764     // that has an initializer, then its type will be completed once
04765     // the initializer is instantiated.
04766     if (ResultType && !Entity.getType()->isDependentType() &&
04767         Args.size() == 1) {
04768       QualType DeclType = Entity.getType();
04769       if (const IncompleteArrayType *ArrayT
04770                            = S.Context.getAsIncompleteArrayType(DeclType)) {
04771         // FIXME: We don't currently have the ability to accurately
04772         // compute the length of an initializer list without
04773         // performing full type-checking of the initializer list
04774         // (since we have to determine where braces are implicitly
04775         // introduced and such).  So, we fall back to making the array
04776         // type a dependently-sized array type with no specified
04777         // bound.
04778         if (isa<InitListExpr>((Expr *)Args.get()[0])) {
04779           SourceRange Brackets;
04780 
04781           // Scavange the location of the brackets from the entity, if we can.
04782           if (DeclaratorDecl *DD = Entity.getDecl()) {
04783             if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
04784               TypeLoc TL = TInfo->getTypeLoc();
04785               if (IncompleteArrayTypeLoc *ArrayLoc
04786                                       = dyn_cast<IncompleteArrayTypeLoc>(&TL))
04787               Brackets = ArrayLoc->getBracketsRange();
04788             }
04789           }
04790 
04791           *ResultType
04792             = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
04793                                                    /*NumElts=*/0,
04794                                                    ArrayT->getSizeModifier(),
04795                                        ArrayT->getIndexTypeCVRQualifiers(),
04796                                                    Brackets);
04797         }
04798 
04799       }
04800     }
04801     if (Kind.getKind() == InitializationKind::IK_Direct &&
04802         !Kind.isExplicitCast()) {
04803       // Rebuild the ParenListExpr.
04804       SourceRange ParenRange = Kind.getParenRange();
04805       return S.ActOnParenListExpr(ParenRange.getBegin(), ParenRange.getEnd(),
04806                                   move(Args));
04807     }
04808     assert(Kind.getKind() == InitializationKind::IK_Copy ||
04809            Kind.isExplicitCast() || 
04810            Kind.getKind() == InitializationKind::IK_DirectList);
04811     return ExprResult(Args.release()[0]);
04812   }
04813 
04814   // No steps means no initialization.
04815   if (Steps.empty())
04816     return S.Owned((Expr *)0);
04817 
04818   if (S.getLangOpts().CPlusPlus0x && Entity.getType()->isReferenceType() &&
04819       Args.size() == 1 && isa<InitListExpr>(Args.get()[0]) &&
04820       Entity.getKind() != InitializedEntity::EK_Parameter) {
04821     // Produce a C++98 compatibility warning if we are initializing a reference
04822     // from an initializer list. For parameters, we produce a better warning
04823     // elsewhere.
04824     Expr *Init = Args.get()[0];
04825     S.Diag(Init->getLocStart(), diag::warn_cxx98_compat_reference_list_init)
04826       << Init->getSourceRange();
04827   }
04828 
04829   QualType DestType = Entity.getType().getNonReferenceType();
04830   // FIXME: Ugly hack around the fact that Entity.getType() is not
04831   // the same as Entity.getDecl()->getType() in cases involving type merging,
04832   //  and we want latter when it makes sense.
04833   if (ResultType)
04834     *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
04835                                      Entity.getType();
04836 
04837   ExprResult CurInit = S.Owned((Expr *)0);
04838 
04839   // For initialization steps that start with a single initializer,
04840   // grab the only argument out the Args and place it into the "current"
04841   // initializer.
04842   switch (Steps.front().Kind) {
04843   case SK_ResolveAddressOfOverloadedFunction:
04844   case SK_CastDerivedToBaseRValue:
04845   case SK_CastDerivedToBaseXValue:
04846   case SK_CastDerivedToBaseLValue:
04847   case SK_BindReference:
04848   case SK_BindReferenceToTemporary:
04849   case SK_ExtraneousCopyToTemporary:
04850   case SK_UserConversion:
04851   case SK_QualificationConversionLValue:
04852   case SK_QualificationConversionXValue:
04853   case SK_QualificationConversionRValue:
04854   case SK_ConversionSequence:
04855   case SK_ListConstructorCall:
04856   case SK_ListInitialization:
04857   case SK_UnwrapInitList:
04858   case SK_RewrapInitList:
04859   case SK_CAssignment:
04860   case SK_StringInit:
04861   case SK_ObjCObjectConversion:
04862   case SK_ArrayInit:
04863   case SK_ParenthesizedArrayInit:
04864   case SK_PassByIndirectCopyRestore:
04865   case SK_PassByIndirectRestore:
04866   case SK_ProduceObjCObject:
04867   case SK_StdInitializerList: {
04868     assert(Args.size() == 1);
04869     CurInit = Args.get()[0];
04870     if (!CurInit.get()) return ExprError();
04871     break;
04872   }
04873 
04874   case SK_ConstructorInitialization:
04875   case SK_ZeroInitialization:
04876     break;
04877   }
04878 
04879   // Walk through the computed steps for the initialization sequence,
04880   // performing the specified conversions along the way.
04881   bool ConstructorInitRequiresZeroInit = false;
04882   for (step_iterator Step = step_begin(), StepEnd = step_end();
04883        Step != StepEnd; ++Step) {
04884     if (CurInit.isInvalid())
04885       return ExprError();
04886 
04887     QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
04888 
04889     switch (Step->Kind) {
04890     case SK_ResolveAddressOfOverloadedFunction:
04891       // Overload resolution determined which function invoke; update the
04892       // initializer to reflect that choice.
04893       S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
04894       S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
04895       CurInit = S.FixOverloadedFunctionReference(move(CurInit),
04896                                                  Step->Function.FoundDecl,
04897                                                  Step->Function.Function);
04898       break;
04899 
04900     case SK_CastDerivedToBaseRValue:
04901     case SK_CastDerivedToBaseXValue:
04902     case SK_CastDerivedToBaseLValue: {
04903       // We have a derived-to-base cast that produces either an rvalue or an
04904       // lvalue. Perform that cast.
04905 
04906       CXXCastPath BasePath;
04907 
04908       // Casts to inaccessible base classes are allowed with C-style casts.
04909       bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
04910       if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
04911                                          CurInit.get()->getLocStart(),
04912                                          CurInit.get()->getSourceRange(),
04913                                          &BasePath, IgnoreBaseAccess))
04914         return ExprError();
04915 
04916       if (S.BasePathInvolvesVirtualBase(BasePath)) {
04917         QualType T = SourceType;
04918         if (const PointerType *Pointer = T->getAs<PointerType>())
04919           T = Pointer->getPointeeType();
04920         if (const RecordType *RecordTy = T->getAs<RecordType>())
04921           S.MarkVTableUsed(CurInit.get()->getLocStart(),
04922                            cast<CXXRecordDecl>(RecordTy->getDecl()));
04923       }
04924 
04925       ExprValueKind VK =
04926           Step->Kind == SK_CastDerivedToBaseLValue ?
04927               VK_LValue :
04928               (Step->Kind == SK_CastDerivedToBaseXValue ?
04929                    VK_XValue :
04930                    VK_RValue);
04931       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
04932                                                  Step->Type,
04933                                                  CK_DerivedToBase,
04934                                                  CurInit.get(),
04935                                                  &BasePath, VK));
04936       break;
04937     }
04938 
04939     case SK_BindReference:
04940       if (FieldDecl *BitField = CurInit.get()->getBitField()) {
04941         // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
04942         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
04943           << Entity.getType().isVolatileQualified()
04944           << BitField->getDeclName()
04945           << CurInit.get()->getSourceRange();
04946         S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
04947         return ExprError();
04948       }
04949 
04950       if (CurInit.get()->refersToVectorElement()) {
04951         // References cannot bind to vector elements.
04952         S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
04953           << Entity.getType().isVolatileQualified()
04954           << CurInit.get()->getSourceRange();
04955         PrintInitLocationNote(S, Entity);
04956         return ExprError();
04957       }
04958 
04959       // Reference binding does not have any corresponding ASTs.
04960 
04961       // Check exception specifications
04962       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
04963         return ExprError();
04964 
04965       break;
04966 
04967     case SK_BindReferenceToTemporary:
04968       // Check exception specifications
04969       if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
04970         return ExprError();
04971 
04972       // Materialize the temporary into memory.
04973       CurInit = new (S.Context) MaterializeTemporaryExpr(
04974                                          Entity.getType().getNonReferenceType(),
04975                                                          CurInit.get(),
04976                                      Entity.getType()->isLValueReferenceType());
04977 
04978       // If we're binding to an Objective-C object that has lifetime, we
04979       // need cleanups.
04980       if (S.getLangOpts().ObjCAutoRefCount &&
04981           CurInit.get()->getType()->isObjCLifetimeType())
04982         S.ExprNeedsCleanups = true;
04983             
04984       break;
04985 
04986     case SK_ExtraneousCopyToTemporary:
04987       CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
04988                            /*IsExtraneousCopy=*/true);
04989       break;
04990 
04991     case SK_UserConversion: {
04992       // We have a user-defined conversion that invokes either a constructor
04993       // or a conversion function.
04994       CastKind CastKind;
04995       bool IsCopy = false;
04996       FunctionDecl *Fn = Step->Function.Function;
04997       DeclAccessPair FoundFn = Step->Function.FoundDecl;
04998       bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
04999       bool CreatedObject = false;
05000       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
05001         // Build a call to the selected constructor.
05002         ASTOwningVector<Expr*> ConstructorArgs(S);
05003         SourceLocation Loc = CurInit.get()->getLocStart();
05004         CurInit.release(); // Ownership transferred into MultiExprArg, below.
05005 
05006         // Determine the arguments required to actually perform the constructor
05007         // call.
05008         Expr *Arg = CurInit.get();
05009         if (S.CompleteConstructorCall(Constructor,
05010                                       MultiExprArg(&Arg, 1),
05011                                       Loc, ConstructorArgs))
05012           return ExprError();
05013 
05014         // Build an expression that constructs a temporary.
05015         CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
05016                                           move_arg(ConstructorArgs),
05017                                           HadMultipleCandidates,
05018                                           /*ZeroInit*/ false,
05019                                           CXXConstructExpr::CK_Complete,
05020                                           SourceRange());
05021         if (CurInit.isInvalid())
05022           return ExprError();
05023 
05024         S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
05025                                  FoundFn.getAccess());
05026         S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
05027 
05028         CastKind = CK_ConstructorConversion;
05029         QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
05030         if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
05031             S.IsDerivedFrom(SourceType, Class))
05032           IsCopy = true;
05033 
05034         CreatedObject = true;
05035       } else {
05036         // Build a call to the conversion function.
05037         CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
05038         S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
05039                                     FoundFn);
05040         S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
05041 
05042         // FIXME: Should we move this initialization into a separate
05043         // derived-to-base conversion? I believe the answer is "no", because
05044         // we don't want to turn off access control here for c-style casts.
05045         ExprResult CurInitExprRes =
05046           S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
05047                                                 FoundFn, Conversion);
05048         if(CurInitExprRes.isInvalid())
05049           return ExprError();
05050         CurInit = move(CurInitExprRes);
05051 
05052         // Build the actual call to the conversion function.
05053         CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
05054                                            HadMultipleCandidates);
05055         if (CurInit.isInvalid() || !CurInit.get())
05056           return ExprError();
05057 
05058         CastKind = CK_UserDefinedConversion;
05059 
05060         CreatedObject = Conversion->getResultType()->isRecordType();
05061       }
05062 
05063       bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
05064       bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
05065 
05066       if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
05067         QualType T = CurInit.get()->getType();
05068         if (const RecordType *Record = T->getAs<RecordType>()) {
05069           CXXDestructorDecl *Destructor
05070             = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
05071           S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
05072                                   S.PDiag(diag::err_access_dtor_temp) << T);
05073           S.MarkFunctionReferenced(CurInit.get()->getLocStart(), Destructor);
05074           S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
05075         }
05076       }
05077 
05078       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
05079                                                  CurInit.get()->getType(),
05080                                                  CastKind, CurInit.get(), 0,
05081                                                 CurInit.get()->getValueKind()));
05082       if (MaybeBindToTemp)
05083         CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
05084       if (RequiresCopy)
05085         CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
05086                              move(CurInit), /*IsExtraneousCopy=*/false);
05087       break;
05088     }
05089 
05090     case SK_QualificationConversionLValue:
05091     case SK_QualificationConversionXValue:
05092     case SK_QualificationConversionRValue: {
05093       // Perform a qualification conversion; these can never go wrong.
05094       ExprValueKind VK =
05095           Step->Kind == SK_QualificationConversionLValue ?
05096               VK_LValue :
05097               (Step->Kind == SK_QualificationConversionXValue ?
05098                    VK_XValue :
05099                    VK_RValue);
05100       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
05101       break;
05102     }
05103 
05104     case SK_ConversionSequence: {
05105       Sema::CheckedConversionKind CCK 
05106         = Kind.isCStyleCast()? Sema::CCK_CStyleCast
05107         : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
05108         : Kind.isExplicitCast()? Sema::CCK_OtherCast
05109         : Sema::CCK_ImplicitConversion;
05110       ExprResult CurInitExprRes =
05111         S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
05112                                     getAssignmentAction(Entity), CCK);
05113       if (CurInitExprRes.isInvalid())
05114         return ExprError();
05115       CurInit = move(CurInitExprRes);
05116       break;
05117     }
05118 
05119     case SK_ListInitialization: {
05120       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
05121       // Hack: We must pass *ResultType if available in order to set the type
05122       // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
05123       // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
05124       // temporary, not a reference, so we should pass Ty.
05125       // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
05126       // Since this step is never used for a reference directly, we explicitly
05127       // unwrap references here and rewrap them afterwards.
05128       // We also need to create a InitializeTemporary entity for this.
05129       QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
05130       bool IsTemporary = Entity.getType()->isReferenceType();
05131       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
05132       InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
05133           InitList, Ty, /*VerifyOnly=*/false,
05134           Kind.getKind() != InitializationKind::IK_DirectList ||
05135             !S.getLangOpts().CPlusPlus0x);
05136       if (PerformInitList.HadError())
05137         return ExprError();
05138 
05139       if (ResultType) {
05140         if ((*ResultType)->isRValueReferenceType())
05141           Ty = S.Context.getRValueReferenceType(Ty);
05142         else if ((*ResultType)->isLValueReferenceType())
05143           Ty = S.Context.getLValueReferenceType(Ty,
05144             (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
05145         *ResultType = Ty;
05146       }
05147 
05148       InitListExpr *StructuredInitList =
05149           PerformInitList.getFullyStructuredList();
05150       CurInit.release();
05151       CurInit = S.Owned(StructuredInitList);
05152       break;
05153     }
05154 
05155     case SK_ListConstructorCall: {
05156       // When an initializer list is passed for a parameter of type "reference
05157       // to object", we don't get an EK_Temporary entity, but instead an
05158       // EK_Parameter entity with reference type.
05159       // FIXME: This is a hack. What we really should do is create a user
05160       // conversion step for this case, but this makes it considerably more
05161       // complicated. For now, this will do.
05162       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
05163                                         Entity.getType().getNonReferenceType());
05164       bool UseTemporary = Entity.getType()->isReferenceType();
05165       InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
05166       S.Diag(InitList->getExprLoc(), diag::warn_cxx98_compat_ctor_list_init)
05167         << InitList->getSourceRange();
05168       MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
05169       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity :
05170                                                                    Entity,
05171                                                  Kind, move(Arg), *Step,
05172                                                ConstructorInitRequiresZeroInit);
05173       break;
05174     }
05175 
05176     case SK_UnwrapInitList:
05177       CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
05178       break;
05179 
05180     case SK_RewrapInitList: {
05181       Expr *E = CurInit.take();
05182       InitListExpr *Syntactic = Step->WrappingSyntacticList;
05183       InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
05184           Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
05185       ILE->setSyntacticForm(Syntactic);
05186       ILE->setType(E->getType());
05187       ILE->setValueKind(E->getValueKind());
05188       CurInit = S.Owned(ILE);
05189       break;
05190     }
05191 
05192     case SK_ConstructorInitialization: {
05193       // When an initializer list is passed for a parameter of type "reference
05194       // to object", we don't get an EK_Temporary entity, but instead an
05195       // EK_Parameter entity with reference type.
05196       // FIXME: This is a hack. What we really should do is create a user
05197       // conversion step for this case, but this makes it considerably more
05198       // complicated. For now, this will do.
05199       InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(
05200                                         Entity.getType().getNonReferenceType());
05201       bool UseTemporary = Entity.getType()->isReferenceType();
05202       CurInit = PerformConstructorInitialization(S, UseTemporary ? TempEntity
05203                                                                  : Entity,
05204                                                  Kind, move(Args), *Step,
05205                                                ConstructorInitRequiresZeroInit);
05206       break;
05207     }
05208 
05209     case SK_ZeroInitialization: {
05210       step_iterator NextStep = Step;
05211       ++NextStep;
05212       if (NextStep != StepEnd &&
05213           NextStep->Kind == SK_ConstructorInitialization) {
05214         // The need for zero-initialization is recorded directly into
05215         // the call to the object's constructor within the next step.
05216         ConstructorInitRequiresZeroInit = true;
05217       } else if (Kind.getKind() == InitializationKind::IK_Value &&
05218                  S.getLangOpts().CPlusPlus &&
05219                  !Kind.isImplicitValueInit()) {
05220         TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
05221         if (!TSInfo)
05222           TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
05223                                                     Kind.getRange().getBegin());
05224 
05225         CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
05226                               TSInfo->getType().getNonLValueExprType(S.Context),
05227                                                                  TSInfo,
05228                                                     Kind.getRange().getEnd()));
05229       } else {
05230         CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
05231       }
05232       break;
05233     }
05234 
05235     case SK_CAssignment: {
05236       QualType SourceType = CurInit.get()->getType();
05237       ExprResult Result = move(CurInit);
05238       Sema::AssignConvertType ConvTy =
05239         S.CheckSingleAssignmentConstraints(Step->Type, Result);
05240       if (Result.isInvalid())
05241         return ExprError();
05242       CurInit = move(Result);
05243 
05244       // If this is a call, allow conversion to a transparent union.
05245       ExprResult CurInitExprRes = move(CurInit);
05246       if (ConvTy != Sema::Compatible &&
05247           Entity.getKind() == InitializedEntity::EK_Parameter &&
05248           S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
05249             == Sema::Compatible)
05250         ConvTy = Sema::Compatible;
05251       if (CurInitExprRes.isInvalid())
05252         return ExprError();
05253       CurInit = move(CurInitExprRes);
05254 
05255       bool Complained;
05256       if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
05257                                      Step->Type, SourceType,
05258                                      CurInit.get(),
05259                                      getAssignmentAction(Entity),
05260                                      &Complained)) {
05261         PrintInitLocationNote(S, Entity);
05262         return ExprError();
05263       } else if (Complained)
05264         PrintInitLocationNote(S, Entity);
05265       break;
05266     }
05267 
05268     case SK_StringInit: {
05269       QualType Ty = Step->Type;
05270       CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
05271                       S.Context.getAsArrayType(Ty), S);
05272       break;
05273     }
05274 
05275     case SK_ObjCObjectConversion:
05276       CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
05277                           CK_ObjCObjectLValueCast,
05278                           CurInit.get()->getValueKind());
05279       break;
05280 
05281     case SK_ArrayInit:
05282       // Okay: we checked everything before creating this step. Note that
05283       // this is a GNU extension.
05284       S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
05285         << Step->Type << CurInit.get()->getType()
05286         << CurInit.get()->getSourceRange();
05287 
05288       // If the destination type is an incomplete array type, update the
05289       // type accordingly.
05290       if (ResultType) {
05291         if (const IncompleteArrayType *IncompleteDest
05292                            = S.Context.getAsIncompleteArrayType(Step->Type)) {
05293           if (const ConstantArrayType *ConstantSource
05294                  = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
05295             *ResultType = S.Context.getConstantArrayType(
05296                                              IncompleteDest->getElementType(),
05297                                              ConstantSource->getSize(),
05298                                              ArrayType::Normal, 0);
05299           }
05300         }
05301       }
05302       break;
05303 
05304     case SK_ParenthesizedArrayInit:
05305       // Okay: we checked everything before creating this step. Note that
05306       // this is a GNU extension.
05307       S.Diag(Kind.getLocation(), diag::ext_array_init_parens)
05308         << CurInit.get()->getSourceRange();
05309       break;
05310 
05311     case SK_PassByIndirectCopyRestore:
05312     case SK_PassByIndirectRestore:
05313       checkIndirectCopyRestoreSource(S, CurInit.get());
05314       CurInit = S.Owned(new (S.Context)
05315                         ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
05316                                 Step->Kind == SK_PassByIndirectCopyRestore));
05317       break;
05318 
05319     case SK_ProduceObjCObject:
05320       CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
05321                                                  CK_ARCProduceObject,
05322                                                  CurInit.take(), 0, VK_RValue));
05323       break;
05324 
05325     case SK_StdInitializerList: {
05326       QualType Dest = Step->Type;
05327       QualType E;
05328       bool Success = S.isStdInitializerList(Dest, &E);
05329       (void)Success;
05330       assert(Success && "Destination type changed?");
05331 
05332       // If the element type has a destructor, check it.
05333       if (CXXRecordDecl *RD = E->getAsCXXRecordDecl()) {
05334         if (!RD->hasIrrelevantDestructor()) {
05335           if (CXXDestructorDecl *Destructor = S.LookupDestructor(RD)) {
05336             S.MarkFunctionReferenced(Kind.getLocation(), Destructor);
05337             S.CheckDestructorAccess(Kind.getLocation(), Destructor,
05338                                     S.PDiag(diag::err_access_dtor_temp) << E);
05339             S.DiagnoseUseOfDecl(Destructor, Kind.getLocation());
05340           }
05341         }
05342       }
05343 
05344       InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
05345       S.Diag(ILE->getExprLoc(), diag::warn_cxx98_compat_initializer_list_init)
05346         << ILE->getSourceRange();
05347       unsigned NumInits = ILE->getNumInits();
05348       SmallVector<Expr*, 16> Converted(NumInits);
05349       InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
05350           S.Context.getConstantArrayType(E,
05351               llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
05352                           NumInits),
05353               ArrayType::Normal, 0));
05354       InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
05355           0, HiddenArray);
05356       for (unsigned i = 0; i < NumInits; ++i) {
05357         Element.setElementIndex(i);
05358         ExprResult Init = S.Owned(ILE->getInit(i));
05359         ExprResult Res = S.PerformCopyInitialization(Element,
05360                                                      Init.get()->getExprLoc(),
05361                                                      Init);
05362         assert(!Res.isInvalid() && "Result changed since try phase.");
05363         Converted[i] = Res.take();
05364       }
05365       InitListExpr *Semantic = new (S.Context)
05366           InitListExpr(S.Context, ILE->getLBraceLoc(),
05367                        Converted.data(), NumInits, ILE->getRBraceLoc());
05368       Semantic->setSyntacticForm(ILE);
05369       Semantic->setType(Dest);
05370       Semantic->setInitializesStdInitializerList();
05371       CurInit = S.Owned(Semantic);
05372       break;
05373     }
05374     }
05375   }
05376 
05377   // Diagnose non-fatal problems with the completed initialization.
05378   if (Entity.getKind() == InitializedEntity::EK_Member &&
05379       cast<FieldDecl>(Entity.getDecl())->isBitField())
05380     S.CheckBitFieldInitialization(Kind.getLocation(),
05381                                   cast<FieldDecl>(Entity.getDecl()),
05382                                   CurInit.get());
05383 
05384   return move(CurInit);
05385 }
05386 
05387 //===----------------------------------------------------------------------===//
05388 // Diagnose initialization failures
05389 //===----------------------------------------------------------------------===//
05390 bool InitializationSequence::Diagnose(Sema &S,
05391                                       const InitializedEntity &Entity,
05392                                       const InitializationKind &Kind,
05393                                       Expr **Args, unsigned NumArgs) {
05394   if (!Failed())
05395     return false;
05396 
05397   QualType DestType = Entity.getType();
05398   switch (Failure) {
05399   case FK_TooManyInitsForReference:
05400     // FIXME: Customize for the initialized entity?
05401     if (NumArgs == 0)
05402       S.Diag(Kind.getLocation(), diag::err_reference_without_init)
05403         << DestType.getNonReferenceType();
05404     else  // FIXME: diagnostic below could be better!
05405       S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
05406         << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
05407     break;
05408 
05409   case FK_ArrayNeedsInitList:
05410   case FK_ArrayNeedsInitListOrStringLiteral:
05411     S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
05412       << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
05413     break;
05414 
05415   case FK_ArrayTypeMismatch:
05416   case FK_NonConstantArrayInit:
05417     S.Diag(Kind.getLocation(), 
05418            (Failure == FK_ArrayTypeMismatch
05419               ? diag::err_array_init_different_type
05420               : diag::err_array_init_non_constant_array))
05421       << DestType.getNonReferenceType()
05422       << Args[0]->getType()
05423       << Args[0]->getSourceRange();
05424     break;
05425 
05426   case FK_VariableLengthArrayHasInitializer:
05427     S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
05428       << Args[0]->getSourceRange();
05429     break;
05430 
05431   case FK_AddressOfOverloadFailed: {
05432     DeclAccessPair Found;
05433     S.ResolveAddressOfOverloadedFunction(Args[0],
05434                                          DestType.getNonReferenceType(),
05435                                          true,
05436                                          Found);
05437     break;
05438   }
05439 
05440   case FK_ReferenceInitOverloadFailed:
05441   case FK_UserConversionOverloadFailed:
05442     switch (FailedOverloadResult) {
05443     case OR_Ambiguous:
05444       if (Failure == FK_UserConversionOverloadFailed)
05445         S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
05446           << Args[0]->getType() << DestType
05447           << Args[0]->getSourceRange();
05448       else
05449         S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
05450           << DestType << Args[0]->getType()
05451           << Args[0]->getSourceRange();
05452 
05453       FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
05454                                         llvm::makeArrayRef(Args, NumArgs));
05455       break;
05456 
05457     case OR_No_Viable_Function:
05458       S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
05459         << Args[0]->getType() << DestType.getNonReferenceType()
05460         << Args[0]->getSourceRange();
05461       FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
05462                                         llvm::makeArrayRef(Args, NumArgs));
05463       break;
05464 
05465     case OR_Deleted: {
05466       S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
05467         << Args[0]->getType() << DestType.getNonReferenceType()
05468         << Args[0]->getSourceRange();
05469       OverloadCandidateSet::iterator Best;
05470       OverloadingResult Ovl
05471         = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
05472                                                 true);
05473       if (Ovl == OR_Deleted) {
05474         S.NoteDeletedFunction(Best->Function);
05475       } else {
05476         llvm_unreachable("Inconsistent overload resolution?");
05477       }
05478       break;
05479     }
05480 
05481     case OR_Success:
05482       llvm_unreachable("Conversion did not fail!");
05483     }
05484     break;
05485 
05486   case FK_NonConstLValueReferenceBindingToTemporary:
05487     if (isa<InitListExpr>(Args[0])) {
05488       S.Diag(Kind.getLocation(),
05489              diag::err_lvalue_reference_bind_to_initlist)
05490       << DestType.getNonReferenceType().isVolatileQualified()
05491       << DestType.getNonReferenceType()
05492       << Args[0]->getSourceRange();
05493       break;
05494     }
05495     // Intentional fallthrough
05496 
05497   case FK_NonConstLValueReferenceBindingToUnrelated:
05498     S.Diag(Kind.getLocation(),
05499            Failure == FK_NonConstLValueReferenceBindingToTemporary
05500              ? diag::err_lvalue_reference_bind_to_temporary
05501              : diag::err_lvalue_reference_bind_to_unrelated)
05502       << DestType.getNonReferenceType().isVolatileQualified()
05503       << DestType.getNonReferenceType()
05504       << Args[0]->getType()
05505       << Args[0]->getSourceRange();
05506     break;
05507 
05508   case FK_RValueReferenceBindingToLValue:
05509     S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
05510       << DestType.getNonReferenceType() << Args[0]->getType()
05511       << Args[0]->getSourceRange();
05512     break;
05513 
05514   case FK_ReferenceInitDropsQualifiers:
05515     S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
05516       << DestType.getNonReferenceType()
05517       << Args[0]->getType()
05518       << Args[0]->getSourceRange();
05519     break;
05520 
05521   case FK_ReferenceInitFailed:
05522     S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
05523       << DestType.getNonReferenceType()
05524       << Args[0]->isLValue()
05525       << Args[0]->getType()
05526       << Args[0]->getSourceRange();
05527     if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
05528         Args[0]->getType()->isObjCObjectPointerType())
05529       S.EmitRelatedResultTypeNote(Args[0]);
05530     break;
05531 
05532   case FK_ConversionFailed: {
05533     QualType FromType = Args[0]->getType();
05534     PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
05535       << (int)Entity.getKind()
05536       << DestType
05537       << Args[0]->isLValue()
05538       << FromType
05539       << Args[0]->getSourceRange();
05540     S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
05541     S.Diag(Kind.getLocation(), PDiag);
05542     if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
05543         Args[0]->getType()->isObjCObjectPointerType())
05544       S.EmitRelatedResultTypeNote(Args[0]);
05545     break;
05546   }
05547 
05548   case FK_ConversionFromPropertyFailed:
05549     // No-op. This error has already been reported.
05550     break;
05551 
05552   case FK_TooManyInitsForScalar: {
05553     SourceRange R;
05554 
05555     if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
05556       R = SourceRange(InitList->getInit(0)->getLocEnd(),
05557                       InitList->getLocEnd());
05558     else
05559       R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
05560 
05561     R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
05562     if (Kind.isCStyleOrFunctionalCast())
05563       S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
05564         << R;
05565     else
05566       S.Diag(Kind.getLocation(), diag::err_excess_initializers)
05567         << /*scalar=*/2 << R;
05568     break;
05569   }
05570 
05571   case FK_ReferenceBindingToInitList:
05572     S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
05573       << DestType.getNonReferenceType() << Args[0]->getSourceRange();
05574     break;
05575 
05576   case FK_InitListBadDestinationType:
05577     S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
05578       << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
05579     break;
05580 
05581   case FK_ListConstructorOverloadFailed:
05582   case FK_ConstructorOverloadFailed: {
05583     SourceRange ArgsRange;
05584     if (NumArgs)
05585       ArgsRange = SourceRange(Args[0]->getLocStart(),
05586                               Args[NumArgs - 1]->getLocEnd());
05587 
05588     if (Failure == FK_ListConstructorOverloadFailed) {
05589       assert(NumArgs == 1 && "List construction from other than 1 argument.");
05590       InitListExpr *InitList = cast<InitListExpr>(Args[0]);
05591       Args = InitList->getInits();
05592       NumArgs = InitList->getNumInits();
05593     }
05594 
05595     // FIXME: Using "DestType" for the entity we're printing is probably
05596     // bad.
05597     switch (FailedOverloadResult) {
05598       case OR_Ambiguous:
05599         S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
05600           << DestType << ArgsRange;
05601         FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
05602                                           llvm::makeArrayRef(Args, NumArgs));
05603         break;
05604 
05605       case OR_No_Viable_Function:
05606         if (Kind.getKind() == InitializationKind::IK_Default &&
05607             (Entity.getKind() == InitializedEntity::EK_Base ||
05608              Entity.getKind() == InitializedEntity::EK_Member) &&
05609             isa<CXXConstructorDecl>(S.CurContext)) {
05610           // This is implicit default initialization of a member or
05611           // base within a constructor. If no viable function was
05612           // found, notify the user that she needs to explicitly
05613           // initialize this base/member.
05614           CXXConstructorDecl *Constructor
05615             = cast<CXXConstructorDecl>(S.CurContext);
05616           if (Entity.getKind() == InitializedEntity::EK_Base) {
05617             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
05618               << Constructor->isImplicit()
05619               << S.Context.getTypeDeclType(Constructor->getParent())
05620               << /*base=*/0
05621               << Entity.getType();
05622 
05623             RecordDecl *BaseDecl
05624               = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
05625                                                                   ->getDecl();
05626             S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
05627               << S.Context.getTagDeclType(BaseDecl);
05628           } else {
05629             S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
05630               << Constructor->isImplicit()
05631               << S.Context.getTypeDeclType(Constructor->getParent())
05632               << /*member=*/1
05633               << Entity.getName();
05634             S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
05635 
05636             if (const RecordType *Record
05637                                  = Entity.getType()->getAs<RecordType>())
05638               S.Diag(Record->getDecl()->getLocation(),
05639                      diag::note_previous_decl)
05640                 << S.Context.getTagDeclType(Record->getDecl());
05641           }
05642           break;
05643         }
05644 
05645         S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
05646           << DestType << ArgsRange;
05647         FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates,
05648                                           llvm::makeArrayRef(Args, NumArgs));
05649         break;
05650 
05651       case OR_Deleted: {
05652         OverloadCandidateSet::iterator Best;
05653         OverloadingResult Ovl
05654           = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
05655         if (Ovl != OR_Deleted) {
05656           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
05657             << true << DestType << ArgsRange;
05658           llvm_unreachable("Inconsistent overload resolution?");
05659           break;
05660         }
05661        
05662         // If this is a defaulted or implicitly-declared function, then
05663         // it was implicitly deleted. Make it clear that the deletion was
05664         // implicit.
05665         if (S.isImplicitlyDeleted(Best->Function))
05666           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_special_init)
05667             << S.getSpecialMember(cast<CXXMethodDecl>(Best->Function))
05668             << DestType << ArgsRange;
05669         else
05670           S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
05671             << true << DestType << ArgsRange;
05672 
05673         S.NoteDeletedFunction(Best->Function);
05674         break;
05675       }
05676 
05677       case OR_Success:
05678         llvm_unreachable("Conversion did not fail!");
05679     }
05680   }
05681   break;
05682 
05683   case FK_DefaultInitOfConst:
05684     if (Entity.getKind() == InitializedEntity::EK_Member &&
05685         isa<CXXConstructorDecl>(S.CurContext)) {
05686       // This is implicit default-initialization of a const member in
05687       // a constructor. Complain that it needs to be explicitly
05688       // initialized.
05689       CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
05690       S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
05691         << Constructor->isImplicit()
05692         << S.Context.getTypeDeclType(Constructor->getParent())
05693         << /*const=*/1
05694         << Entity.getName();
05695       S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
05696         << Entity.getName();
05697     } else {
05698       S.Diag(Kind.getLocation(), diag::err_default_init_const)
05699         << DestType << (bool)DestType->getAs<RecordType>();
05700     }
05701     break;
05702 
05703   case FK_Incomplete:
05704     S.RequireCompleteType(Kind.getLocation(), FailedIncompleteType,
05705                           diag::err_init_incomplete_type);
05706     break;
05707 
05708   case FK_ListInitializationFailed: {
05709     // Run the init list checker again to emit diagnostics.
05710     InitListExpr* InitList = cast<InitListExpr>(Args[0]);
05711     QualType DestType = Entity.getType();
05712     InitListChecker DiagnoseInitList(S, Entity, InitList,
05713             DestType, /*VerifyOnly=*/false,
05714             Kind.getKind() != InitializationKind::IK_DirectList ||
05715               !S.getLangOpts().CPlusPlus0x);
05716     assert(DiagnoseInitList.HadError() &&
05717            "Inconsistent init list check result.");
05718     break;
05719   }
05720 
05721   case FK_PlaceholderType: {
05722     // FIXME: Already diagnosed!
05723     break;
05724   }
05725 
05726   case FK_InitListElementCopyFailure: {
05727     // Try to perform all copies again.
05728     InitListExpr* InitList = cast<InitListExpr>(Args[0]);
05729     unsigned NumInits = InitList->getNumInits();
05730     QualType DestType = Entity.getType();
05731     QualType E;
05732     bool Success = S.isStdInitializerList(DestType, &E);
05733     (void)Success;
05734     assert(Success && "Where did the std::initializer_list go?");
05735     InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
05736         S.Context.getConstantArrayType(E,
05737             llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
05738                         NumInits),
05739             ArrayType::Normal, 0));
05740     InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
05741         0, HiddenArray);
05742     // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
05743     // where the init list type is wrong, e.g.
05744     //   std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
05745     // FIXME: Emit a note if we hit the limit?
05746     int ErrorCount = 0;
05747     for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
05748       Element.setElementIndex(i);
05749       ExprResult Init = S.Owned(InitList->getInit(i));
05750       if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
05751            .isInvalid())
05752         ++ErrorCount;
05753     }
05754     break;
05755   }
05756 
05757   case FK_ExplicitConstructor: {
05758     S.Diag(Kind.getLocation(), diag::err_selected_explicit_constructor)
05759       << Args[0]->getSourceRange();
05760     OverloadCandidateSet::iterator Best;
05761     OverloadingResult Ovl
05762       = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
05763     (void)Ovl;
05764     assert(Ovl == OR_Success && "Inconsistent overload resolution");
05765     CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
05766     S.Diag(CtorDecl->getLocation(), diag::note_constructor_declared_here);
05767     break;
05768   }
05769   }
05770 
05771   PrintInitLocationNote(S, Entity);
05772   return true;
05773 }
05774 
05775 void InitializationSequence::dump(raw_ostream &OS) const {
05776   switch (SequenceKind) {
05777   case FailedSequence: {
05778     OS << "Failed sequence: ";
05779     switch (Failure) {
05780     case FK_TooManyInitsForReference:
05781       OS << "too many initializers for reference";
05782       break;
05783 
05784     case FK_ArrayNeedsInitList:
05785       OS << "array requires initializer list";
05786       break;
05787 
05788     case FK_ArrayNeedsInitListOrStringLiteral:
05789       OS << "array requires initializer list or string literal";
05790       break;
05791 
05792     case FK_ArrayTypeMismatch:
05793       OS << "array type mismatch";
05794       break;
05795 
05796     case FK_NonConstantArrayInit:
05797       OS << "non-constant array initializer";
05798       break;
05799 
05800     case FK_AddressOfOverloadFailed:
05801       OS << "address of overloaded function failed";
05802       break;
05803 
05804     case FK_ReferenceInitOverloadFailed:
05805       OS << "overload resolution for reference initialization failed";
05806       break;
05807 
05808     case FK_NonConstLValueReferenceBindingToTemporary:
05809       OS << "non-const lvalue reference bound to temporary";
05810       break;
05811 
05812     case FK_NonConstLValueReferenceBindingToUnrelated:
05813       OS << "non-const lvalue reference bound to unrelated type";
05814       break;
05815 
05816     case FK_RValueReferenceBindingToLValue:
05817       OS << "rvalue reference bound to an lvalue";
05818       break;
05819 
05820     case FK_ReferenceInitDropsQualifiers:
05821       OS << "reference initialization drops qualifiers";
05822       break;
05823 
05824     case FK_ReferenceInitFailed:
05825       OS << "reference initialization failed";
05826       break;
05827 
05828     case FK_ConversionFailed:
05829       OS << "conversion failed";
05830       break;
05831 
05832     case FK_ConversionFromPropertyFailed:
05833       OS << "conversion from property failed";
05834       break;
05835 
05836     case FK_TooManyInitsForScalar:
05837       OS << "too many initializers for scalar";
05838       break;
05839 
05840     case FK_ReferenceBindingToInitList:
05841       OS << "referencing binding to initializer list";
05842       break;
05843 
05844     case FK_InitListBadDestinationType:
05845       OS << "initializer list for non-aggregate, non-scalar type";
05846       break;
05847 
05848     case FK_UserConversionOverloadFailed:
05849       OS << "overloading failed for user-defined conversion";
05850       break;
05851 
05852     case FK_ConstructorOverloadFailed:
05853       OS << "constructor overloading failed";
05854       break;
05855 
05856     case FK_DefaultInitOfConst:
05857       OS << "default initialization of a const variable";
05858       break;
05859 
05860     case FK_Incomplete:
05861       OS << "initialization of incomplete type";
05862       break;
05863 
05864     case FK_ListInitializationFailed:
05865       OS << "list initialization checker failure";
05866       break;
05867 
05868     case FK_VariableLengthArrayHasInitializer:
05869       OS << "variable length array has an initializer";
05870       break;
05871 
05872     case FK_PlaceholderType:
05873       OS << "initializer expression isn't contextually valid";
05874       break;
05875 
05876     case FK_ListConstructorOverloadFailed:
05877       OS << "list constructor overloading failed";
05878       break;
05879 
05880     case FK_InitListElementCopyFailure:
05881       OS << "copy construction of initializer list element failed";
05882       break;
05883 
05884     case FK_ExplicitConstructor:
05885       OS << "list copy initialization chose explicit constructor";
05886       break;
05887     }
05888     OS << '\n';
05889     return;
05890   }
05891 
05892   case DependentSequence:
05893     OS << "Dependent sequence\n";
05894     return;
05895 
05896   case NormalSequence:
05897     OS << "Normal sequence: ";
05898     break;
05899   }
05900 
05901   for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
05902     if (S != step_begin()) {
05903       OS << " -> ";
05904     }
05905 
05906     switch (S->Kind) {
05907     case SK_ResolveAddressOfOverloadedFunction:
05908       OS << "resolve address of overloaded function";
05909       break;
05910 
05911     case SK_CastDerivedToBaseRValue:
05912       OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
05913       break;
05914 
05915     case SK_CastDerivedToBaseXValue:
05916       OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
05917       break;
05918 
05919     case SK_CastDerivedToBaseLValue:
05920       OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
05921       break;
05922 
05923     case SK_BindReference:
05924       OS << "bind reference to lvalue";
05925       break;
05926 
05927     case SK_BindReferenceToTemporary:
05928       OS << "bind reference to a temporary";
05929       break;
05930 
05931     case SK_ExtraneousCopyToTemporary:
05932       OS << "extraneous C++03 copy to temporary";
05933       break;
05934 
05935     case SK_UserConversion:
05936       OS << "user-defined conversion via " << *S->Function.Function;
05937       break;
05938 
05939     case SK_QualificationConversionRValue:
05940       OS << "qualification conversion (rvalue)";
05941       break;
05942 
05943     case SK_QualificationConversionXValue:
05944       OS << "qualification conversion (xvalue)";
05945       break;
05946 
05947     case SK_QualificationConversionLValue:
05948       OS << "qualification conversion (lvalue)";
05949       break;
05950 
05951     case SK_ConversionSequence:
05952       OS << "implicit conversion sequence (";
05953       S->ICS->DebugPrint(); // FIXME: use OS
05954       OS << ")";
05955       break;
05956 
05957     case SK_ListInitialization:
05958       OS << "list aggregate initialization";
05959       break;
05960 
05961     case SK_ListConstructorCall:
05962       OS << "list initialization via constructor";
05963       break;
05964 
05965     case SK_UnwrapInitList:
05966       OS << "unwrap reference initializer list";
05967       break;
05968 
05969     case SK_RewrapInitList:
05970       OS << "rewrap reference initializer list";
05971       break;
05972 
05973     case SK_ConstructorInitialization:
05974       OS << "constructor initialization";
05975       break;
05976 
05977     case SK_ZeroInitialization:
05978       OS << "zero initialization";
05979       break;
05980 
05981     case SK_CAssignment:
05982       OS << "C assignment";
05983       break;
05984 
05985     case SK_StringInit:
05986       OS << "string initialization";
05987       break;
05988 
05989     case SK_ObjCObjectConversion:
05990       OS << "Objective-C object conversion";
05991       break;
05992 
05993     case SK_ArrayInit:
05994       OS << "array initialization";
05995       break;
05996 
05997     case SK_ParenthesizedArrayInit:
05998       OS << "parenthesized array initialization";
05999       break;
06000 
06001     case SK_PassByIndirectCopyRestore:
06002       OS << "pass by indirect copy and restore";
06003       break;
06004 
06005     case SK_PassByIndirectRestore:
06006       OS << "pass by indirect restore";
06007       break;
06008 
06009     case SK_ProduceObjCObject:
06010       OS << "Objective-C object retension";
06011       break;
06012 
06013     case SK_StdInitializerList:
06014       OS << "std::initializer_list from initializer list";
06015       break;
06016     }
06017   }
06018 }
06019 
06020 void InitializationSequence::dump() const {
06021   dump(llvm::errs());
06022 }
06023 
06024 static void DiagnoseNarrowingInInitList(Sema &S, InitializationSequence &Seq,
06025                                         QualType EntityType,
06026                                         const Expr *PreInit,
06027                                         const Expr *PostInit) {
06028   if (Seq.step_begin() == Seq.step_end() || PreInit->isValueDependent())
06029     return;
06030 
06031   // A narrowing conversion can only appear as the final implicit conversion in
06032   // an initialization sequence.
06033   const InitializationSequence::Step &LastStep = Seq.step_end()[-1];
06034   if (LastStep.Kind != InitializationSequence::SK_ConversionSequence)
06035     return;
06036 
06037   const ImplicitConversionSequence &ICS = *LastStep.ICS;
06038   const StandardConversionSequence *SCS = 0;
06039   switch (ICS.getKind()) {
06040   case ImplicitConversionSequence::StandardConversion:
06041     SCS = &ICS.Standard;
06042     break;
06043   case ImplicitConversionSequence::UserDefinedConversion:
06044     SCS = &ICS.UserDefined.After;
06045     break;
06046   case ImplicitConversionSequence::AmbiguousConversion:
06047   case ImplicitConversionSequence::EllipsisConversion:
06048   case ImplicitConversionSequence::BadConversion:
06049     return;
06050   }
06051 
06052   // Determine the type prior to the narrowing conversion. If a conversion
06053   // operator was used, this may be different from both the type of the entity
06054   // and of the pre-initialization expression.
06055   QualType PreNarrowingType = PreInit->getType();
06056   if (Seq.step_begin() + 1 != Seq.step_end())
06057     PreNarrowingType = Seq.step_end()[-2].Type;
06058 
06059   // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion.
06060   APValue ConstantValue;
06061   QualType ConstantType;
06062   switch (SCS->getNarrowingKind(S.Context, PostInit, ConstantValue,
06063                                 ConstantType)) {
06064   case NK_Not_Narrowing:
06065     // No narrowing occurred.
06066     return;
06067 
06068   case NK_Type_Narrowing:
06069     // This was a floating-to-integer conversion, which is always considered a
06070     // narrowing conversion even if the value is a constant and can be
06071     // represented exactly as an integer.
06072     S.Diag(PostInit->getLocStart(),
06073            S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x? 
06074              diag::warn_init_list_type_narrowing
06075            : S.isSFINAEContext()?
06076              diag::err_init_list_type_narrowing_sfinae
06077            : diag::err_init_list_type_narrowing)
06078       << PostInit->getSourceRange()
06079       << PreNarrowingType.getLocalUnqualifiedType()
06080       << EntityType.getLocalUnqualifiedType();
06081     break;
06082 
06083   case NK_Constant_Narrowing:
06084     // A constant value was narrowed.
06085     S.Diag(PostInit->getLocStart(),
06086            S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x? 
06087              diag::warn_init_list_constant_narrowing
06088            : S.isSFINAEContext()?
06089              diag::err_init_list_constant_narrowing_sfinae
06090            : diag::err_init_list_constant_narrowing)
06091       << PostInit->getSourceRange()
06092       << ConstantValue.getAsString(S.getASTContext(), ConstantType)
06093       << EntityType.getLocalUnqualifiedType();
06094     break;
06095 
06096   case NK_Variable_Narrowing:
06097     // A variable's value may have been narrowed.
06098     S.Diag(PostInit->getLocStart(),
06099            S.getLangOpts().MicrosoftExt || !S.getLangOpts().CPlusPlus0x? 
06100              diag::warn_init_list_variable_narrowing
06101            : S.isSFINAEContext()?
06102              diag::err_init_list_variable_narrowing_sfinae
06103            : diag::err_init_list_variable_narrowing)
06104       << PostInit->getSourceRange()
06105       << PreNarrowingType.getLocalUnqualifiedType()
06106       << EntityType.getLocalUnqualifiedType();
06107     break;
06108   }
06109 
06110   SmallString<128> StaticCast;
06111   llvm::raw_svector_ostream OS(StaticCast);
06112   OS << "static_cast<";
06113   if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
06114     // It's important to use the typedef's name if there is one so that the
06115     // fixit doesn't break code using types like int64_t.
06116     //
06117     // FIXME: This will break if the typedef requires qualification.  But
06118     // getQualifiedNameAsString() includes non-machine-parsable components.
06119     OS << *TT->getDecl();
06120   } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
06121     OS << BT->getName(S.getLangOpts());
06122   else {
06123     // Oops, we didn't find the actual type of the variable.  Don't emit a fixit
06124     // with a broken cast.
06125     return;
06126   }
06127   OS << ">(";
06128   S.Diag(PostInit->getLocStart(), diag::note_init_list_narrowing_override)
06129     << PostInit->getSourceRange()
06130     << FixItHint::CreateInsertion(PostInit->getLocStart(), OS.str())
06131     << FixItHint::CreateInsertion(
06132       S.getPreprocessor().getLocForEndOfToken(PostInit->getLocEnd()), ")");
06133 }
06134 
06135 //===----------------------------------------------------------------------===//
06136 // Initialization helper functions
06137 //===----------------------------------------------------------------------===//
06138 bool
06139 Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
06140                                    ExprResult Init) {
06141   if (Init.isInvalid())
06142     return false;
06143 
06144   Expr *InitE = Init.get();
06145   assert(InitE && "No initialization expression");
06146 
06147   InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
06148                                                            SourceLocation());
06149   InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
06150   return !Seq.Failed();
06151 }
06152 
06153 ExprResult
06154 Sema::PerformCopyInitialization(const InitializedEntity &Entity,
06155                                 SourceLocation EqualLoc,
06156                                 ExprResult Init,
06157                                 bool TopLevelOfInitList,
06158                                 bool AllowExplicit) {
06159   if (Init.isInvalid())
06160     return ExprError();
06161 
06162   Expr *InitE = Init.get();
06163   assert(InitE && "No initialization expression?");
06164 
06165   if (EqualLoc.isInvalid())
06166     EqualLoc = InitE->getLocStart();
06167 
06168   InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
06169                                                            EqualLoc,
06170                                                            AllowExplicit);
06171   InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
06172   Init.release();
06173 
06174   ExprResult Result = Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
06175 
06176   if (!Result.isInvalid() && TopLevelOfInitList)
06177     DiagnoseNarrowingInInitList(*this, Seq, Entity.getType(),
06178                                 InitE, Result.get());
06179 
06180   return Result;
06181 }