blob: 2e4b2362b1f60f63ec49fecb9acadafcc3ba090e [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000025#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000026#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000027using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000028
Chris Lattnerdd8e0062009-02-24 22:27:37 +000029//===----------------------------------------------------------------------===//
30// Sema Initialization Checking
31//===----------------------------------------------------------------------===//
32
John McCallce6c9b72011-02-21 07:22:22 +000033static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000035 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
36 return 0;
37
Chris Lattner8879e3b2009-02-26 23:26:43 +000038 // See if this is a string literal or @encode.
39 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000040
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // Handle @encode, which is a narrow string.
42 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
43 return Init;
44
45 // Otherwise we can only handle string literals.
46 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000047 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000048
49 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000050
51 switch (SL->getKind()) {
52 case StringLiteral::Ascii:
53 case StringLiteral::UTF8:
54 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000057 case StringLiteral::UTF16:
58 return ElemTy->isChar16Type() ? Init : 0;
59 case StringLiteral::UTF32:
60 return ElemTy->isChar32Type() ? Init : 0;
61 case StringLiteral::Wide:
62 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
63 // correction from DR343): "An array with element type compatible with a
64 // qualified or unqualified version of wchar_t may be initialized by a wide
65 // string literal, optionally enclosed in braces."
66 if (Context.typesAreCompatible(Context.getWCharType(),
67 ElemTy.getUnqualifiedType()))
68 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000069
Douglas Gregor5cee1192011-07-27 05:40:30 +000070 return 0;
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor5cee1192011-07-27 05:40:30 +000073 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074}
75
John McCallce6c9b72011-02-21 07:22:22 +000076static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
77 const ArrayType *arrayType = Context.getAsArrayType(declType);
78 if (!arrayType) return 0;
79
80 return IsStringInit(init, arrayType, Context);
81}
82
John McCallfef8b342011-02-21 07:57:55 +000083static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
84 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000085 // Get the length of the string as parsed.
86 uint64_t StrLength =
87 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
88
Mike Stump1eb44332009-09-09 15:08:12 +000089
Chris Lattnerdd8e0062009-02-24 22:27:37 +000090 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000091 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 // being initialized to a string literal.
93 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000094 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000095 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000096 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
97 ConstVal,
98 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000099 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000100 }
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Eli Friedman8718a6a2009-05-29 18:22:49 +0000102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000104 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000105 // the size may be smaller or larger than the string we are initializing.
106 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000107 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000108 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
109 // For Pascal strings it's OK to strip off the terminating null character,
110 // so the example below is valid:
111 //
112 // unsigned char a[2] = "\pa";
113 if (SL->isPascal())
114 StrLength--;
115 }
116
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000117 // [dcl.init.string]p2
118 if (StrLength > CAT->getSize().getZExtValue())
119 S.Diag(Str->getSourceRange().getBegin(),
120 diag::err_initializer_string_for_char_array_too_long)
121 << Str->getSourceRange();
122 } else {
123 // C99 6.7.8p14.
124 if (StrLength-1 > CAT->getSize().getZExtValue())
125 S.Diag(Str->getSourceRange().getBegin(),
126 diag::warn_initializer_string_for_char_array_too_long)
127 << Str->getSourceRange();
128 }
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregor9e80f722009-01-29 01:05:33 +0000141/// @brief Semantic checking for initializer lists.
142///
143/// The InitListChecker class contains a set of routines that each
144/// handle the initialization of a certain kind of entity, e.g.,
145/// arrays, vectors, struct/union types, scalars, etc. The
146/// InitListChecker itself performs a recursive walk of the subobject
147/// structure of the type to be initialized, while stepping through
148/// the initializer list one element at a time. The IList and Index
149/// parameters to each of the Check* routines contain the active
150/// (syntactic) initializer list and the index into that initializer
151/// list that represents the current initializer. Each routine is
152/// responsible for moving that Index forward as it consumes elements.
153///
154/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000155/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000156/// initializer list and the index into that initializer list where we
157/// are copying initializers as we map them over to the semantic
158/// list. Once we have completed our recursive walk of the subobject
159/// structure, we will have constructed a full semantic initializer
160/// list.
161///
162/// C99 designators cause changes in the initializer list traversal,
163/// because they make the initialization "jump" into a specific
164/// subobject and then continue the initialization from that
165/// point. CheckDesignatedInitializer() recursively steps into the
166/// designated subobject and manages backing out the recursion to
167/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000168namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000172 bool VerifyOnly; // no diagnostics, no structure building
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000177 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000178 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000179 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000181 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000182 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000185 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000186 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000187 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000188 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000189 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000190 unsigned &StructuredIndex,
191 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000192 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000193 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000194 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000197 void CheckComplexType(const InitializedEntity &Entity,
198 InitListExpr *IList, QualType DeclType,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000202 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000203 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000204 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000205 InitListExpr *StructuredList,
206 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000207 void CheckReferenceType(const InitializedEntity &Entity,
208 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000209 unsigned &Index,
210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000212 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000213 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000216 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000217 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000218 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000220 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000221 unsigned &StructuredIndex,
222 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000223 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000224 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000225 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000226 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000227 InitListExpr *StructuredList,
228 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000229 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000230 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000231 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000233 RecordDecl::field_iterator *NextField,
234 llvm::APSInt *NextElementIndex,
235 unsigned &Index,
236 InitListExpr *StructuredList,
237 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000238 bool FinishSubobjectInit,
239 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
241 QualType CurrentObjectType,
242 InitListExpr *StructuredList,
243 unsigned StructuredIndex,
244 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000245 void UpdateStructuredListElement(InitListExpr *StructuredList,
246 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000247 Expr *expr);
248 int numArrayElements(QualType DeclType);
249 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000250
Douglas Gregord6d37de2009-12-22 00:05:34 +0000251 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
252 const InitializedEntity &ParentEntity,
253 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000254 void FillInValueInitializations(const InitializedEntity &Entity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000256 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
257 Expr *InitExpr, FieldDecl *Field,
258 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000259public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000260 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000261 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000262 bool HadError() { return hadError; }
263
264 // @brief Retrieves the fully-structured initializer list used for
265 // semantic analysis and code generation.
266 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
267};
Chris Lattner8b419b92009-02-24 22:48:58 +0000268} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000269
Douglas Gregord6d37de2009-12-22 00:05:34 +0000270void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
271 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000273 bool &RequiresSecondPass) {
274 SourceLocation Loc = ILE->getSourceRange().getBegin();
275 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000277 = InitializedEntity::InitializeMember(Field, &ParentEntity);
278 if (Init >= NumInits || !ILE->getInit(Init)) {
279 // FIXME: We probably don't need to handle references
280 // specially here, since value-initialization of references is
281 // handled in InitializationSequence.
282 if (Field->getType()->isReferenceType()) {
283 // C++ [dcl.init.aggr]p9:
284 // If an incomplete or empty initializer-list leaves a
285 // member of reference type uninitialized, the program is
286 // ill-formed.
287 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
288 << Field->getType()
289 << ILE->getSyntacticForm()->getSourceRange();
290 SemaRef.Diag(Field->getLocation(),
291 diag::note_uninit_reference_member);
292 hadError = true;
293 return;
294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000295
Douglas Gregord6d37de2009-12-22 00:05:34 +0000296 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
297 true);
298 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
299 if (!InitSeq) {
300 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
301 hadError = true;
302 return;
303 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000304
John McCall60d7b3a2010-08-24 06:29:42 +0000305 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000306 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000307 if (MemberInit.isInvalid()) {
308 hadError = true;
309 return;
310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000311
Douglas Gregord6d37de2009-12-22 00:05:34 +0000312 if (hadError) {
313 // Do nothing
314 } else if (Init < NumInits) {
315 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000316 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000317 // Value-initialization requires a constructor call, so
318 // extend the initializer list to include the constructor
319 // call and make a note that we'll need to take another pass
320 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000321 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322 RequiresSecondPass = true;
323 }
324 } else if (InitListExpr *InnerILE
325 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000326 FillInValueInitializations(MemberEntity, InnerILE,
327 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000328}
329
Douglas Gregor4c678342009-01-28 21:54:33 +0000330/// Recursively replaces NULL values within the given initializer list
331/// with expressions that perform value-initialization of the
332/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000334InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
335 InitListExpr *ILE,
336 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000337 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000338 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000339 SourceLocation Loc = ILE->getSourceRange().getBegin();
340 if (ILE->getSyntacticForm())
341 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Ted Kremenek6217b802009-07-29 21:53:49 +0000343 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000344 if (RType->getDecl()->isUnion() &&
345 ILE->getInitializedFieldInUnion())
346 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
347 Entity, ILE, RequiresSecondPass);
348 else {
349 unsigned Init = 0;
350 for (RecordDecl::field_iterator
351 Field = RType->getDecl()->field_begin(),
352 FieldEnd = RType->getDecl()->field_end();
353 Field != FieldEnd; ++Field) {
354 if (Field->isUnnamedBitfield())
355 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000356
Douglas Gregord6d37de2009-12-22 00:05:34 +0000357 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000359
360 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
361 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000362 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000363
Douglas Gregord6d37de2009-12-22 00:05:34 +0000364 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000365
Douglas Gregord6d37de2009-12-22 00:05:34 +0000366 // Only look at the first initialization of a union.
367 if (RType->getDecl()->isUnion())
368 break;
369 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000370 }
371
372 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000373 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000374
375 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000377 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 unsigned NumInits = ILE->getNumInits();
379 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000380 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
383 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000385 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000386 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000388 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000389 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000390 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000392 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000393
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000394
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000396 if (hadError)
397 return;
398
Anders Carlssond3d824d2010-01-23 04:34:47 +0000399 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
400 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401 ElementEntity.setElementIndex(Init);
402
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
405 true);
406 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
407 if (!InitSeq) {
408 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000409 hadError = true;
410 return;
411 }
412
John McCall60d7b3a2010-08-24 06:29:42 +0000413 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000414 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000415 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000416 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000417 return;
418 }
419
420 if (hadError) {
421 // Do nothing
422 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000423 // For arrays, just set the expression used for value-initialization
424 // of the "holes" in the array.
425 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
426 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
427 else
428 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000429 } else {
430 // For arrays, just set the expression used for value-initialization
431 // of the rest of elements and exit.
432 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
433 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
434 return;
435 }
436
Sebastian Redl7491c492011-06-05 13:59:11 +0000437 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000438 // Value-initialization requires a constructor call, so
439 // extend the initializer list to include the constructor
440 // call and make a note that we'll need to take another pass
441 // through the initializer list.
442 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
443 RequiresSecondPass = true;
444 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000445 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000446 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000447 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
448 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000449 }
450}
451
Chris Lattner68355a52009-01-29 05:10:57 +0000452
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000453InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000454 InitListExpr *IL, QualType &T,
455 bool VerifyOnly)
456 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000457 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000458
Eli Friedmanb85f7072008-05-19 19:16:24 +0000459 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000460 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000461 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000462 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000463 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000464 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000465 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000466
Sebastian Redl14b0c192011-09-24 17:48:00 +0000467 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000468 bool RequiresSecondPass = false;
469 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000470 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000471 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000472 RequiresSecondPass);
473 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000474}
475
476int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000477 // FIXME: use a proper constant
478 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000479 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000480 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000481 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
482 }
483 return maxElements;
484}
485
486int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000487 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000488 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000489 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000490 Field = structDecl->field_begin(),
491 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000492 Field != FieldEnd; ++Field) {
493 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
494 ++InitializableMembers;
495 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000496 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000497 return std::min(InitializableMembers, 1);
498 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000499}
500
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000501void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000502 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 QualType T, unsigned &Index,
504 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000505 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000506 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Steve Naroff0cca7492008-05-01 22:18:59 +0000508 if (T->isArrayType())
509 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000510 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000511 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000512 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000513 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000514 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000515 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000516
Eli Friedman402256f2008-05-25 13:49:22 +0000517 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000518 if (!VerifyOnly)
519 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
520 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000522 hadError = true;
523 return;
524 }
525
Douglas Gregor4c678342009-01-28 21:54:33 +0000526 // Build a structured initializer list corresponding to this subobject.
527 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000528 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
529 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000530 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
531 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000532 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000533
Douglas Gregor4c678342009-01-28 21:54:33 +0000534 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000535 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000537 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000538 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000539 StructuredSubobjectInitIndex);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000540 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000541 if (!VerifyOnly) {
542 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000543
Sebastian Redl14b0c192011-09-24 17:48:00 +0000544 // Update the structured sub-object initializer so that it's ending
545 // range corresponds with the end of the last initializer it used.
546 if (EndIndex < ParentIList->getNumInits()) {
547 SourceLocation EndLoc
548 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
549 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000551
Sebastian Redl14b0c192011-09-24 17:48:00 +0000552 // Warn about missing braces.
553 if (T->isArrayType() || T->isRecordType()) {
554 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
555 diag::warn_missing_braces)
556 << StructuredSubobjectInitList->getSourceRange()
557 << FixItHint::CreateInsertion(
558 StructuredSubobjectInitList->getLocStart(), "{")
559 << FixItHint::CreateInsertion(
560 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000561 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000562 "}");
563 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000564 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000565}
566
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000567void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000568 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 unsigned &Index,
570 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000571 unsigned &StructuredIndex,
572 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000573 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000574 if (!VerifyOnly) {
575 SyntacticToSemantic[IList] = StructuredList;
576 StructuredList->setSyntacticForm(IList);
577 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000579 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000580 if (!VerifyOnly) {
581 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
582 IList->setType(ExprTy);
583 StructuredList->setType(ExprTy);
584 }
Eli Friedman638e1442008-05-25 13:22:35 +0000585 if (hadError)
586 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587
Eli Friedman638e1442008-05-25 13:22:35 +0000588 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000589 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000590 if (VerifyOnly) {
591 if (SemaRef.getLangOptions().CPlusPlus ||
592 (SemaRef.getLangOptions().OpenCL &&
593 IList->getType()->isVectorType())) {
594 hadError = true;
595 }
596 return;
597 }
598
Eli Friedmane5408582009-05-29 20:20:05 +0000599 if (StructuredIndex == 1 &&
600 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000601 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000602 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000603 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000604 hadError = true;
605 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000606 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000608 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000609 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000610 // Don't complain for incomplete types, since we'll get an error
611 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000612 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000613 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000614 CurrentObjectType->isArrayType()? 0 :
615 CurrentObjectType->isVectorType()? 1 :
616 CurrentObjectType->isScalarType()? 2 :
617 CurrentObjectType->isUnionType()? 3 :
618 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000619
620 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000621 if (SemaRef.getLangOptions().CPlusPlus) {
622 DK = diag::err_excess_initializers;
623 hadError = true;
624 }
Nate Begeman08634522009-07-07 21:53:06 +0000625 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
626 DK = diag::err_excess_initializers;
627 hadError = true;
628 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000629
Chris Lattner08202542009-02-24 22:50:46 +0000630 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000631 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000632 }
633 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000634
Sebastian Redl14b0c192011-09-24 17:48:00 +0000635 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
636 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000637 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000638 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000639 << FixItHint::CreateRemoval(IList->getLocStart())
640 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000641}
642
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000643void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000644 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000645 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000646 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 unsigned &Index,
648 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000649 unsigned &StructuredIndex,
650 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000651 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
652 // Explicitly braced initializer for complex type can be real+imaginary
653 // parts.
654 CheckComplexType(Entity, IList, DeclType, Index,
655 StructuredList, StructuredIndex);
656 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000657 CheckScalarType(Entity, IList, DeclType, Index,
658 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000659 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000660 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000661 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000662 } else if (DeclType->isAggregateType()) {
663 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000664 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000665 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000666 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000667 StructuredList, StructuredIndex,
668 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000669 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000670 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000671 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000672 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000673 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000674 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000675 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000676 } else
David Blaikieb219cfc2011-09-23 05:06:16 +0000677 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000678 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
679 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000680 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000681 if (!VerifyOnly)
682 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
683 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000684 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 } else if (DeclType->isRecordType()) {
686 // C++ [dcl.init]p14:
687 // [...] If the class is an aggregate (8.5.1), and the initializer
688 // is a brace-enclosed list, see 8.5.1.
689 //
690 // Note: 8.5.1 is handled below; here, we diagnose the case where
691 // we have an initializer list and a destination type that is not
692 // an aggregate.
693 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000694 if (!VerifyOnly)
695 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
696 << DeclType << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000697 hadError = true;
698 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000699 CheckReferenceType(Entity, IList, DeclType, Index,
700 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000701 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000702 if (!VerifyOnly)
703 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
704 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000705 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000706 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000710 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000711 }
712}
713
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000714void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000715 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000716 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000717 unsigned &Index,
718 InitListExpr *StructuredList,
719 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000720 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000721 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
722 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000723 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000724 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000725 = getStructuredSubobjectInit(IList, Index, ElemType,
726 StructuredList, StructuredIndex,
727 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000728 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000729 newStructuredList, newStructuredIndex);
730 ++StructuredIndex;
731 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000732 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000733 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000734 return CheckScalarType(Entity, IList, ElemType, Index,
735 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000736 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000737 return CheckReferenceType(Entity, IList, ElemType, Index,
738 StructuredList, StructuredIndex);
739 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000740
John McCallfef8b342011-02-21 07:57:55 +0000741 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
742 // arrayType can be incomplete if we're initializing a flexible
743 // array member. There's nothing we can do with the completed
744 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000745
John McCallfef8b342011-02-21 07:57:55 +0000746 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
747 CheckStringInit(Str, ElemType, arrayType, SemaRef);
748 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000749 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000750 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000751 }
John McCallfef8b342011-02-21 07:57:55 +0000752
753 // Fall through for subaggregate initialization.
754
755 } else if (SemaRef.getLangOptions().CPlusPlus) {
756 // C++ [dcl.init.aggr]p12:
757 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000758 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000759 // an initializer-list. If the initializer can initialize a
760 // member, the member is initialized. [...]
761
762 // FIXME: Better EqualLoc?
763 InitializationKind Kind =
764 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
765 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
766
767 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000768 if (!VerifyOnly) {
769 ExprResult Result =
770 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
771 if (Result.isInvalid())
772 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000773
Sebastian Redl14b0c192011-09-24 17:48:00 +0000774 UpdateStructuredListElement(StructuredList, StructuredIndex,
775 Result.takeAs<Expr>());
776 }
John McCallfef8b342011-02-21 07:57:55 +0000777 ++Index;
778 return;
779 }
780
781 // Fall through for subaggregate initialization
782 } else {
783 // C99 6.7.8p13:
784 //
785 // The initializer for a structure or union object that has
786 // automatic storage duration shall be either an initializer
787 // list as described below, or a single expression that has
788 // compatible structure or union type. In the latter case, the
789 // initial value of the object, including unnamed members, is
790 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000791 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000792 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000793 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
794 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000795 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000796 if (ExprRes.isInvalid())
797 hadError = true;
798 else {
799 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
800 if (ExprRes.isInvalid())
801 hadError = true;
802 }
803 UpdateStructuredListElement(StructuredList, StructuredIndex,
804 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000805 ++Index;
806 return;
807 }
John Wiegley429bb272011-04-08 18:41:53 +0000808 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000809 // Fall through for subaggregate initialization
810 }
811
812 // C++ [dcl.init.aggr]p12:
813 //
814 // [...] Otherwise, if the member is itself a non-empty
815 // subaggregate, brace elision is assumed and the initializer is
816 // considered for the initialization of the first member of
817 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000818 if (!SemaRef.getLangOptions().OpenCL &&
819 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000820 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
821 StructuredIndex);
822 ++StructuredIndex;
823 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000824 if (!VerifyOnly) {
825 // We cannot initialize this element, so let
826 // PerformCopyInitialization produce the appropriate diagnostic.
827 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
828 SemaRef.Owned(expr),
829 /*TopLevelOfInitList=*/true);
830 }
John McCallfef8b342011-02-21 07:57:55 +0000831 hadError = true;
832 ++Index;
833 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000834 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000835}
836
Eli Friedman0c706c22011-09-19 23:17:44 +0000837void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
838 InitListExpr *IList, QualType DeclType,
839 unsigned &Index,
840 InitListExpr *StructuredList,
841 unsigned &StructuredIndex) {
842 assert(Index == 0 && "Index in explicit init list must be zero");
843
844 // As an extension, clang supports complex initializers, which initialize
845 // a complex number component-wise. When an explicit initializer list for
846 // a complex number contains two two initializers, this extension kicks in:
847 // it exepcts the initializer list to contain two elements convertible to
848 // the element type of the complex type. The first element initializes
849 // the real part, and the second element intitializes the imaginary part.
850
851 if (IList->getNumInits() != 2)
852 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
853 StructuredIndex);
854
855 // This is an extension in C. (The builtin _Complex type does not exist
856 // in the C++ standard.)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000857 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000858 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
859 << IList->getSourceRange();
860
861 // Initialize the complex number.
862 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
863 InitializedEntity ElementEntity =
864 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
865
866 for (unsigned i = 0; i < 2; ++i) {
867 ElementEntity.setElementIndex(Index);
868 CheckSubElementType(ElementEntity, IList, elementType, Index,
869 StructuredList, StructuredIndex);
870 }
871}
872
873
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000874void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000875 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000876 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000877 InitListExpr *StructuredList,
878 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000879 if (Index >= IList->getNumInits()) {
Sebastian Redlcea8d962011-09-24 17:48:14 +0000880 if (!SemaRef.getLangOptions().CPlusPlus0x) {
881 if (!VerifyOnly)
882 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
883 << IList->getSourceRange();
884 hadError = true;
885 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000886 ++Index;
887 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000888 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000889 }
John McCallb934c2d2010-11-11 00:46:36 +0000890
891 Expr *expr = IList->getInit(Index);
892 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000893 if (!VerifyOnly)
894 SemaRef.Diag(SubIList->getLocStart(),
895 diag::warn_many_braces_around_scalar_init)
896 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000897
898 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
899 StructuredIndex);
900 return;
901 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000902 if (!VerifyOnly)
903 SemaRef.Diag(expr->getSourceRange().getBegin(),
904 diag::err_designator_for_scalar_init)
905 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000906 hadError = true;
907 ++Index;
908 ++StructuredIndex;
909 return;
910 }
911
Sebastian Redl14b0c192011-09-24 17:48:00 +0000912 if (VerifyOnly) {
913 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
914 hadError = true;
915 ++Index;
916 return;
917 }
918
John McCallb934c2d2010-11-11 00:46:36 +0000919 ExprResult Result =
920 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000921 SemaRef.Owned(expr),
922 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000923
924 Expr *ResultExpr = 0;
925
926 if (Result.isInvalid())
927 hadError = true; // types weren't compatible.
928 else {
929 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000930
John McCallb934c2d2010-11-11 00:46:36 +0000931 if (ResultExpr != expr) {
932 // The type was promoted, update initializer list.
933 IList->setInit(Index, ResultExpr);
934 }
935 }
936 if (hadError)
937 ++StructuredIndex;
938 else
939 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
940 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000941}
942
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000943void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
944 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000945 unsigned &Index,
946 InitListExpr *StructuredList,
947 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000948 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000949 // FIXME: It would be wonderful if we could point at the actual member. In
950 // general, it would be useful to pass location information down the stack,
951 // so that we know the location (or decl) of the "current object" being
952 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000953 if (!VerifyOnly)
954 SemaRef.Diag(IList->getLocStart(),
955 diag::err_init_reference_member_uninitialized)
956 << DeclType
957 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000958 hadError = true;
959 ++Index;
960 ++StructuredIndex;
961 return;
962 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000963
964 Expr *expr = IList->getInit(Index);
965 if (isa<InitListExpr>(expr)) {
966 // FIXME: Allowed in C++11.
967 if (!VerifyOnly)
968 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
969 << DeclType << IList->getSourceRange();
970 hadError = true;
971 ++Index;
972 ++StructuredIndex;
973 return;
974 }
975
976 if (VerifyOnly) {
977 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
978 hadError = true;
979 ++Index;
980 return;
981 }
982
983 ExprResult Result =
984 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
985 SemaRef.Owned(expr),
986 /*TopLevelOfInitList=*/true);
987
988 if (Result.isInvalid())
989 hadError = true;
990
991 expr = Result.takeAs<Expr>();
992 IList->setInit(Index, expr);
993
994 if (hadError)
995 ++StructuredIndex;
996 else
997 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
998 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000999}
1000
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001001void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001002 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001003 unsigned &Index,
1004 InitListExpr *StructuredList,
1005 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001006 if (Index >= IList->getNumInits())
1007 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001008
John McCall20e047a2010-10-30 00:11:39 +00001009 const VectorType *VT = DeclType->getAs<VectorType>();
1010 unsigned maxElements = VT->getNumElements();
1011 unsigned numEltsInit = 0;
1012 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001013
John McCall20e047a2010-10-30 00:11:39 +00001014 if (!SemaRef.getLangOptions().OpenCL) {
1015 // If the initializing element is a vector, try to copy-initialize
1016 // instead of breaking it apart (which is doomed to failure anyway).
1017 Expr *Init = IList->getInit(Index);
1018 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001019 if (VerifyOnly) {
1020 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1021 hadError = true;
1022 ++Index;
1023 return;
1024 }
1025
John McCall20e047a2010-10-30 00:11:39 +00001026 ExprResult Result =
1027 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001028 SemaRef.Owned(Init),
1029 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001030
1031 Expr *ResultExpr = 0;
1032 if (Result.isInvalid())
1033 hadError = true; // types weren't compatible.
1034 else {
1035 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001036
John McCall20e047a2010-10-30 00:11:39 +00001037 if (ResultExpr != Init) {
1038 // The type was promoted, update initializer list.
1039 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001040 }
1041 }
John McCall20e047a2010-10-30 00:11:39 +00001042 if (hadError)
1043 ++StructuredIndex;
1044 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001045 UpdateStructuredListElement(StructuredList, StructuredIndex,
1046 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001047 ++Index;
1048 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
John McCall20e047a2010-10-30 00:11:39 +00001051 InitializedEntity ElementEntity =
1052 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001053
John McCall20e047a2010-10-30 00:11:39 +00001054 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1055 // Don't attempt to go past the end of the init list
1056 if (Index >= IList->getNumInits())
1057 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001058
John McCall20e047a2010-10-30 00:11:39 +00001059 ElementEntity.setElementIndex(Index);
1060 CheckSubElementType(ElementEntity, IList, elementType, Index,
1061 StructuredList, StructuredIndex);
1062 }
1063 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001064 }
John McCall20e047a2010-10-30 00:11:39 +00001065
1066 InitializedEntity ElementEntity =
1067 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
John McCall20e047a2010-10-30 00:11:39 +00001069 // OpenCL initializers allows vectors to be constructed from vectors.
1070 for (unsigned i = 0; i < maxElements; ++i) {
1071 // Don't attempt to go past the end of the init list
1072 if (Index >= IList->getNumInits())
1073 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001074
John McCall20e047a2010-10-30 00:11:39 +00001075 ElementEntity.setElementIndex(Index);
1076
1077 QualType IType = IList->getInit(Index)->getType();
1078 if (!IType->isVectorType()) {
1079 CheckSubElementType(ElementEntity, IList, elementType, Index,
1080 StructuredList, StructuredIndex);
1081 ++numEltsInit;
1082 } else {
1083 QualType VecType;
1084 const VectorType *IVT = IType->getAs<VectorType>();
1085 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001086
John McCall20e047a2010-10-30 00:11:39 +00001087 if (IType->isExtVectorType())
1088 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1089 else
1090 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001091 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001092 CheckSubElementType(ElementEntity, IList, VecType, Index,
1093 StructuredList, StructuredIndex);
1094 numEltsInit += numIElts;
1095 }
1096 }
1097
1098 // OpenCL requires all elements to be initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001099 // FIXME: Shouldn't this set hadError to true then?
1100 if (numEltsInit != maxElements && !VerifyOnly)
1101 SemaRef.Diag(IList->getSourceRange().getBegin(),
1102 diag::err_vector_incorrect_num_initializers)
1103 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001104}
1105
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001106void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001107 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001108 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001109 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001110 unsigned &Index,
1111 InitListExpr *StructuredList,
1112 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001113 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1114
Steve Naroff0cca7492008-05-01 22:18:59 +00001115 // Check for the special-case of initializing an array with a string.
1116 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001117 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001118 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +00001119 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001120 // We place the string literal directly into the resulting
1121 // initializer list. This is the only place where the structure
1122 // of the structured initializer list doesn't match exactly,
1123 // because doing so would involve allocating one character
1124 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001125 if (!VerifyOnly) {
1126 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1127 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1128 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001129 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001130 return;
1131 }
1132 }
John McCallce6c9b72011-02-21 07:22:22 +00001133 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001134 // Check for VLAs; in standard C it would be possible to check this
1135 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1136 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001137 if (!VerifyOnly)
1138 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1139 diag::err_variable_object_no_init)
1140 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001141 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001142 ++Index;
1143 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001144 return;
1145 }
1146
Douglas Gregor05c13a32009-01-22 00:58:24 +00001147 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001148 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1149 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001150 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001151 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001152 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001153 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001154 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001155 maxElementsKnown = true;
1156 }
1157
John McCallce6c9b72011-02-21 07:22:22 +00001158 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001159 while (Index < IList->getNumInits()) {
1160 Expr *Init = IList->getInit(Index);
1161 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001162 // If we're not the subobject that matches up with the '{' for
1163 // the designator, we shouldn't be handling the
1164 // designator. Return immediately.
1165 if (!SubobjectIsDesignatorContext)
1166 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001167
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001168 // Handle this designated initializer. elementIndex will be
1169 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001170 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001171 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001172 StructuredList, StructuredIndex, true,
1173 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001174 hadError = true;
1175 continue;
1176 }
1177
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001178 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001179 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001180 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001181 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001182 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001183
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001184 // If the array is of incomplete type, keep track of the number of
1185 // elements in the initializer.
1186 if (!maxElementsKnown && elementIndex > maxElements)
1187 maxElements = elementIndex;
1188
Douglas Gregor05c13a32009-01-22 00:58:24 +00001189 continue;
1190 }
1191
1192 // If we know the maximum number of elements, and we've already
1193 // hit it, stop consuming elements in the initializer list.
1194 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001195 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001196
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001197 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001198 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001199 Entity);
1200 // Check this element.
1201 CheckSubElementType(ElementEntity, IList, elementType, Index,
1202 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001203 ++elementIndex;
1204
1205 // If the array is of incomplete type, keep track of the number of
1206 // elements in the initializer.
1207 if (!maxElementsKnown && elementIndex > maxElements)
1208 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001209 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001210 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001211 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001212 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001213 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001214 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001215 // Sizing an array implicitly to zero is not allowed by ISO C,
1216 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001217 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001218 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001219 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001220
Mike Stump1eb44332009-09-09 15:08:12 +00001221 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001222 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001223 }
1224}
1225
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001226bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1227 Expr *InitExpr,
1228 FieldDecl *Field,
1229 bool TopLevelObject) {
1230 // Handle GNU flexible array initializers.
1231 unsigned FlexArrayDiag;
1232 if (isa<InitListExpr>(InitExpr) &&
1233 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1234 // Empty flexible array init always allowed as an extension
1235 FlexArrayDiag = diag::ext_flexible_array_init;
1236 } else if (SemaRef.getLangOptions().CPlusPlus) {
1237 // Disallow flexible array init in C++; it is not required for gcc
1238 // compatibility, and it needs work to IRGen correctly in general.
1239 FlexArrayDiag = diag::err_flexible_array_init;
1240 } else if (!TopLevelObject) {
1241 // Disallow flexible array init on non-top-level object
1242 FlexArrayDiag = diag::err_flexible_array_init;
1243 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1244 // Disallow flexible array init on anything which is not a variable.
1245 FlexArrayDiag = diag::err_flexible_array_init;
1246 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1247 // Disallow flexible array init on local variables.
1248 FlexArrayDiag = diag::err_flexible_array_init;
1249 } else {
1250 // Allow other cases.
1251 FlexArrayDiag = diag::ext_flexible_array_init;
1252 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001253
1254 if (!VerifyOnly) {
1255 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1256 FlexArrayDiag)
1257 << InitExpr->getSourceRange().getBegin();
1258 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1259 << Field;
1260 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001261
1262 return FlexArrayDiag != diag::ext_flexible_array_init;
1263}
1264
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001265void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001266 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001267 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001268 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001269 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001270 unsigned &Index,
1271 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001272 unsigned &StructuredIndex,
1273 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001274 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Eli Friedmanb85f7072008-05-19 19:16:24 +00001276 // If the record is invalid, some of it's members are invalid. To avoid
1277 // confusion, we forgo checking the intializer for the entire record.
1278 if (structDecl->isInvalidDecl()) {
1279 hadError = true;
1280 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001281 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001282
1283 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001284 if (!VerifyOnly) {
1285 // Value-initialize the first named member of the union.
1286 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1287 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1288 Field != FieldEnd; ++Field) {
1289 if (Field->getDeclName()) {
1290 StructuredList->setInitializedFieldInUnion(*Field);
1291 break;
1292 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001293 }
1294 }
1295 return;
1296 }
1297
Douglas Gregor05c13a32009-01-22 00:58:24 +00001298 // If structDecl is a forward declaration, this loop won't do
1299 // anything except look at designated initializers; That's okay,
1300 // because an error should get printed out elsewhere. It might be
1301 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001302 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001303 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001304 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001305 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001306 while (Index < IList->getNumInits()) {
1307 Expr *Init = IList->getInit(Index);
1308
1309 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001310 // If we're not the subobject that matches up with the '{' for
1311 // the designator, we shouldn't be handling the
1312 // designator. Return immediately.
1313 if (!SubobjectIsDesignatorContext)
1314 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001315
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001316 // Handle this designated initializer. Field will be updated to
1317 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001318 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001319 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001320 StructuredList, StructuredIndex,
1321 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001322 hadError = true;
1323
Douglas Gregordfb5e592009-02-12 19:00:39 +00001324 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001325
1326 // Disable check for missing fields when designators are used.
1327 // This matches gcc behaviour.
1328 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001329 continue;
1330 }
1331
1332 if (Field == FieldEnd) {
1333 // We've run out of fields. We're done.
1334 break;
1335 }
1336
Douglas Gregordfb5e592009-02-12 19:00:39 +00001337 // We've already initialized a member of a union. We're done.
1338 if (InitializedSomething && DeclType->isUnionType())
1339 break;
1340
Douglas Gregor44b43212008-12-11 16:49:14 +00001341 // If we've hit the flexible array member at the end, we're done.
1342 if (Field->getType()->isIncompleteArrayType())
1343 break;
1344
Douglas Gregor0bb76892009-01-29 16:53:55 +00001345 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001346 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001347 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001348 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001349 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001350
Douglas Gregor54001c12011-06-29 21:51:31 +00001351 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001352 bool InvalidUse;
1353 if (VerifyOnly)
1354 InvalidUse = !SemaRef.CanUseDecl(*Field);
1355 else
1356 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1357 IList->getInit(Index)->getLocStart());
1358 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001359 ++Index;
1360 ++Field;
1361 hadError = true;
1362 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001363 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001364
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001365 InitializedEntity MemberEntity =
1366 InitializedEntity::InitializeMember(*Field, &Entity);
1367 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1368 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001369 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001370
Sebastian Redl14b0c192011-09-24 17:48:00 +00001371 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001372 // Initialize the first field within the union.
1373 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001374 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001375
1376 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001377 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001378
John McCall80639de2010-03-11 19:32:38 +00001379 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001380 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1381 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1382 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001383 // It is possible we have one or more unnamed bitfields remaining.
1384 // Find first (if any) named field and emit warning.
1385 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1386 it != end; ++it) {
1387 if (!it->isUnnamedBitfield()) {
1388 SemaRef.Diag(IList->getSourceRange().getEnd(),
1389 diag::warn_missing_field_initializers) << it->getName();
1390 break;
1391 }
1392 }
1393 }
1394
Mike Stump1eb44332009-09-09 15:08:12 +00001395 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001396 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001397 return;
1398
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001399 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1400 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001401 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001402 ++Index;
1403 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001404 }
1405
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001406 InitializedEntity MemberEntity =
1407 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001408
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001409 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001410 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001411 StructuredList, StructuredIndex);
1412 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001413 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001414 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001415}
Steve Naroff0cca7492008-05-01 22:18:59 +00001416
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001417/// \brief Expand a field designator that refers to a member of an
1418/// anonymous struct or union into a series of field designators that
1419/// refers to the field within the appropriate subobject.
1420///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001421static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001422 DesignatedInitExpr *DIE,
1423 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001424 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001425 typedef DesignatedInitExpr::Designator Designator;
1426
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001427 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001428 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001429 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1430 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1431 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001432 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001433 DIE->getDesignator(DesigIdx)->getDotLoc(),
1434 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1435 else
1436 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1437 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001438 assert(isa<FieldDecl>(*PI));
1439 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001440 }
1441
1442 // Expand the current designator into the set of replacement
1443 // designators, so we have a full subobject path down to where the
1444 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001445 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001446 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001447}
Mike Stump1eb44332009-09-09 15:08:12 +00001448
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001450/// corresponds to FieldName.
1451static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1452 IdentifierInfo *FieldName) {
1453 assert(AnonField->isAnonymousStructOrUnion());
1454 Decl *NextDecl = AnonField->getNextDeclInContext();
1455 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1456 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1457 return IF;
1458 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001459 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001460 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001461}
1462
Sebastian Redl14b0c192011-09-24 17:48:00 +00001463static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1464 DesignatedInitExpr *DIE) {
1465 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1466 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1467 for (unsigned I = 0; I < NumIndexExprs; ++I)
1468 IndexExprs[I] = DIE->getSubExpr(I + 1);
1469 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1470 DIE->size(), IndexExprs.data(),
1471 NumIndexExprs, DIE->getEqualOrColonLoc(),
1472 DIE->usesGNUSyntax(), DIE->getInit());
1473}
1474
Douglas Gregor05c13a32009-01-22 00:58:24 +00001475/// @brief Check the well-formedness of a C99 designated initializer.
1476///
1477/// Determines whether the designated initializer @p DIE, which
1478/// resides at the given @p Index within the initializer list @p
1479/// IList, is well-formed for a current object of type @p DeclType
1480/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001481/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001482/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001483///
1484/// @param IList The initializer list in which this designated
1485/// initializer occurs.
1486///
Douglas Gregor71199712009-04-15 04:56:10 +00001487/// @param DIE The designated initializer expression.
1488///
1489/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001490///
1491/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1492/// into which the designation in @p DIE should refer.
1493///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001494/// @param NextField If non-NULL and the first designator in @p DIE is
1495/// a field, this will be set to the field declaration corresponding
1496/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001497///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001498/// @param NextElementIndex If non-NULL and the first designator in @p
1499/// DIE is an array designator or GNU array-range designator, this
1500/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001501///
1502/// @param Index Index into @p IList where the designated initializer
1503/// @p DIE occurs.
1504///
Douglas Gregor4c678342009-01-28 21:54:33 +00001505/// @param StructuredList The initializer list expression that
1506/// describes all of the subobject initializers in the order they'll
1507/// actually be initialized.
1508///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001509/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001510bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001511InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001512 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001513 DesignatedInitExpr *DIE,
1514 unsigned DesigIdx,
1515 QualType &CurrentObjectType,
1516 RecordDecl::field_iterator *NextField,
1517 llvm::APSInt *NextElementIndex,
1518 unsigned &Index,
1519 InitListExpr *StructuredList,
1520 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001521 bool FinishSubobjectInit,
1522 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001523 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001524 // Check the actual initialization for the designated object type.
1525 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001526
1527 // Temporarily remove the designator expression from the
1528 // initializer list that the child calls see, so that we don't try
1529 // to re-process the designator.
1530 unsigned OldIndex = Index;
1531 IList->setInit(OldIndex, DIE->getInit());
1532
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001533 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001534 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001535
1536 // Restore the designated initializer expression in the syntactic
1537 // form of the initializer list.
1538 if (IList->getInit(OldIndex) != DIE->getInit())
1539 DIE->setInit(IList->getInit(OldIndex));
1540 IList->setInit(OldIndex, DIE);
1541
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001542 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001543 }
1544
Douglas Gregor71199712009-04-15 04:56:10 +00001545 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001546 bool IsFirstDesignator = (DesigIdx == 0);
1547 if (!VerifyOnly) {
1548 assert((IsFirstDesignator || StructuredList) &&
1549 "Need a non-designated initializer list to start from");
1550
1551 // Determine the structural initializer list that corresponds to the
1552 // current subobject.
1553 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1554 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1555 StructuredList, StructuredIndex,
1556 SourceRange(D->getStartLocation(),
1557 DIE->getSourceRange().getEnd()));
1558 assert(StructuredList && "Expected a structured initializer list");
1559 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001560
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001561 if (D->isFieldDesignator()) {
1562 // C99 6.7.8p7:
1563 //
1564 // If a designator has the form
1565 //
1566 // . identifier
1567 //
1568 // then the current object (defined below) shall have
1569 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001570 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001571 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001572 if (!RT) {
1573 SourceLocation Loc = D->getDotLoc();
1574 if (Loc.isInvalid())
1575 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001576 if (!VerifyOnly)
1577 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1578 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001579 ++Index;
1580 return true;
1581 }
1582
Douglas Gregor4c678342009-01-28 21:54:33 +00001583 // Note: we perform a linear search of the fields here, despite
1584 // the fact that we have a faster lookup method, because we always
1585 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001586 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001587 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001588 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001589 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001590 Field = RT->getDecl()->field_begin(),
1591 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001592 for (; Field != FieldEnd; ++Field) {
1593 if (Field->isUnnamedBitfield())
1594 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001595
Francois Picheta0e27f02010-12-22 03:46:10 +00001596 // If we find a field representing an anonymous field, look in the
1597 // IndirectFieldDecl that follow for the designated initializer.
1598 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1599 if (IndirectFieldDecl *IF =
1600 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001601 // In verify mode, don't modify the original.
1602 if (VerifyOnly)
1603 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001604 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1605 D = DIE->getDesignator(DesigIdx);
1606 break;
1607 }
1608 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001609 if (KnownField && KnownField == *Field)
1610 break;
1611 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001612 break;
1613
1614 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001615 }
1616
Douglas Gregor4c678342009-01-28 21:54:33 +00001617 if (Field == FieldEnd) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001618 if (VerifyOnly)
1619 return true; // No typo correction when just trying this out.
1620
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001621 // There was no normal field in the struct with the designated
1622 // name. Perform another lookup for this name, which may find
1623 // something that we can't designate (e.g., a member function),
1624 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001625 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001626 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001627 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001628 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001629 // Name lookup didn't find anything. Determine whether this
1630 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001631 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001632 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001633 TypoCorrection Corrected = SemaRef.CorrectTypo(
1634 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1635 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1636 RT->getDecl(), false, Sema::CTC_NoKeywords);
1637 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001638 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001639 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001640 std::string CorrectedStr(
1641 Corrected.getAsString(SemaRef.getLangOptions()));
1642 std::string CorrectedQuotedStr(
1643 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001644 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001645 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001646 << FieldName << CurrentObjectType << CorrectedQuotedStr
1647 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001649 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001650 } else {
1651 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1652 << FieldName << CurrentObjectType;
1653 ++Index;
1654 return true;
1655 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001656 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001657
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001658 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001659 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001660 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001661 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001662 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001663 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001664 ++Index;
1665 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001666 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001667
Francois Picheta0e27f02010-12-22 03:46:10 +00001668 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001669 // The replacement field comes from typo correction; find it
1670 // in the list of fields.
1671 FieldIndex = 0;
1672 Field = RT->getDecl()->field_begin();
1673 for (; Field != FieldEnd; ++Field) {
1674 if (Field->isUnnamedBitfield())
1675 continue;
1676
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001677 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001678 Field->getIdentifier() == ReplacementField->getIdentifier())
1679 break;
1680
1681 ++FieldIndex;
1682 }
1683 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001684 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001685
1686 // All of the fields of a union are located at the same place in
1687 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001688 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001689 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001690 if (!VerifyOnly)
1691 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001692 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001693
Douglas Gregor54001c12011-06-29 21:51:31 +00001694 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001695 bool InvalidUse;
1696 if (VerifyOnly)
1697 InvalidUse = !SemaRef.CanUseDecl(*Field);
1698 else
1699 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1700 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001701 ++Index;
1702 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001703 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001704
Sebastian Redl14b0c192011-09-24 17:48:00 +00001705 if (!VerifyOnly) {
1706 // Update the designator with the field declaration.
1707 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Sebastian Redl14b0c192011-09-24 17:48:00 +00001709 // Make sure that our non-designated initializer list has space
1710 // for a subobject corresponding to this field.
1711 if (FieldIndex >= StructuredList->getNumInits())
1712 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1713 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001714
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001715 // This designator names a flexible array member.
1716 if (Field->getType()->isIncompleteArrayType()) {
1717 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001718 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001719 // We can't designate an object within the flexible array
1720 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001721 if (!VerifyOnly) {
1722 DesignatedInitExpr::Designator *NextD
1723 = DIE->getDesignator(DesigIdx + 1);
1724 SemaRef.Diag(NextD->getStartLocation(),
1725 diag::err_designator_into_flexible_array_member)
1726 << SourceRange(NextD->getStartLocation(),
1727 DIE->getSourceRange().getEnd());
1728 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1729 << *Field;
1730 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001731 Invalid = true;
1732 }
1733
Chris Lattner9046c222010-10-10 17:49:49 +00001734 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1735 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001736 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001737 if (!VerifyOnly) {
1738 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1739 diag::err_flexible_array_init_needs_braces)
1740 << DIE->getInit()->getSourceRange();
1741 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1742 << *Field;
1743 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001744 Invalid = true;
1745 }
1746
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001747 // Check GNU flexible array initializer.
1748 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1749 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001750 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001751
1752 if (Invalid) {
1753 ++Index;
1754 return true;
1755 }
1756
1757 // Initialize the array.
1758 bool prevHadError = hadError;
1759 unsigned newStructuredIndex = FieldIndex;
1760 unsigned OldIndex = Index;
1761 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001762
1763 InitializedEntity MemberEntity =
1764 InitializedEntity::InitializeMember(*Field, &Entity);
1765 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001766 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001767
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001768 IList->setInit(OldIndex, DIE);
1769 if (hadError && !prevHadError) {
1770 ++Field;
1771 ++FieldIndex;
1772 if (NextField)
1773 *NextField = Field;
1774 StructuredIndex = FieldIndex;
1775 return true;
1776 }
1777 } else {
1778 // Recurse to check later designated subobjects.
1779 QualType FieldType = (*Field)->getType();
1780 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001782 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001783 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001784 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1785 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001786 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001787 true, false))
1788 return true;
1789 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001790
1791 // Find the position of the next field to be initialized in this
1792 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001793 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001794 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001795
1796 // If this the first designator, our caller will continue checking
1797 // the rest of this struct/class/union subobject.
1798 if (IsFirstDesignator) {
1799 if (NextField)
1800 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001801 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001802 return false;
1803 }
1804
Douglas Gregor34e79462009-01-28 23:36:17 +00001805 if (!FinishSubobjectInit)
1806 return false;
1807
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001808 // We've already initialized something in the union; we're done.
1809 if (RT->getDecl()->isUnion())
1810 return hadError;
1811
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001812 // Check the remaining fields within this class/struct/union subobject.
1813 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001814
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001815 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001816 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001817 return hadError && !prevHadError;
1818 }
1819
1820 // C99 6.7.8p6:
1821 //
1822 // If a designator has the form
1823 //
1824 // [ constant-expression ]
1825 //
1826 // then the current object (defined below) shall have array
1827 // type and the expression shall be an integer constant
1828 // expression. If the array is of unknown size, any
1829 // nonnegative value is valid.
1830 //
1831 // Additionally, cope with the GNU extension that permits
1832 // designators of the form
1833 //
1834 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001835 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001836 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001837 if (!VerifyOnly)
1838 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1839 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001840 ++Index;
1841 return true;
1842 }
1843
1844 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001845 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1846 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001847 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001848 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001849 DesignatedEndIndex = DesignatedStartIndex;
1850 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001851 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001852
Mike Stump1eb44332009-09-09 15:08:12 +00001853 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001854 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001855 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001856 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001857 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001858
Chris Lattnere0fd8322011-02-19 22:28:58 +00001859 // Codegen can't handle evaluating array range designators that have side
1860 // effects, because we replicate the AST value for each initialized element.
1861 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1862 // elements with something that has a side effect, so codegen can emit an
1863 // "error unsupported" error instead of miscompiling the app.
1864 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001865 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001866 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001867 }
1868
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001869 if (isa<ConstantArrayType>(AT)) {
1870 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001871 DesignatedStartIndex
1872 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001873 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001874 DesignatedEndIndex
1875 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001876 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1877 if (DesignatedEndIndex >= MaxElements) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001878 if (VerifyOnly)
1879 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1880 diag::err_array_designator_too_large)
1881 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1882 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001883 ++Index;
1884 return true;
1885 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001886 } else {
1887 // Make sure the bit-widths and signedness match.
1888 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001889 DesignatedEndIndex
1890 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001891 else if (DesignatedStartIndex.getBitWidth() <
1892 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001893 DesignatedStartIndex
1894 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001895 DesignatedStartIndex.setIsUnsigned(true);
1896 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001897 }
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Douglas Gregor4c678342009-01-28 21:54:33 +00001899 // Make sure that our non-designated initializer list has space
1900 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001901 if (!VerifyOnly &&
1902 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001903 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001904 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001905
Douglas Gregor34e79462009-01-28 23:36:17 +00001906 // Repeatedly perform subobject initializations in the range
1907 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001908
Douglas Gregor34e79462009-01-28 23:36:17 +00001909 // Move to the next designator
1910 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1911 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001912
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001913 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001914 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001915
Douglas Gregor34e79462009-01-28 23:36:17 +00001916 while (DesignatedStartIndex <= DesignatedEndIndex) {
1917 // Recurse to check later designated subobjects.
1918 QualType ElementType = AT->getElementType();
1919 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001920
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001921 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001922 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1923 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001924 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001925 (DesignatedStartIndex == DesignatedEndIndex),
1926 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001927 return true;
1928
1929 // Move to the next index in the array that we'll be initializing.
1930 ++DesignatedStartIndex;
1931 ElementIndex = DesignatedStartIndex.getZExtValue();
1932 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001933
1934 // If this the first designator, our caller will continue checking
1935 // the rest of this array subobject.
1936 if (IsFirstDesignator) {
1937 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001938 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001939 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001940 return false;
1941 }
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Douglas Gregor34e79462009-01-28 23:36:17 +00001943 if (!FinishSubobjectInit)
1944 return false;
1945
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001946 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001947 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001948 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001949 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001950 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001951 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001952}
1953
Douglas Gregor4c678342009-01-28 21:54:33 +00001954// Get the structured initializer list for a subobject of type
1955// @p CurrentObjectType.
1956InitListExpr *
1957InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1958 QualType CurrentObjectType,
1959 InitListExpr *StructuredList,
1960 unsigned StructuredIndex,
1961 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001962 if (VerifyOnly)
1963 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00001964 Expr *ExistingInit = 0;
1965 if (!StructuredList)
1966 ExistingInit = SyntacticToSemantic[IList];
1967 else if (StructuredIndex < StructuredList->getNumInits())
1968 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Douglas Gregor4c678342009-01-28 21:54:33 +00001970 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1971 return Result;
1972
1973 if (ExistingInit) {
1974 // We are creating an initializer list that initializes the
1975 // subobjects of the current object, but there was already an
1976 // initialization that completely initialized the current
1977 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001978 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001979 // struct X { int a, b; };
1980 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001981 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001982 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1983 // designated initializer re-initializes the whole
1984 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001985 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001986 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001987 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001988 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001989 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001990 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001991 << ExistingInit->getSourceRange();
1992 }
1993
Mike Stump1eb44332009-09-09 15:08:12 +00001994 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001995 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1996 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001997 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001998
Douglas Gregor63982352010-07-13 18:40:04 +00001999 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00002000
Douglas Gregorfa219202009-03-20 23:58:33 +00002001 // Pre-allocate storage for the structured initializer list.
2002 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002003 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002004 bool GotNumInits = false;
2005 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002006 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002007 GotNumInits = true;
2008 } else if (Index < IList->getNumInits()) {
2009 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002010 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002011 GotNumInits = true;
2012 }
Douglas Gregor08457732009-03-21 18:13:52 +00002013 }
2014
Mike Stump1eb44332009-09-09 15:08:12 +00002015 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002016 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2017 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2018 NumElements = CAType->getSize().getZExtValue();
2019 // Simple heuristic so that we don't allocate a very large
2020 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002021 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002022 NumElements = 0;
2023 }
John McCall183700f2009-09-21 23:43:11 +00002024 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002025 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002026 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002027 RecordDecl *RDecl = RType->getDecl();
2028 if (RDecl->isUnion())
2029 NumElements = 1;
2030 else
Mike Stump1eb44332009-09-09 15:08:12 +00002031 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002032 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002033 }
2034
Douglas Gregor08457732009-03-21 18:13:52 +00002035 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002036 NumElements = IList->getNumInits();
2037
Ted Kremenek709210f2010-04-13 23:39:13 +00002038 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002039
Douglas Gregor4c678342009-01-28 21:54:33 +00002040 // Link this new initializer list into the structured initializer
2041 // lists.
2042 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002043 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002044 else {
2045 Result->setSyntacticForm(IList);
2046 SyntacticToSemantic[IList] = Result;
2047 }
2048
2049 return Result;
2050}
2051
2052/// Update the initializer at index @p StructuredIndex within the
2053/// structured initializer list to the value @p expr.
2054void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2055 unsigned &StructuredIndex,
2056 Expr *expr) {
2057 // No structured initializer list to update
2058 if (!StructuredList)
2059 return;
2060
Ted Kremenek709210f2010-04-13 23:39:13 +00002061 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2062 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002063 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00002064 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002065 diag::warn_initializer_overrides)
2066 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002067 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002068 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002069 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 << PrevInit->getSourceRange();
2071 }
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Douglas Gregor4c678342009-01-28 21:54:33 +00002073 ++StructuredIndex;
2074}
2075
Douglas Gregor05c13a32009-01-22 00:58:24 +00002076/// Check that the given Index expression is a valid array designator
2077/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002078/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002079/// and produces a reasonable diagnostic if there is a
2080/// failure. Returns true if there was an error, false otherwise. If
2081/// everything went okay, Value will receive the value of the constant
2082/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002083static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00002084CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002085 SourceLocation Loc = Index->getSourceRange().getBegin();
2086
2087 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00002088 if (S.VerifyIntegerConstantExpression(Index, &Value))
2089 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002090
Chris Lattner3bf68932009-04-25 21:59:05 +00002091 if (Value.isSigned() && Value.isNegative())
2092 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002093 << Value.toString(10) << Index->getSourceRange();
2094
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002095 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002096 return false;
2097}
2098
John McCall60d7b3a2010-08-24 06:29:42 +00002099ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002100 SourceLocation Loc,
2101 bool GNUSyntax,
2102 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002103 typedef DesignatedInitExpr::Designator ASTDesignator;
2104
2105 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002106 SmallVector<ASTDesignator, 32> Designators;
2107 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002108
2109 // Build designators and check array designator expressions.
2110 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2111 const Designator &D = Desig.getDesignator(Idx);
2112 switch (D.getKind()) {
2113 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002114 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002115 D.getFieldLoc()));
2116 break;
2117
2118 case Designator::ArrayDesignator: {
2119 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2120 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002121 if (!Index->isTypeDependent() &&
2122 !Index->isValueDependent() &&
2123 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002124 Invalid = true;
2125 else {
2126 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002127 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002128 D.getRBracketLoc()));
2129 InitExpressions.push_back(Index);
2130 }
2131 break;
2132 }
2133
2134 case Designator::ArrayRangeDesignator: {
2135 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2136 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2137 llvm::APSInt StartValue;
2138 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002139 bool StartDependent = StartIndex->isTypeDependent() ||
2140 StartIndex->isValueDependent();
2141 bool EndDependent = EndIndex->isTypeDependent() ||
2142 EndIndex->isValueDependent();
2143 if ((!StartDependent &&
2144 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2145 (!EndDependent &&
2146 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002147 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002148 else {
2149 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002150 if (StartDependent || EndDependent) {
2151 // Nothing to compute.
2152 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002153 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002154 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002155 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002156
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002157 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002158 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002159 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002160 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2161 Invalid = true;
2162 } else {
2163 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002164 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002165 D.getEllipsisLoc(),
2166 D.getRBracketLoc()));
2167 InitExpressions.push_back(StartIndex);
2168 InitExpressions.push_back(EndIndex);
2169 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002170 }
2171 break;
2172 }
2173 }
2174 }
2175
2176 if (Invalid || Init.isInvalid())
2177 return ExprError();
2178
2179 // Clear out the expressions within the designation.
2180 Desig.ClearExprs(*this);
2181
2182 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002183 = DesignatedInitExpr::Create(Context,
2184 Designators.data(), Designators.size(),
2185 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002186 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002187
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002188 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002189 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2190 << DIE->getSourceRange();
2191 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002192 Diag(DIE->getLocStart(), diag::ext_designated_init)
2193 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002194
Douglas Gregor05c13a32009-01-22 00:58:24 +00002195 return Owned(DIE);
2196}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002197
Douglas Gregor20093b42009-12-09 23:02:17 +00002198//===----------------------------------------------------------------------===//
2199// Initialization entity
2200//===----------------------------------------------------------------------===//
2201
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002202InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002203 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002204 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002205{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002206 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2207 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002208 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002209 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002210 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002211 Type = VT->getElementType();
2212 } else {
2213 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2214 assert(CT && "Unexpected type");
2215 Kind = EK_ComplexElement;
2216 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002217 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002218}
2219
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002220InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002221 CXXBaseSpecifier *Base,
2222 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002223{
2224 InitializedEntity Result;
2225 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002226 Result.Base = reinterpret_cast<uintptr_t>(Base);
2227 if (IsInheritedVirtualBase)
2228 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002229
Douglas Gregord6542d82009-12-22 15:35:07 +00002230 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002231 return Result;
2232}
2233
Douglas Gregor99a2e602009-12-16 01:38:02 +00002234DeclarationName InitializedEntity::getName() const {
2235 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002236 case EK_Parameter: {
2237 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2238 return (D ? D->getDeclName() : DeclarationName());
2239 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002240
2241 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002242 case EK_Member:
2243 return VariableOrMember->getDeclName();
2244
2245 case EK_Result:
2246 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002247 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002248 case EK_Temporary:
2249 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002250 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002251 case EK_ArrayElement:
2252 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002253 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002254 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002255 return DeclarationName();
2256 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002257
Douglas Gregor99a2e602009-12-16 01:38:02 +00002258 // Silence GCC warning
2259 return DeclarationName();
2260}
2261
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002262DeclaratorDecl *InitializedEntity::getDecl() const {
2263 switch (getKind()) {
2264 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002265 case EK_Member:
2266 return VariableOrMember;
2267
John McCallf85e1932011-06-15 23:02:42 +00002268 case EK_Parameter:
2269 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2270
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002271 case EK_Result:
2272 case EK_Exception:
2273 case EK_New:
2274 case EK_Temporary:
2275 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002276 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002277 case EK_ArrayElement:
2278 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002279 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002280 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002281 return 0;
2282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002283
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002284 // Silence GCC warning
2285 return 0;
2286}
2287
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002288bool InitializedEntity::allowsNRVO() const {
2289 switch (getKind()) {
2290 case EK_Result:
2291 case EK_Exception:
2292 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002293
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002294 case EK_Variable:
2295 case EK_Parameter:
2296 case EK_Member:
2297 case EK_New:
2298 case EK_Temporary:
2299 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002300 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002301 case EK_ArrayElement:
2302 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002303 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002304 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002305 break;
2306 }
2307
2308 return false;
2309}
2310
Douglas Gregor20093b42009-12-09 23:02:17 +00002311//===----------------------------------------------------------------------===//
2312// Initialization sequence
2313//===----------------------------------------------------------------------===//
2314
2315void InitializationSequence::Step::Destroy() {
2316 switch (Kind) {
2317 case SK_ResolveAddressOfOverloadedFunction:
2318 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002319 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002320 case SK_CastDerivedToBaseLValue:
2321 case SK_BindReference:
2322 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002323 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002324 case SK_UserConversion:
2325 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002326 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002327 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002328 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002329 case SK_ListConstructorCall:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002330 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002331 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002332 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002333 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002334 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002335 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002336 case SK_PassByIndirectCopyRestore:
2337 case SK_PassByIndirectRestore:
2338 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002339 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002340
Douglas Gregor20093b42009-12-09 23:02:17 +00002341 case SK_ConversionSequence:
2342 delete ICS;
2343 }
2344}
2345
Douglas Gregorb70cf442010-03-26 20:14:36 +00002346bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002347 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002348}
2349
2350bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002351 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002352 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002353
Douglas Gregorb70cf442010-03-26 20:14:36 +00002354 switch (getFailureKind()) {
2355 case FK_TooManyInitsForReference:
2356 case FK_ArrayNeedsInitList:
2357 case FK_ArrayNeedsInitListOrStringLiteral:
2358 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2359 case FK_NonConstLValueReferenceBindingToTemporary:
2360 case FK_NonConstLValueReferenceBindingToUnrelated:
2361 case FK_RValueReferenceBindingToLValue:
2362 case FK_ReferenceInitDropsQualifiers:
2363 case FK_ReferenceInitFailed:
2364 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002365 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002366 case FK_TooManyInitsForScalar:
2367 case FK_ReferenceBindingToInitList:
2368 case FK_InitListBadDestinationType:
2369 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002370 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002371 case FK_ArrayTypeMismatch:
2372 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002373 case FK_ListInitializationFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002374 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002375
Douglas Gregorb70cf442010-03-26 20:14:36 +00002376 case FK_ReferenceInitOverloadFailed:
2377 case FK_UserConversionOverloadFailed:
2378 case FK_ConstructorOverloadFailed:
2379 return FailedOverloadResult == OR_Ambiguous;
2380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002381
Douglas Gregorb70cf442010-03-26 20:14:36 +00002382 return false;
2383}
2384
Douglas Gregord6e44a32010-04-16 22:09:46 +00002385bool InitializationSequence::isConstructorInitialization() const {
2386 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2387}
2388
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002389bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2390 const Expr *Initializer,
2391 bool *isInitializerConstant,
2392 APValue *ConstantValue) const {
2393 if (Steps.empty() || Initializer->isValueDependent())
2394 return false;
2395
2396 const Step &LastStep = Steps.back();
2397 if (LastStep.Kind != SK_ConversionSequence)
2398 return false;
2399
2400 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2401 const StandardConversionSequence *SCS = NULL;
2402 switch (ICS.getKind()) {
2403 case ImplicitConversionSequence::StandardConversion:
2404 SCS = &ICS.Standard;
2405 break;
2406 case ImplicitConversionSequence::UserDefinedConversion:
2407 SCS = &ICS.UserDefined.After;
2408 break;
2409 case ImplicitConversionSequence::AmbiguousConversion:
2410 case ImplicitConversionSequence::EllipsisConversion:
2411 case ImplicitConversionSequence::BadConversion:
2412 return false;
2413 }
2414
2415 // Check if SCS represents a narrowing conversion, according to C++0x
2416 // [dcl.init.list]p7:
2417 //
2418 // A narrowing conversion is an implicit conversion ...
2419 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2420 QualType FromType = SCS->getToType(0);
2421 QualType ToType = SCS->getToType(1);
2422 switch (PossibleNarrowing) {
2423 // * from a floating-point type to an integer type, or
2424 //
2425 // * from an integer type or unscoped enumeration type to a floating-point
2426 // type, except where the source is a constant expression and the actual
2427 // value after conversion will fit into the target type and will produce
2428 // the original value when converted back to the original type, or
2429 case ICK_Floating_Integral:
2430 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2431 *isInitializerConstant = false;
2432 return true;
2433 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2434 llvm::APSInt IntConstantValue;
2435 if (Initializer &&
2436 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2437 // Convert the integer to the floating type.
2438 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2439 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2440 llvm::APFloat::rmNearestTiesToEven);
2441 // And back.
2442 llvm::APSInt ConvertedValue = IntConstantValue;
2443 bool ignored;
2444 Result.convertToInteger(ConvertedValue,
2445 llvm::APFloat::rmTowardZero, &ignored);
2446 // If the resulting value is different, this was a narrowing conversion.
2447 if (IntConstantValue != ConvertedValue) {
2448 *isInitializerConstant = true;
2449 *ConstantValue = APValue(IntConstantValue);
2450 return true;
2451 }
2452 } else {
2453 // Variables are always narrowings.
2454 *isInitializerConstant = false;
2455 return true;
2456 }
2457 }
2458 return false;
2459
2460 // * from long double to double or float, or from double to float, except
2461 // where the source is a constant expression and the actual value after
2462 // conversion is within the range of values that can be represented (even
2463 // if it cannot be represented exactly), or
2464 case ICK_Floating_Conversion:
2465 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2466 // FromType is larger than ToType.
2467 Expr::EvalResult InitializerValue;
2468 // FIXME: Check whether Initializer is a constant expression according
2469 // to C++0x [expr.const], rather than just whether it can be folded.
2470 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2471 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2472 // Constant! (Except for FIXME above.)
2473 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2474 // Convert the source value into the target type.
2475 bool ignored;
2476 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2477 Ctx.getFloatTypeSemantics(ToType),
2478 llvm::APFloat::rmNearestTiesToEven, &ignored);
2479 // If there was no overflow, the source value is within the range of
2480 // values that can be represented.
2481 if (ConvertStatus & llvm::APFloat::opOverflow) {
2482 *isInitializerConstant = true;
2483 *ConstantValue = InitializerValue.Val;
2484 return true;
2485 }
2486 } else {
2487 *isInitializerConstant = false;
2488 return true;
2489 }
2490 }
2491 return false;
2492
2493 // * from an integer type or unscoped enumeration type to an integer type
2494 // that cannot represent all the values of the original type, except where
2495 // the source is a constant expression and the actual value after
2496 // conversion will fit into the target type and will produce the original
2497 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002498 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002499 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2500 // Boolean conversions can be from pointers and pointers to members
2501 // [conv.bool], and those aren't considered narrowing conversions.
2502 return false;
2503 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002504 case ICK_Integral_Conversion: {
2505 assert(FromType->isIntegralOrUnscopedEnumerationType());
2506 assert(ToType->isIntegralOrUnscopedEnumerationType());
2507 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2508 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2509 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2510 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2511
2512 if (FromWidth > ToWidth ||
2513 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2514 // Not all values of FromType can be represented in ToType.
2515 llvm::APSInt InitializerValue;
2516 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2517 *isInitializerConstant = true;
2518 *ConstantValue = APValue(InitializerValue);
2519
2520 // Add a bit to the InitializerValue so we don't have to worry about
2521 // signed vs. unsigned comparisons.
2522 InitializerValue = InitializerValue.extend(
2523 InitializerValue.getBitWidth() + 1);
2524 // Convert the initializer to and from the target width and signed-ness.
2525 llvm::APSInt ConvertedValue = InitializerValue;
2526 ConvertedValue = ConvertedValue.trunc(ToWidth);
2527 ConvertedValue.setIsSigned(ToSigned);
2528 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2529 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2530 // If the result is different, this was a narrowing conversion.
2531 return ConvertedValue != InitializerValue;
2532 } else {
2533 // Variables are always narrowings.
2534 *isInitializerConstant = false;
2535 return true;
2536 }
2537 }
2538 return false;
2539 }
2540
2541 default:
2542 // Other kinds of conversions are not narrowings.
2543 return false;
2544 }
2545}
2546
Douglas Gregor20093b42009-12-09 23:02:17 +00002547void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002548 FunctionDecl *Function,
2549 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002550 Step S;
2551 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2552 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002553 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002554 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002555 Steps.push_back(S);
2556}
2557
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002558void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002559 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002560 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002561 switch (VK) {
2562 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2563 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2564 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002565 default: llvm_unreachable("No such category");
2566 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002567 S.Type = BaseType;
2568 Steps.push_back(S);
2569}
2570
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002571void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002572 bool BindingTemporary) {
2573 Step S;
2574 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2575 S.Type = T;
2576 Steps.push_back(S);
2577}
2578
Douglas Gregor523d46a2010-04-18 07:40:54 +00002579void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2580 Step S;
2581 S.Kind = SK_ExtraneousCopyToTemporary;
2582 S.Type = T;
2583 Steps.push_back(S);
2584}
2585
Eli Friedman03981012009-12-11 02:42:07 +00002586void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002587 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002588 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002589 Step S;
2590 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002591 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002592 S.Function.Function = Function;
2593 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002594 Steps.push_back(S);
2595}
2596
2597void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002598 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002599 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002600 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002601 switch (VK) {
2602 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002603 S.Kind = SK_QualificationConversionRValue;
2604 break;
John McCall5baba9d2010-08-25 10:28:54 +00002605 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002606 S.Kind = SK_QualificationConversionXValue;
2607 break;
John McCall5baba9d2010-08-25 10:28:54 +00002608 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002609 S.Kind = SK_QualificationConversionLValue;
2610 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002611 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002612 S.Type = Ty;
2613 Steps.push_back(S);
2614}
2615
2616void InitializationSequence::AddConversionSequenceStep(
2617 const ImplicitConversionSequence &ICS,
2618 QualType T) {
2619 Step S;
2620 S.Kind = SK_ConversionSequence;
2621 S.Type = T;
2622 S.ICS = new ImplicitConversionSequence(ICS);
2623 Steps.push_back(S);
2624}
2625
Douglas Gregord87b61f2009-12-10 17:56:55 +00002626void InitializationSequence::AddListInitializationStep(QualType T) {
2627 Step S;
2628 S.Kind = SK_ListInitialization;
2629 S.Type = T;
2630 Steps.push_back(S);
2631}
2632
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002633void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002634InitializationSequence::AddConstructorInitializationStep(
2635 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002636 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002637 QualType T) {
2638 Step S;
2639 S.Kind = SK_ConstructorInitialization;
2640 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002641 S.Function.Function = Constructor;
2642 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002643 Steps.push_back(S);
2644}
2645
Douglas Gregor71d17402009-12-15 00:01:57 +00002646void InitializationSequence::AddZeroInitializationStep(QualType T) {
2647 Step S;
2648 S.Kind = SK_ZeroInitialization;
2649 S.Type = T;
2650 Steps.push_back(S);
2651}
2652
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002653void InitializationSequence::AddCAssignmentStep(QualType T) {
2654 Step S;
2655 S.Kind = SK_CAssignment;
2656 S.Type = T;
2657 Steps.push_back(S);
2658}
2659
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002660void InitializationSequence::AddStringInitStep(QualType T) {
2661 Step S;
2662 S.Kind = SK_StringInit;
2663 S.Type = T;
2664 Steps.push_back(S);
2665}
2666
Douglas Gregor569c3162010-08-07 11:51:51 +00002667void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2668 Step S;
2669 S.Kind = SK_ObjCObjectConversion;
2670 S.Type = T;
2671 Steps.push_back(S);
2672}
2673
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002674void InitializationSequence::AddArrayInitStep(QualType T) {
2675 Step S;
2676 S.Kind = SK_ArrayInit;
2677 S.Type = T;
2678 Steps.push_back(S);
2679}
2680
John McCallf85e1932011-06-15 23:02:42 +00002681void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2682 bool shouldCopy) {
2683 Step s;
2684 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2685 : SK_PassByIndirectRestore);
2686 s.Type = type;
2687 Steps.push_back(s);
2688}
2689
2690void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2691 Step S;
2692 S.Kind = SK_ProduceObjCObject;
2693 S.Type = T;
2694 Steps.push_back(S);
2695}
2696
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002697void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002698 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002699 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002700 this->Failure = Failure;
2701 this->FailedOverloadResult = Result;
2702}
2703
2704//===----------------------------------------------------------------------===//
2705// Attempt initialization
2706//===----------------------------------------------------------------------===//
2707
John McCallf85e1932011-06-15 23:02:42 +00002708static void MaybeProduceObjCObject(Sema &S,
2709 InitializationSequence &Sequence,
2710 const InitializedEntity &Entity) {
2711 if (!S.getLangOptions().ObjCAutoRefCount) return;
2712
2713 /// When initializing a parameter, produce the value if it's marked
2714 /// __attribute__((ns_consumed)).
2715 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2716 if (!Entity.isParameterConsumed())
2717 return;
2718
2719 assert(Entity.getType()->isObjCRetainableType() &&
2720 "consuming an object of unretainable type?");
2721 Sequence.AddProduceObjCObjectStep(Entity.getType());
2722
2723 /// When initializing a return value, if the return type is a
2724 /// retainable type, then returns need to immediately retain the
2725 /// object. If an autorelease is required, it will be done at the
2726 /// last instant.
2727 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2728 if (!Entity.getType()->isObjCRetainableType())
2729 return;
2730
2731 Sequence.AddProduceObjCObjectStep(Entity.getType());
2732 }
2733}
2734
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002735/// \brief Attempt list initialization (C++0x [dcl.init.list])
2736static void TryListInitialization(Sema &S,
2737 const InitializedEntity &Entity,
2738 const InitializationKind &Kind,
2739 InitListExpr *InitList,
2740 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002741 QualType DestType = Entity.getType();
2742
Sebastian Redl14b0c192011-09-24 17:48:00 +00002743 // C++ doesn't allow scalar initialization with more than one argument.
2744 // But C99 complex numbers are scalars and it makes sense there.
2745 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2746 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2747 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2748 return;
2749 }
2750 // FIXME: C++0x defines behavior for these two cases.
2751 if (DestType->isReferenceType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002752 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2753 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002754 }
2755 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002756 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00002757 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002758 }
2759
Sebastian Redl14b0c192011-09-24 17:48:00 +00002760 InitListChecker CheckInitList(S, Entity, InitList,
2761 DestType, /*VerifyOnly=*/true);
2762 if (CheckInitList.HadError()) {
2763 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2764 return;
2765 }
2766
2767 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002768 Sequence.AddListInitializationStep(DestType);
2769}
Douglas Gregor20093b42009-12-09 23:02:17 +00002770
2771/// \brief Try a reference initialization that involves calling a conversion
2772/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002773static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2774 const InitializedEntity &Entity,
2775 const InitializationKind &Kind,
2776 Expr *Initializer,
2777 bool AllowRValues,
2778 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002779 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002780 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2781 QualType T1 = cv1T1.getUnqualifiedType();
2782 QualType cv2T2 = Initializer->getType();
2783 QualType T2 = cv2T2.getUnqualifiedType();
2784
2785 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002786 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002787 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002788 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002789 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002790 ObjCConversion,
2791 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002792 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002793 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002794 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002795 (void)ObjCLifetimeConversion;
2796
Douglas Gregor20093b42009-12-09 23:02:17 +00002797 // Build the candidate set directly in the initialization sequence
2798 // structure, so that it will persist if we fail.
2799 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2800 CandidateSet.clear();
2801
2802 // Determine whether we are allowed to call explicit constructors or
2803 // explicit conversion operators.
2804 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805
Douglas Gregor20093b42009-12-09 23:02:17 +00002806 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002807 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2808 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002809 // The type we're converting to is a class type. Enumerate its constructors
2810 // to see if there is a suitable conversion.
2811 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002812
Douglas Gregor20093b42009-12-09 23:02:17 +00002813 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002814 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002815 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002816 NamedDecl *D = *Con;
2817 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2818
Douglas Gregor20093b42009-12-09 23:02:17 +00002819 // Find the constructor (which may be a template).
2820 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002821 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002822 if (ConstructorTmpl)
2823 Constructor = cast<CXXConstructorDecl>(
2824 ConstructorTmpl->getTemplatedDecl());
2825 else
John McCall9aa472c2010-03-19 07:35:19 +00002826 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002827
Douglas Gregor20093b42009-12-09 23:02:17 +00002828 if (!Constructor->isInvalidDecl() &&
2829 Constructor->isConvertingConstructor(AllowExplicit)) {
2830 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002831 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002832 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002833 &Initializer, 1, CandidateSet,
2834 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002835 else
John McCall9aa472c2010-03-19 07:35:19 +00002836 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002837 &Initializer, 1, CandidateSet,
2838 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002839 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002840 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002841 }
John McCall572fc622010-08-17 07:23:57 +00002842 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2843 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002844
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002845 const RecordType *T2RecordType = 0;
2846 if ((T2RecordType = T2->getAs<RecordType>()) &&
2847 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002848 // The type we're converting from is a class type, enumerate its conversion
2849 // functions.
2850 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2851
John McCalleec51cf2010-01-20 00:46:10 +00002852 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002853 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002854 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2855 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002856 NamedDecl *D = *I;
2857 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2858 if (isa<UsingShadowDecl>(D))
2859 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002860
Douglas Gregor20093b42009-12-09 23:02:17 +00002861 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2862 CXXConversionDecl *Conv;
2863 if (ConvTemplate)
2864 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2865 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002866 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002867
Douglas Gregor20093b42009-12-09 23:02:17 +00002868 // If the conversion function doesn't return a reference type,
2869 // it can't be considered for this conversion unless we're allowed to
2870 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871 // FIXME: Do we need to make sure that we only consider conversion
2872 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002873 // break recursion.
2874 if ((AllowExplicit || !Conv->isExplicit()) &&
2875 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2876 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002877 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002878 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002879 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002880 else
John McCall9aa472c2010-03-19 07:35:19 +00002881 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002882 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002883 }
2884 }
2885 }
John McCall572fc622010-08-17 07:23:57 +00002886 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2887 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002888
Douglas Gregor20093b42009-12-09 23:02:17 +00002889 SourceLocation DeclLoc = Initializer->getLocStart();
2890
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002891 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002892 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002893 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002894 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002895 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002896
Douglas Gregor20093b42009-12-09 23:02:17 +00002897 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002898
Chandler Carruth25ca4212011-02-25 19:41:05 +00002899 // This is the overload that will actually be used for the initialization, so
2900 // mark it as used.
2901 S.MarkDeclarationReferenced(DeclLoc, Function);
2902
Eli Friedman03981012009-12-11 02:42:07 +00002903 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002904 if (isa<CXXConversionDecl>(Function))
2905 T2 = Function->getResultType();
2906 else
2907 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002908
2909 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002910 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002911 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002912
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002913 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002914 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002915 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002916 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002917 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002918 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002919 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002920
Douglas Gregor20093b42009-12-09 23:02:17 +00002921 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002922 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002923 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002924 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002925 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002926 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002927 NewDerivedToBase, NewObjCConversion,
2928 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002929 if (NewRefRelationship == Sema::Ref_Incompatible) {
2930 // If the type we've converted to is not reference-related to the
2931 // type we're looking for, then there is another conversion step
2932 // we need to perform to produce a temporary of the right type
2933 // that we'll be binding to.
2934 ImplicitConversionSequence ICS;
2935 ICS.setStandard();
2936 ICS.Standard = Best->FinalConversion;
2937 T2 = ICS.Standard.getToType(2);
2938 Sequence.AddConversionSequenceStep(ICS, T2);
2939 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002940 Sequence.AddDerivedToBaseCastStep(
2941 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002942 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002943 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002944 else if (NewObjCConversion)
2945 Sequence.AddObjCObjectConversionStep(
2946 S.Context.getQualifiedType(T1,
2947 T2.getNonReferenceType().getQualifiers()));
2948
Douglas Gregor20093b42009-12-09 23:02:17 +00002949 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002950 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002951
Douglas Gregor20093b42009-12-09 23:02:17 +00002952 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2953 return OR_Success;
2954}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002955
2956/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2957static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002958 const InitializedEntity &Entity,
2959 const InitializationKind &Kind,
2960 Expr *Initializer,
2961 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002962 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002963 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002964 Qualifiers T1Quals;
2965 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002966 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002967 Qualifiers T2Quals;
2968 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002969 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002970
Douglas Gregor20093b42009-12-09 23:02:17 +00002971 // If the initializer is the address of an overloaded function, try
2972 // to resolve the overloaded function. If all goes well, T2 is the
2973 // type of the resulting function.
2974 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002975 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002977 T1,
2978 false,
2979 Found)) {
2980 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2981 cv2T2 = Fn->getType();
2982 T2 = cv2T2.getUnqualifiedType();
2983 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002984 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2985 return;
2986 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002987 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002988
Douglas Gregor20093b42009-12-09 23:02:17 +00002989 // Compute some basic properties of the types and the initializer.
2990 bool isLValueRef = DestType->isLValueReferenceType();
2991 bool isRValueRef = !isLValueRef;
2992 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002993 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002994 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002995 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002996 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002997 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002998 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002999
Douglas Gregor20093b42009-12-09 23:02:17 +00003000 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003001 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003002 // "cv2 T2" as follows:
3003 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003004 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003005 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003006 // Note the analogous bullet points for rvlaue refs to functions. Because
3007 // there are no function rvalues in C++, rvalue refs to functions are treated
3008 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003009 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003010 bool T1Function = T1->isFunctionType();
3011 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003012 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003013 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003014 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003015 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003016 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003017 // reference-compatible with "cv2 T2," or
3018 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003020 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003021 // can occur. However, we do pay attention to whether it is a bit-field
3022 // to decide whether we're actually binding to a temporary created from
3023 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003024 if (DerivedToBase)
3025 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003026 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003027 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003028 else if (ObjCConversion)
3029 Sequence.AddObjCObjectConversionStep(
3030 S.Context.getQualifiedType(T1, T2Quals));
3031
Chandler Carruth5535c382010-01-12 20:32:25 +00003032 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003033 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003034 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003035 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003036 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003037 return;
3038 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003039
3040 // - has a class type (i.e., T2 is a class type), where T1 is not
3041 // reference-related to T2, and can be implicitly converted to an
3042 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3043 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003044 // applicable conversion functions (13.3.1.6) and choosing the best
3045 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003046 // If we have an rvalue ref to function type here, the rhs must be
3047 // an rvalue.
3048 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3049 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003050 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003051 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003052 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003053 Sequence);
3054 if (ConvOvlResult == OR_Success)
3055 return;
John McCall1d318332010-01-12 00:44:57 +00003056 if (ConvOvlResult != OR_No_Viable_Function) {
3057 Sequence.SetOverloadFailure(
3058 InitializationSequence::FK_ReferenceInitOverloadFailed,
3059 ConvOvlResult);
3060 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003061 }
3062 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003063
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003064 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003065 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003066 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003067 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003068 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3069 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3070 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003071 Sequence.SetOverloadFailure(
3072 InitializationSequence::FK_ReferenceInitOverloadFailed,
3073 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003074 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003075 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003076 ? (RefRelationship == Sema::Ref_Related
3077 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3078 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3079 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003080
Douglas Gregor20093b42009-12-09 23:02:17 +00003081 return;
3082 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003083
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003084 // - If the initializer expression
3085 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3086 // "cv1 T1" is reference-compatible with "cv2 T2"
3087 // Note: functions are handled below.
3088 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003089 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003090 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003091 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003092 (InitCategory.isXValue() ||
3093 (InitCategory.isPRValue() && T2->isRecordType()) ||
3094 (InitCategory.isPRValue() && T2->isArrayType()))) {
3095 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3096 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003097 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3098 // compiler the freedom to perform a copy here or bind to the
3099 // object, while C++0x requires that we bind directly to the
3100 // object. Hence, we always bind to the object without making an
3101 // extra copy. However, in C++03 requires that we check for the
3102 // presence of a suitable copy constructor:
3103 //
3104 // The constructor that would be used to make the copy shall
3105 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003106 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003107 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00003108 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003109
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003110 if (DerivedToBase)
3111 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3112 ValueKind);
3113 else if (ObjCConversion)
3114 Sequence.AddObjCObjectConversionStep(
3115 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003116
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003117 if (T1Quals != T2Quals)
3118 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003119 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003120 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003122 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003123
3124 // - has a class type (i.e., T2 is a class type), where T1 is not
3125 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003126 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3127 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003128 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003129 if (RefRelationship == Sema::Ref_Incompatible) {
3130 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3131 Kind, Initializer,
3132 /*AllowRValues=*/true,
3133 Sequence);
3134 if (ConvOvlResult)
3135 Sequence.SetOverloadFailure(
3136 InitializationSequence::FK_ReferenceInitOverloadFailed,
3137 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003138
Douglas Gregor20093b42009-12-09 23:02:17 +00003139 return;
3140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003141
Douglas Gregor20093b42009-12-09 23:02:17 +00003142 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3143 return;
3144 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003145
3146 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003147 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003148 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003149 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003150
Douglas Gregor20093b42009-12-09 23:02:17 +00003151 // Determine whether we are allowed to call explicit constructors or
3152 // explicit conversion operators.
3153 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003154
3155 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3156
John McCallf85e1932011-06-15 23:02:42 +00003157 ImplicitConversionSequence ICS
3158 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003159 /*SuppressUserConversions*/ false,
3160 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003161 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003162 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3163 /*AllowObjCWritebackConversion=*/false);
3164
3165 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003166 // FIXME: Use the conversion function set stored in ICS to turn
3167 // this into an overloading ambiguity diagnostic. However, we need
3168 // to keep that set as an OverloadCandidateSet rather than as some
3169 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003170 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3171 Sequence.SetOverloadFailure(
3172 InitializationSequence::FK_ReferenceInitOverloadFailed,
3173 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003174 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3175 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003176 else
3177 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003178 return;
John McCallf85e1932011-06-15 23:02:42 +00003179 } else {
3180 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003181 }
3182
3183 // [...] If T1 is reference-related to T2, cv1 must be the
3184 // same cv-qualification as, or greater cv-qualification
3185 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003186 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3187 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003188 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003189 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003190 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3191 return;
3192 }
3193
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003194 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003195 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003196 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003197 InitCategory.isLValue()) {
3198 Sequence.SetFailed(
3199 InitializationSequence::FK_RValueReferenceBindingToLValue);
3200 return;
3201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202
Douglas Gregor20093b42009-12-09 23:02:17 +00003203 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3204 return;
3205}
3206
3207/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003208/// (C++ [dcl.init.string], C99 6.7.8).
3209static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003210 const InitializedEntity &Entity,
3211 const InitializationKind &Kind,
3212 Expr *Initializer,
3213 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003214 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003215}
3216
Douglas Gregor20093b42009-12-09 23:02:17 +00003217/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3218/// enumerates the constructors of the initialized entity and performs overload
3219/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003221 const InitializedEntity &Entity,
3222 const InitializationKind &Kind,
3223 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003224 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003225 InitializationSequence &Sequence) {
Richard Trieu898267f2011-09-01 21:44:13 +00003226 // Check constructor arguments for self reference.
3227 if (DeclaratorDecl *DD = Entity.getDecl())
3228 // Parameters arguments are occassionially constructed with itself,
3229 // for instance, in recursive functions. Skip them.
3230 if (!isa<ParmVarDecl>(DD))
3231 for (unsigned i = 0; i < NumArgs; ++i)
3232 S.CheckSelfReference(DD, Args[i]);
3233
Douglas Gregor51c56d62009-12-14 20:49:26 +00003234 // Build the candidate set directly in the initialization sequence
3235 // structure, so that it will persist if we fail.
3236 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3237 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003238
Douglas Gregor51c56d62009-12-14 20:49:26 +00003239 // Determine whether we are allowed to call explicit constructors or
3240 // explicit conversion operators.
3241 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3242 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003243 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003244
3245 // The type we're constructing needs to be complete.
3246 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003247 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003248 return;
3249 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003250
Douglas Gregor51c56d62009-12-14 20:49:26 +00003251 // The type we're converting to is a class type. Enumerate its constructors
3252 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003253 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003254 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003255 CXXRecordDecl *DestRecordDecl
3256 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003257
Douglas Gregor51c56d62009-12-14 20:49:26 +00003258 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003259 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003260 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003261 NamedDecl *D = *Con;
3262 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003263 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003264
Douglas Gregor51c56d62009-12-14 20:49:26 +00003265 // Find the constructor (which may be a template).
3266 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003267 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003268 if (ConstructorTmpl)
3269 Constructor = cast<CXXConstructorDecl>(
3270 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003271 else {
John McCall9aa472c2010-03-19 07:35:19 +00003272 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003273
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003274 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003275 // suppress user-defined conversions on the arguments.
3276 // FIXME: Move constructors?
3277 if (Kind.getKind() == InitializationKind::IK_Copy &&
3278 Constructor->isCopyConstructor())
3279 SuppressUserConversions = true;
3280 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003281
Douglas Gregor51c56d62009-12-14 20:49:26 +00003282 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003283 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003284 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003285 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003286 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003287 Args, NumArgs, CandidateSet,
3288 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003289 else
John McCall9aa472c2010-03-19 07:35:19 +00003290 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003291 Args, NumArgs, CandidateSet,
3292 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003293 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003294 }
3295
Douglas Gregor51c56d62009-12-14 20:49:26 +00003296 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297
3298 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003299 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003300 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003301 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003302 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003304 Result);
3305 return;
3306 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003307
3308 // C++0x [dcl.init]p6:
3309 // If a program calls for the default initialization of an object
3310 // of a const-qualified type T, T shall be a class type with a
3311 // user-provided default constructor.
3312 if (Kind.getKind() == InitializationKind::IK_Default &&
3313 Entity.getType().isConstQualified() &&
3314 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3315 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3316 return;
3317 }
3318
Douglas Gregor51c56d62009-12-14 20:49:26 +00003319 // Add the constructor initialization step. Any cv-qualification conversion is
3320 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003321 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003322 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003323 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003324 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003325}
3326
Douglas Gregor71d17402009-12-15 00:01:57 +00003327/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003328static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003329 const InitializedEntity &Entity,
3330 const InitializationKind &Kind,
3331 InitializationSequence &Sequence) {
3332 // C++ [dcl.init]p5:
3333 //
3334 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003335 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003336
Douglas Gregor71d17402009-12-15 00:01:57 +00003337 // -- if T is an array type, then each element is value-initialized;
3338 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3339 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003340
Douglas Gregor71d17402009-12-15 00:01:57 +00003341 if (const RecordType *RT = T->getAs<RecordType>()) {
3342 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3343 // -- if T is a class type (clause 9) with a user-declared
3344 // constructor (12.1), then the default constructor for T is
3345 // called (and the initialization is ill-formed if T has no
3346 // accessible default constructor);
3347 //
3348 // FIXME: we really want to refer to a single subobject of the array,
3349 // but Entity doesn't have a way to capture that (yet).
3350 if (ClassDecl->hasUserDeclaredConstructor())
3351 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003352
Douglas Gregor16006c92009-12-16 18:50:27 +00003353 // -- if T is a (possibly cv-qualified) non-union class type
3354 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003355 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003356 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003357 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003358 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003359 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003361 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003362 }
3363 }
3364
Douglas Gregord6542d82009-12-22 15:35:07 +00003365 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003366}
3367
Douglas Gregor99a2e602009-12-16 01:38:02 +00003368/// \brief Attempt default initialization (C++ [dcl.init]p6).
3369static void TryDefaultInitialization(Sema &S,
3370 const InitializedEntity &Entity,
3371 const InitializationKind &Kind,
3372 InitializationSequence &Sequence) {
3373 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003374
Douglas Gregor99a2e602009-12-16 01:38:02 +00003375 // C++ [dcl.init]p6:
3376 // To default-initialize an object of type T means:
3377 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003378 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3379
Douglas Gregor99a2e602009-12-16 01:38:02 +00003380 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3381 // constructor for T is called (and the initialization is ill-formed if
3382 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003383 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003384 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3385 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003386 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003387
Douglas Gregor99a2e602009-12-16 01:38:02 +00003388 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003389
Douglas Gregor99a2e602009-12-16 01:38:02 +00003390 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003391 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003392 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003393 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003394 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003395 return;
3396 }
3397
3398 // If the destination type has a lifetime property, zero-initialize it.
3399 if (DestType.getQualifiers().hasObjCLifetime()) {
3400 Sequence.AddZeroInitializationStep(Entity.getType());
3401 return;
3402 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003403}
3404
Douglas Gregor20093b42009-12-09 23:02:17 +00003405/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3406/// which enumerates all conversion functions and performs overload resolution
3407/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003408static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003409 const InitializedEntity &Entity,
3410 const InitializationKind &Kind,
3411 Expr *Initializer,
3412 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003413 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003414 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3415 QualType SourceType = Initializer->getType();
3416 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3417 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003418
Douglas Gregor4a520a22009-12-14 17:27:33 +00003419 // Build the candidate set directly in the initialization sequence
3420 // structure, so that it will persist if we fail.
3421 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3422 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003423
Douglas Gregor4a520a22009-12-14 17:27:33 +00003424 // Determine whether we are allowed to call explicit constructors or
3425 // explicit conversion operators.
3426 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003427
Douglas Gregor4a520a22009-12-14 17:27:33 +00003428 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3429 // The type we're converting to is a class type. Enumerate its constructors
3430 // to see if there is a suitable conversion.
3431 CXXRecordDecl *DestRecordDecl
3432 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003433
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003434 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003435 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003436 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003437 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003438 Con != ConEnd; ++Con) {
3439 NamedDecl *D = *Con;
3440 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003441
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003442 // Find the constructor (which may be a template).
3443 CXXConstructorDecl *Constructor = 0;
3444 FunctionTemplateDecl *ConstructorTmpl
3445 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003446 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003447 Constructor = cast<CXXConstructorDecl>(
3448 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003449 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003450 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003451
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003452 if (!Constructor->isInvalidDecl() &&
3453 Constructor->isConvertingConstructor(AllowExplicit)) {
3454 if (ConstructorTmpl)
3455 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3456 /*ExplicitArgs*/ 0,
3457 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003458 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003459 else
3460 S.AddOverloadCandidate(Constructor, FoundDecl,
3461 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003462 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003463 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003464 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003465 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003466 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003467
3468 SourceLocation DeclLoc = Initializer->getLocStart();
3469
Douglas Gregor4a520a22009-12-14 17:27:33 +00003470 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3471 // The type we're converting from is a class type, enumerate its conversion
3472 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003473
Eli Friedman33c2da92009-12-20 22:12:03 +00003474 // We can only enumerate the conversion functions for a complete type; if
3475 // the type isn't complete, simply skip this step.
3476 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3477 CXXRecordDecl *SourceRecordDecl
3478 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003479
John McCalleec51cf2010-01-20 00:46:10 +00003480 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003481 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003482 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003483 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003484 I != E; ++I) {
3485 NamedDecl *D = *I;
3486 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3487 if (isa<UsingShadowDecl>(D))
3488 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003489
Eli Friedman33c2da92009-12-20 22:12:03 +00003490 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3491 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003492 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003493 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003494 else
John McCall32daa422010-03-31 01:36:47 +00003495 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003496
Eli Friedman33c2da92009-12-20 22:12:03 +00003497 if (AllowExplicit || !Conv->isExplicit()) {
3498 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003499 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003500 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003501 CandidateSet);
3502 else
John McCall9aa472c2010-03-19 07:35:19 +00003503 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003504 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003505 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003506 }
3507 }
3508 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003509
3510 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003511 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003512 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003513 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003514 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003515 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003516 Result);
3517 return;
3518 }
John McCall1d318332010-01-12 00:44:57 +00003519
Douglas Gregor4a520a22009-12-14 17:27:33 +00003520 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003521 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003522
Douglas Gregor4a520a22009-12-14 17:27:33 +00003523 if (isa<CXXConstructorDecl>(Function)) {
3524 // Add the user-defined conversion step. Any cv-qualification conversion is
3525 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003526 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003527 return;
3528 }
3529
3530 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003531 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003532 if (ConvType->getAs<RecordType>()) {
3533 // If we're converting to a class type, there may be an copy if
3534 // the resulting temporary object (possible to create an object of
3535 // a base class type). That copy is not a separate conversion, so
3536 // we just make a note of the actual destination type (possibly a
3537 // base class of the type returned by the conversion function) and
3538 // let the user-defined conversion step handle the conversion.
3539 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3540 return;
3541 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003542
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003543 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003544
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003545 // If the conversion following the call to the conversion function
3546 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003547 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3548 Best->FinalConversion.Third) {
3549 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003550 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003551 ICS.Standard = Best->FinalConversion;
3552 Sequence.AddConversionSequenceStep(ICS, DestType);
3553 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003554}
3555
John McCallf85e1932011-06-15 23:02:42 +00003556/// The non-zero enum values here are indexes into diagnostic alternatives.
3557enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3558
3559/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003560static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3561 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003562 // Skip parens.
3563 e = e->IgnoreParens();
3564
3565 // Skip address-of nodes.
3566 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3567 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003568 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003569
3570 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003571 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3572 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003573 case CK_Dependent:
3574 case CK_BitCast:
3575 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003576 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003577 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003578
3579 case CK_ArrayToPointerDecay:
3580 return IIK_nonscalar;
3581
3582 case CK_NullToPointer:
3583 return IIK_okay;
3584
3585 default:
3586 break;
3587 }
3588
3589 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003590 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3591 if (!isAddressOf) return IIK_nonlocal;
3592
3593 VarDecl *var;
3594 if (isa<DeclRefExpr>(e)) {
3595 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3596 if (!var) return IIK_nonlocal;
3597 } else {
3598 var = cast<BlockDeclRefExpr>(e)->getDecl();
3599 }
3600
3601 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003602
3603 // If we have a conditional operator, check both sides.
3604 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003605 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003606 return iik;
3607
John McCallc03fa492011-06-27 23:59:58 +00003608 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003609
3610 // These are never scalar.
3611 } else if (isa<ArraySubscriptExpr>(e)) {
3612 return IIK_nonscalar;
3613
3614 // Otherwise, it needs to be a null pointer constant.
3615 } else {
3616 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3617 ? IIK_okay : IIK_nonlocal);
3618 }
3619
3620 return IIK_nonlocal;
3621}
3622
3623/// Check whether the given expression is a valid operand for an
3624/// indirect copy/restore.
3625static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3626 assert(src->isRValue());
3627
John McCallc03fa492011-06-27 23:59:58 +00003628 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003629 if (iik == IIK_okay) return;
3630
3631 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3632 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3633 << src->getSourceRange();
3634}
3635
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003636/// \brief Determine whether we have compatible array types for the
3637/// purposes of GNU by-copy array initialization.
3638static bool hasCompatibleArrayTypes(ASTContext &Context,
3639 const ArrayType *Dest,
3640 const ArrayType *Source) {
3641 // If the source and destination array types are equivalent, we're
3642 // done.
3643 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3644 return true;
3645
3646 // Make sure that the element types are the same.
3647 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3648 return false;
3649
3650 // The only mismatch we allow is when the destination is an
3651 // incomplete array type and the source is a constant array type.
3652 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3653}
3654
John McCallf85e1932011-06-15 23:02:42 +00003655static bool tryObjCWritebackConversion(Sema &S,
3656 InitializationSequence &Sequence,
3657 const InitializedEntity &Entity,
3658 Expr *Initializer) {
3659 bool ArrayDecay = false;
3660 QualType ArgType = Initializer->getType();
3661 QualType ArgPointee;
3662 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3663 ArrayDecay = true;
3664 ArgPointee = ArgArrayType->getElementType();
3665 ArgType = S.Context.getPointerType(ArgPointee);
3666 }
3667
3668 // Handle write-back conversion.
3669 QualType ConvertedArgType;
3670 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3671 ConvertedArgType))
3672 return false;
3673
3674 // We should copy unless we're passing to an argument explicitly
3675 // marked 'out'.
3676 bool ShouldCopy = true;
3677 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3678 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3679
3680 // Do we need an lvalue conversion?
3681 if (ArrayDecay || Initializer->isGLValue()) {
3682 ImplicitConversionSequence ICS;
3683 ICS.setStandard();
3684 ICS.Standard.setAsIdentityConversion();
3685
3686 QualType ResultType;
3687 if (ArrayDecay) {
3688 ICS.Standard.First = ICK_Array_To_Pointer;
3689 ResultType = S.Context.getPointerType(ArgPointee);
3690 } else {
3691 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3692 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3693 }
3694
3695 Sequence.AddConversionSequenceStep(ICS, ResultType);
3696 }
3697
3698 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3699 return true;
3700}
3701
Douglas Gregor20093b42009-12-09 23:02:17 +00003702InitializationSequence::InitializationSequence(Sema &S,
3703 const InitializedEntity &Entity,
3704 const InitializationKind &Kind,
3705 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003706 unsigned NumArgs)
3707 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003708 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003709
Douglas Gregor20093b42009-12-09 23:02:17 +00003710 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003711 // The semantics of initializers are as follows. The destination type is
3712 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003713 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003714 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003715 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003716 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003717
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003718 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003719 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3720 SequenceKind = DependentSequence;
3721 return;
3722 }
3723
Sebastian Redl7491c492011-06-05 13:59:11 +00003724 // Almost everything is a normal sequence.
3725 setSequenceKind(NormalSequence);
3726
John McCall241d5582010-12-07 22:54:16 +00003727 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003728 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3729 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3730 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003731 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003732 return;
3733 }
3734 Args[I] = Result.take();
3735 }
John McCall241d5582010-12-07 22:54:16 +00003736
Douglas Gregor20093b42009-12-09 23:02:17 +00003737 QualType SourceType;
3738 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003739 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003740 Initializer = Args[0];
3741 if (!isa<InitListExpr>(Initializer))
3742 SourceType = Initializer->getType();
3743 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003744
3745 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003746 // list-initialized (8.5.4).
3747 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003748 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003749 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003751
Douglas Gregor20093b42009-12-09 23:02:17 +00003752 // - If the destination type is a reference type, see 8.5.3.
3753 if (DestType->isReferenceType()) {
3754 // C++0x [dcl.init.ref]p1:
3755 // A variable declared to be a T& or T&&, that is, "reference to type T"
3756 // (8.3.2), shall be initialized by an object, or function, of type T or
3757 // by an object that can be converted into a T.
3758 // (Therefore, multiple arguments are not permitted.)
3759 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003760 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003761 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003762 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003763 return;
3764 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765
Douglas Gregor20093b42009-12-09 23:02:17 +00003766 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003767 if (Kind.getKind() == InitializationKind::IK_Value ||
3768 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003769 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003770 return;
3771 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003772
Douglas Gregor99a2e602009-12-16 01:38:02 +00003773 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003774 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003775 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003776 return;
3777 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003778
John McCallce6c9b72011-02-21 07:22:22 +00003779 // - If the destination type is an array of characters, an array of
3780 // char16_t, an array of char32_t, or an array of wchar_t, and the
3781 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003782 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003783 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003784 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3785 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003786 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003787 return;
3788 }
3789
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003790 // Note: as an GNU C extension, we allow initialization of an
3791 // array from a compound literal that creates an array of the same
3792 // type, so long as the initializer has no side effects.
3793 if (!S.getLangOptions().CPlusPlus && Initializer &&
3794 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3795 Initializer->getType()->isArrayType()) {
3796 const ArrayType *SourceAT
3797 = Context.getAsArrayType(Initializer->getType());
3798 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003799 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003800 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003801 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003802 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003803 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003804 }
3805 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003806 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003807 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003808 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003809
Douglas Gregor20093b42009-12-09 23:02:17 +00003810 return;
3811 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003812
John McCallf85e1932011-06-15 23:02:42 +00003813 // Determine whether we should consider writeback conversions for
3814 // Objective-C ARC.
3815 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3816 Entity.getKind() == InitializedEntity::EK_Parameter;
3817
3818 // We're at the end of the line for C: it's either a write-back conversion
3819 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003820 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003821 // If allowed, check whether this is an Objective-C writeback conversion.
3822 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003823 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003824 return;
3825 }
3826
3827 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003828 AddCAssignmentStep(DestType);
3829 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003830 return;
3831 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003832
John McCallf85e1932011-06-15 23:02:42 +00003833 assert(S.getLangOptions().CPlusPlus);
3834
Douglas Gregor20093b42009-12-09 23:02:17 +00003835 // - If the destination type is a (possibly cv-qualified) class type:
3836 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003837 // - If the initialization is direct-initialization, or if it is
3838 // copy-initialization where the cv-unqualified version of the
3839 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003840 // class of the destination, constructors are considered. [...]
3841 if (Kind.getKind() == InitializationKind::IK_Direct ||
3842 (Kind.getKind() == InitializationKind::IK_Copy &&
3843 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3844 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003845 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003846 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003847 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003848 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003849 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003850 // used) to a derived class thereof are enumerated as described in
3851 // 13.3.1.4, and the best one is chosen through overload resolution
3852 // (13.3).
3853 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003854 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003855 return;
3856 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003857
Douglas Gregor99a2e602009-12-16 01:38:02 +00003858 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003859 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003860 return;
3861 }
3862 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003863
3864 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003865 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003866 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003867 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3868 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003869 return;
3870 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003871
Douglas Gregor20093b42009-12-09 23:02:17 +00003872 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003873 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003874 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003875 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003876 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003877
3878 ImplicitConversionSequence ICS
3879 = S.TryImplicitConversion(Initializer, Entity.getType(),
3880 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003881 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003882 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003883 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3884 allowObjCWritebackConversion);
3885
3886 if (ICS.isStandard() &&
3887 ICS.Standard.Second == ICK_Writeback_Conversion) {
3888 // Objective-C ARC writeback conversion.
3889
3890 // We should copy unless we're passing to an argument explicitly
3891 // marked 'out'.
3892 bool ShouldCopy = true;
3893 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3894 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3895
3896 // If there was an lvalue adjustment, add it as a separate conversion.
3897 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3898 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3899 ImplicitConversionSequence LvalueICS;
3900 LvalueICS.setStandard();
3901 LvalueICS.Standard.setAsIdentityConversion();
3902 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3903 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003904 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003905 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003906
3907 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003908 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003909 DeclAccessPair dap;
3910 if (Initializer->getType() == Context.OverloadTy &&
3911 !S.ResolveAddressOfOverloadedFunction(Initializer
3912 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003913 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003914 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003915 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003916 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003917 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003918
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003919 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003920 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003921}
3922
3923InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003924 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003925 StepEnd = Steps.end();
3926 Step != StepEnd; ++Step)
3927 Step->Destroy();
3928}
3929
3930//===----------------------------------------------------------------------===//
3931// Perform initialization
3932//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003933static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003934getAssignmentAction(const InitializedEntity &Entity) {
3935 switch(Entity.getKind()) {
3936 case InitializedEntity::EK_Variable:
3937 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003938 case InitializedEntity::EK_Exception:
3939 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003940 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003941 return Sema::AA_Initializing;
3942
3943 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003944 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003945 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3946 return Sema::AA_Sending;
3947
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003948 return Sema::AA_Passing;
3949
3950 case InitializedEntity::EK_Result:
3951 return Sema::AA_Returning;
3952
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003953 case InitializedEntity::EK_Temporary:
3954 // FIXME: Can we tell apart casting vs. converting?
3955 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003956
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003957 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003958 case InitializedEntity::EK_ArrayElement:
3959 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00003960 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003961 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003962 return Sema::AA_Initializing;
3963 }
3964
3965 return Sema::AA_Converting;
3966}
3967
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003968/// \brief Whether we should binding a created object as a temporary when
3969/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003970static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003971 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003972 case InitializedEntity::EK_ArrayElement:
3973 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003974 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003975 case InitializedEntity::EK_New:
3976 case InitializedEntity::EK_Variable:
3977 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003978 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003979 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00003980 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003981 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003982 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003983 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003984
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003985 case InitializedEntity::EK_Parameter:
3986 case InitializedEntity::EK_Temporary:
3987 return true;
3988 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003989
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003990 llvm_unreachable("missed an InitializedEntity kind?");
3991}
3992
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003993/// \brief Whether the given entity, when initialized with an object
3994/// created for that initialization, requires destruction.
3995static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3996 switch (Entity.getKind()) {
3997 case InitializedEntity::EK_Member:
3998 case InitializedEntity::EK_Result:
3999 case InitializedEntity::EK_New:
4000 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004001 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004002 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004003 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004004 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004005 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004006
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004007 case InitializedEntity::EK_Variable:
4008 case InitializedEntity::EK_Parameter:
4009 case InitializedEntity::EK_Temporary:
4010 case InitializedEntity::EK_ArrayElement:
4011 case InitializedEntity::EK_Exception:
4012 return true;
4013 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004014
4015 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004016}
4017
Douglas Gregor523d46a2010-04-18 07:40:54 +00004018/// \brief Make a (potentially elidable) temporary copy of the object
4019/// provided by the given initializer by calling the appropriate copy
4020/// constructor.
4021///
4022/// \param S The Sema object used for type-checking.
4023///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004024/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004025/// the type of the initializer expression or a superclass thereof.
4026///
4027/// \param Enter The entity being initialized.
4028///
4029/// \param CurInit The initializer expression.
4030///
4031/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4032/// is permitted in C++03 (but not C++0x) when binding a reference to
4033/// an rvalue.
4034///
4035/// \returns An expression that copies the initializer expression into
4036/// a temporary object, or an error expression if a copy could not be
4037/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004038static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004039 QualType T,
4040 const InitializedEntity &Entity,
4041 ExprResult CurInit,
4042 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004043 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004044 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004045 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004046 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004047 Class = cast<CXXRecordDecl>(Record->getDecl());
4048 if (!Class)
4049 return move(CurInit);
4050
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004051 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004052 // When certain criteria are met, an implementation is allowed to
4053 // omit the copy/move construction of a class object, even if the
4054 // copy/move constructor and/or destructor for the object have
4055 // side effects. [...]
4056 // - when a temporary class object that has not been bound to a
4057 // reference (12.2) would be copied/moved to a class object
4058 // with the same cv-unqualified type, the copy/move operation
4059 // can be omitted by constructing the temporary object
4060 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004061 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004062 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004063 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004065 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004066 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004067 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004068 switch (Entity.getKind()) {
4069 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004070 Loc = Entity.getReturnLoc();
4071 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004072
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004073 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004074 Loc = Entity.getThrowLoc();
4075 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004076
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004077 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004078 Loc = Entity.getDecl()->getLocation();
4079 break;
4080
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004081 case InitializedEntity::EK_ArrayElement:
4082 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004083 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004084 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00004085 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004086 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004087 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004088 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004089 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004090 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00004091 Loc = CurInitExpr->getLocStart();
4092 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004093 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004094
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004095 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004096 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4097 return move(CurInit);
4098
Douglas Gregorcc15f012011-01-21 19:38:21 +00004099 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004100 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00004101 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00004102 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004103 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00004104 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004105 // C++0x [dcl.init]p16, second bullet to class types, this
4106 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00004107 CXXConstructorDecl *Constructor = 0;
4108
4109 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00004110 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00004111 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00004112 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004113 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00004114 continue;
4115
4116 DeclAccessPair FoundDecl
4117 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4118 S.AddOverloadCandidate(Constructor, FoundDecl,
4119 &CurInitExpr, 1, CandidateSet);
4120 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004121 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00004122
4123 // Handle constructor templates.
4124 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4125 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004126 continue;
John McCall9aa472c2010-03-19 07:35:19 +00004127
Douglas Gregor6493cc52010-11-08 17:16:59 +00004128 Constructor = cast<CXXConstructorDecl>(
4129 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004130 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00004131 continue;
4132
4133 // FIXME: Do we need to limit this to copy-constructor-like
4134 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00004135 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00004136 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4137 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4138 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00004139 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004140
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004141 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004142 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004143 case OR_Success:
4144 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004145
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004146 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004147 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4148 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4149 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004150 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004151 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004152 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004153 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004154 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004155 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004156
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004157 case OR_Ambiguous:
4158 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004159 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004160 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004161 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004162 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004164 case OR_Deleted:
4165 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004166 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004167 << CurInitExpr->getSourceRange();
4168 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004169 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004170 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004171 }
4172
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004173 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004174 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004175 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004176
Anders Carlsson9a68a672010-04-21 18:47:17 +00004177 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004178 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004179
4180 if (IsExtraneousCopy) {
4181 // If this is a totally extraneous copy for C++03 reference
4182 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004183 // expression. We don't generate an (elided) copy operation here
4184 // because doing so would require us to pass down a flag to avoid
4185 // infinite recursion, where each step adds another extraneous,
4186 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004187
Douglas Gregor2559a702010-04-18 07:57:34 +00004188 // Instantiate the default arguments of any extra parameters in
4189 // the selected copy constructor, as if we were going to create a
4190 // proper call to the copy constructor.
4191 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4192 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4193 if (S.RequireCompleteType(Loc, Parm->getType(),
4194 S.PDiag(diag::err_call_incomplete_argument)))
4195 break;
4196
4197 // Build the default argument expression; we don't actually care
4198 // if this succeeds or not, because this routine will complain
4199 // if there was a problem.
4200 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4201 }
4202
Douglas Gregor523d46a2010-04-18 07:40:54 +00004203 return S.Owned(CurInitExpr);
4204 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004205
Chandler Carruth25ca4212011-02-25 19:41:05 +00004206 S.MarkDeclarationReferenced(Loc, Constructor);
4207
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004208 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004209 // constructor call (we might have derived-to-base conversions, or
4210 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004211 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004212 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004213 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004214
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004215 // Actually perform the constructor call.
4216 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004217 move_arg(ConstructorArgs),
4218 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004219 CXXConstructExpr::CK_Complete,
4220 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004221
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004222 // If we're supposed to bind temporaries, do so.
4223 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4224 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4225 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004226}
Douglas Gregor20093b42009-12-09 23:02:17 +00004227
Douglas Gregora41a8c52010-04-22 00:20:18 +00004228void InitializationSequence::PrintInitLocationNote(Sema &S,
4229 const InitializedEntity &Entity) {
4230 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4231 if (Entity.getDecl()->getLocation().isInvalid())
4232 return;
4233
4234 if (Entity.getDecl()->getDeclName())
4235 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4236 << Entity.getDecl()->getDeclName();
4237 else
4238 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4239 }
4240}
4241
Sebastian Redl3b802322011-07-14 19:07:55 +00004242static bool isReferenceBinding(const InitializationSequence::Step &s) {
4243 return s.Kind == InitializationSequence::SK_BindReference ||
4244 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4245}
4246
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004247ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004248InitializationSequence::Perform(Sema &S,
4249 const InitializedEntity &Entity,
4250 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004251 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004252 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004253 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004254 unsigned NumArgs = Args.size();
4255 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004256 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004257 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258
Sebastian Redl7491c492011-06-05 13:59:11 +00004259 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004260 // If the declaration is a non-dependent, incomplete array type
4261 // that has an initializer, then its type will be completed once
4262 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004263 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004264 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004265 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004266 if (const IncompleteArrayType *ArrayT
4267 = S.Context.getAsIncompleteArrayType(DeclType)) {
4268 // FIXME: We don't currently have the ability to accurately
4269 // compute the length of an initializer list without
4270 // performing full type-checking of the initializer list
4271 // (since we have to determine where braces are implicitly
4272 // introduced and such). So, we fall back to making the array
4273 // type a dependently-sized array type with no specified
4274 // bound.
4275 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4276 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004277
Douglas Gregord87b61f2009-12-10 17:56:55 +00004278 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004279 if (DeclaratorDecl *DD = Entity.getDecl()) {
4280 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4281 TypeLoc TL = TInfo->getTypeLoc();
4282 if (IncompleteArrayTypeLoc *ArrayLoc
4283 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4284 Brackets = ArrayLoc->getBracketsRange();
4285 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004286 }
4287
4288 *ResultType
4289 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4290 /*NumElts=*/0,
4291 ArrayT->getSizeModifier(),
4292 ArrayT->getIndexTypeCVRQualifiers(),
4293 Brackets);
4294 }
4295
4296 }
4297 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004298 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4299 Kind.isExplicitCast());
4300 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004301 }
4302
Sebastian Redl7491c492011-06-05 13:59:11 +00004303 // No steps means no initialization.
4304 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004305 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306
Douglas Gregord6542d82009-12-22 15:35:07 +00004307 QualType DestType = Entity.getType().getNonReferenceType();
4308 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004309 // the same as Entity.getDecl()->getType() in cases involving type merging,
4310 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004311 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004312 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004313 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004314
John McCall60d7b3a2010-08-24 06:29:42 +00004315 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004316
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004317 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004318 // grab the only argument out the Args and place it into the "current"
4319 // initializer.
4320 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004321 case SK_ResolveAddressOfOverloadedFunction:
4322 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004323 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004324 case SK_CastDerivedToBaseLValue:
4325 case SK_BindReference:
4326 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004327 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004328 case SK_UserConversion:
4329 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004330 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004331 case SK_QualificationConversionRValue:
4332 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004333 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004334 case SK_ListInitialization:
4335 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004336 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004337 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004338 case SK_ArrayInit:
4339 case SK_PassByIndirectCopyRestore:
4340 case SK_PassByIndirectRestore:
4341 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004342 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004343 CurInit = Args.get()[0];
4344 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004345
4346 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004347 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4348 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4349 if (CurInit.isInvalid())
4350 return ExprError();
4351 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004352 break;
John McCallf6a16482010-12-04 03:47:34 +00004353 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004354
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004355 case SK_ConstructorInitialization:
4356 case SK_ZeroInitialization:
4357 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004358 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004359
4360 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004361 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004362 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004363 for (step_iterator Step = step_begin(), StepEnd = step_end();
4364 Step != StepEnd; ++Step) {
4365 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004366 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004367
John Wiegley429bb272011-04-08 18:41:53 +00004368 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004369
Douglas Gregor20093b42009-12-09 23:02:17 +00004370 switch (Step->Kind) {
4371 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004372 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004373 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004374 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004375 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004376 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004377 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004378 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004379 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004380
Douglas Gregor20093b42009-12-09 23:02:17 +00004381 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004382 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004383 case SK_CastDerivedToBaseLValue: {
4384 // We have a derived-to-base cast that produces either an rvalue or an
4385 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004386
John McCallf871d0c2010-08-07 06:22:56 +00004387 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004388
Douglas Gregor20093b42009-12-09 23:02:17 +00004389 // Casts to inaccessible base classes are allowed with C-style casts.
4390 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4391 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004392 CurInit.get()->getLocStart(),
4393 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004394 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004395 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004396
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004397 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4398 QualType T = SourceType;
4399 if (const PointerType *Pointer = T->getAs<PointerType>())
4400 T = Pointer->getPointeeType();
4401 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004402 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004403 cast<CXXRecordDecl>(RecordTy->getDecl()));
4404 }
4405
John McCall5baba9d2010-08-25 10:28:54 +00004406 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004407 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004408 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004409 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004410 VK_XValue :
4411 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004412 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4413 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004414 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004415 CurInit.get(),
4416 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004417 break;
4418 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004419
Douglas Gregor20093b42009-12-09 23:02:17 +00004420 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004421 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004422 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4423 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004424 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004425 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004426 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004427 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004428 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004429 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004430
John Wiegley429bb272011-04-08 18:41:53 +00004431 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004432 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004433 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4434 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004435 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004436 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004437 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004438 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439
Douglas Gregor20093b42009-12-09 23:02:17 +00004440 // Reference binding does not have any corresponding ASTs.
4441
4442 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004443 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004444 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004445
Douglas Gregor20093b42009-12-09 23:02:17 +00004446 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004447
Douglas Gregor20093b42009-12-09 23:02:17 +00004448 case SK_BindReferenceToTemporary:
4449 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004450 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004451 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004452
Douglas Gregor03e80032011-06-21 17:03:29 +00004453 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004454 CurInit = new (S.Context) MaterializeTemporaryExpr(
4455 Entity.getType().getNonReferenceType(),
4456 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004457 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004458
4459 // If we're binding to an Objective-C object that has lifetime, we
4460 // need cleanups.
4461 if (S.getLangOptions().ObjCAutoRefCount &&
4462 CurInit.get()->getType()->isObjCLifetimeType())
4463 S.ExprNeedsCleanups = true;
4464
Douglas Gregor20093b42009-12-09 23:02:17 +00004465 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004466
Douglas Gregor523d46a2010-04-18 07:40:54 +00004467 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004468 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004469 /*IsExtraneousCopy=*/true);
4470 break;
4471
Douglas Gregor20093b42009-12-09 23:02:17 +00004472 case SK_UserConversion: {
4473 // We have a user-defined conversion that invokes either a constructor
4474 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004475 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004476 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004477 FunctionDecl *Fn = Step->Function.Function;
4478 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004479 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004480 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004481 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004482 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004483 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004484 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004485 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004486
Douglas Gregor20093b42009-12-09 23:02:17 +00004487 // Determine the arguments required to actually perform the constructor
4488 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004489 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004490 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004491 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004492 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004493 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004494
Douglas Gregor20093b42009-12-09 23:02:17 +00004495 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004496 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004497 move_arg(ConstructorArgs),
4498 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004499 CXXConstructExpr::CK_Complete,
4500 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004501 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004502 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004503
Anders Carlsson9a68a672010-04-21 18:47:17 +00004504 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004505 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004506 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004507
John McCall2de56d12010-08-25 11:45:40 +00004508 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004509 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4510 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4511 S.IsDerivedFrom(SourceType, Class))
4512 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004513
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004514 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004515 } else {
4516 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004517 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004518 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004519 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004520 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004521 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004522
4523 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004524 // derived-to-base conversion? I believe the answer is "no", because
4525 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004526 ExprResult CurInitExprRes =
4527 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4528 FoundFn, Conversion);
4529 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004530 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004531 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004532
Douglas Gregor20093b42009-12-09 23:02:17 +00004533 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004534 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004535 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004536 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004537
John McCall2de56d12010-08-25 11:45:40 +00004538 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004539
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004540 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004541 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004542
Sebastian Redl3b802322011-07-14 19:07:55 +00004543 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004544 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004545 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004546 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004547 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004548 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004549 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004550 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004551 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004552 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004553 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4554 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004555 }
4556 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004557
Sebastian Redl906082e2010-07-20 04:20:21 +00004558 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004559 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004560 CurInit.get()->getType(),
4561 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004562 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004563
Douglas Gregor2f599792010-04-02 18:24:57 +00004564 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004565 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4566 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004567
Douglas Gregor20093b42009-12-09 23:02:17 +00004568 break;
4569 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004570
Douglas Gregor20093b42009-12-09 23:02:17 +00004571 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004572 case SK_QualificationConversionXValue:
4573 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004574 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004575 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004576 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004577 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004578 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004579 VK_XValue :
4580 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004581 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004582 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004583 }
4584
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004585 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004586 Sema::CheckedConversionKind CCK
4587 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4588 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4589 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4590 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004591 ExprResult CurInitExprRes =
4592 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004593 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004594 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004595 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004596 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004597 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004598 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004599
Douglas Gregord87b61f2009-12-10 17:56:55 +00004600 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004601 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004602 QualType Ty = Step->Type;
Sebastian Redl14b0c192011-09-24 17:48:00 +00004603 InitListChecker PerformInitList(S, Entity, InitList,
4604 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false);
4605 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00004606 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004607
4608 CurInit.release();
Sebastian Redl14b0c192011-09-24 17:48:00 +00004609 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004610 break;
4611 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004612
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004613 case SK_ListConstructorCall:
4614 assert(false && "List constructor calls not yet supported.");
4615
Douglas Gregor51c56d62009-12-14 20:49:26 +00004616 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004617 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004618 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004619 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004620
Douglas Gregor51c56d62009-12-14 20:49:26 +00004621 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004622 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004623 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4624 ? Kind.getEqualLoc()
4625 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004626
4627 if (Kind.getKind() == InitializationKind::IK_Default) {
4628 // Force even a trivial, implicit default constructor to be
4629 // semantically checked. We do this explicitly because we don't build
4630 // the definition for completely trivial constructors.
4631 CXXRecordDecl *ClassDecl = Constructor->getParent();
4632 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004633 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004634 ClassDecl->hasTrivialDefaultConstructor() &&
4635 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004636 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4637 }
4638
Douglas Gregor51c56d62009-12-14 20:49:26 +00004639 // Determine the arguments required to actually perform the constructor
4640 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004641 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004642 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004643 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004644
4645
Douglas Gregor91be6f52010-03-02 17:18:33 +00004646 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004647 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004648 (Kind.getKind() == InitializationKind::IK_Direct ||
4649 Kind.getKind() == InitializationKind::IK_Value)) {
4650 // An explicitly-constructed temporary, e.g., X(1, 2).
4651 unsigned NumExprs = ConstructorArgs.size();
4652 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004653 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004654 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004655
Douglas Gregorab6677e2010-09-08 00:15:04 +00004656 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4657 if (!TSInfo)
4658 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659
Douglas Gregor91be6f52010-03-02 17:18:33 +00004660 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4661 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004662 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004663 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004664 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004665 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004666 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004667 } else {
4668 CXXConstructExpr::ConstructionKind ConstructKind =
4669 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004670
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004671 if (Entity.getKind() == InitializedEntity::EK_Base) {
4672 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004673 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004674 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004675 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004676 ConstructKind = CXXConstructExpr::CK_Delegating;
4677 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004678
Chandler Carruth428edaf2010-10-25 08:47:36 +00004679 // Only get the parenthesis range if it is a direct construction.
4680 SourceRange parenRange =
4681 Kind.getKind() == InitializationKind::IK_Direct ?
4682 Kind.getParenRange() : SourceRange();
4683
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004684 // If the entity allows NRVO, mark the construction as elidable
4685 // unconditionally.
4686 if (Entity.allowsNRVO())
4687 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4688 Constructor, /*Elidable=*/true,
4689 move_arg(ConstructorArgs),
4690 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004691 ConstructKind,
4692 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004693 else
4694 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004695 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004696 move_arg(ConstructorArgs),
4697 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004698 ConstructKind,
4699 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004700 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004701 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004702 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004703
4704 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004705 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004706 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004707 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004708
Douglas Gregor2f599792010-04-02 18:24:57 +00004709 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004710 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004711
Douglas Gregor51c56d62009-12-14 20:49:26 +00004712 break;
4713 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004714
Douglas Gregor71d17402009-12-15 00:01:57 +00004715 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004716 step_iterator NextStep = Step;
4717 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004718 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004719 NextStep->Kind == SK_ConstructorInitialization) {
4720 // The need for zero-initialization is recorded directly into
4721 // the call to the object's constructor within the next step.
4722 ConstructorInitRequiresZeroInit = true;
4723 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4724 S.getLangOptions().CPlusPlus &&
4725 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004726 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4727 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004729 Kind.getRange().getBegin());
4730
4731 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4732 TSInfo->getType().getNonLValueExprType(S.Context),
4733 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004734 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004735 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004736 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004737 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004738 break;
4739 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004740
4741 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004742 QualType SourceType = CurInit.get()->getType();
4743 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004744 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004745 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4746 if (Result.isInvalid())
4747 return ExprError();
4748 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004749
4750 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004751 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004752 if (ConvTy != Sema::Compatible &&
4753 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004754 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004755 == Sema::Compatible)
4756 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004757 if (CurInitExprRes.isInvalid())
4758 return ExprError();
4759 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004760
Douglas Gregora41a8c52010-04-22 00:20:18 +00004761 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004762 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4763 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004764 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004765 getAssignmentAction(Entity),
4766 &Complained)) {
4767 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004768 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004769 } else if (Complained)
4770 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004771 break;
4772 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004773
4774 case SK_StringInit: {
4775 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004776 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004777 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004778 break;
4779 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004780
4781 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004782 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004783 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004784 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004785 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004786
4787 case SK_ArrayInit:
4788 // Okay: we checked everything before creating this step. Note that
4789 // this is a GNU extension.
4790 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004791 << Step->Type << CurInit.get()->getType()
4792 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004793
4794 // If the destination type is an incomplete array type, update the
4795 // type accordingly.
4796 if (ResultType) {
4797 if (const IncompleteArrayType *IncompleteDest
4798 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4799 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004800 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004801 *ResultType = S.Context.getConstantArrayType(
4802 IncompleteDest->getElementType(),
4803 ConstantSource->getSize(),
4804 ArrayType::Normal, 0);
4805 }
4806 }
4807 }
John McCallf85e1932011-06-15 23:02:42 +00004808 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004809
John McCallf85e1932011-06-15 23:02:42 +00004810 case SK_PassByIndirectCopyRestore:
4811 case SK_PassByIndirectRestore:
4812 checkIndirectCopyRestoreSource(S, CurInit.get());
4813 CurInit = S.Owned(new (S.Context)
4814 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4815 Step->Kind == SK_PassByIndirectCopyRestore));
4816 break;
4817
4818 case SK_ProduceObjCObject:
4819 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00004820 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00004821 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004822 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004823 }
4824 }
John McCall15d7d122010-11-11 03:21:53 +00004825
4826 // Diagnose non-fatal problems with the completed initialization.
4827 if (Entity.getKind() == InitializedEntity::EK_Member &&
4828 cast<FieldDecl>(Entity.getDecl())->isBitField())
4829 S.CheckBitFieldInitialization(Kind.getLocation(),
4830 cast<FieldDecl>(Entity.getDecl()),
4831 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004832
Douglas Gregor20093b42009-12-09 23:02:17 +00004833 return move(CurInit);
4834}
4835
4836//===----------------------------------------------------------------------===//
4837// Diagnose initialization failures
4838//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004839bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004840 const InitializedEntity &Entity,
4841 const InitializationKind &Kind,
4842 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004843 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004844 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004845
Douglas Gregord6542d82009-12-22 15:35:07 +00004846 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004847 switch (Failure) {
4848 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004849 // FIXME: Customize for the initialized entity?
4850 if (NumArgs == 0)
4851 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4852 << DestType.getNonReferenceType();
4853 else // FIXME: diagnostic below could be better!
4854 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4855 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004856 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004857
Douglas Gregor20093b42009-12-09 23:02:17 +00004858 case FK_ArrayNeedsInitList:
4859 case FK_ArrayNeedsInitListOrStringLiteral:
4860 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4861 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4862 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004863
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004864 case FK_ArrayTypeMismatch:
4865 case FK_NonConstantArrayInit:
4866 S.Diag(Kind.getLocation(),
4867 (Failure == FK_ArrayTypeMismatch
4868 ? diag::err_array_init_different_type
4869 : diag::err_array_init_non_constant_array))
4870 << DestType.getNonReferenceType()
4871 << Args[0]->getType()
4872 << Args[0]->getSourceRange();
4873 break;
4874
John McCall6bb80172010-03-30 21:47:33 +00004875 case FK_AddressOfOverloadFailed: {
4876 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004877 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004878 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004879 true,
4880 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004881 break;
John McCall6bb80172010-03-30 21:47:33 +00004882 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004883
Douglas Gregor20093b42009-12-09 23:02:17 +00004884 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004885 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004886 switch (FailedOverloadResult) {
4887 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004888 if (Failure == FK_UserConversionOverloadFailed)
4889 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4890 << Args[0]->getType() << DestType
4891 << Args[0]->getSourceRange();
4892 else
4893 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4894 << DestType << Args[0]->getType()
4895 << Args[0]->getSourceRange();
4896
John McCall120d63c2010-08-24 20:38:10 +00004897 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004898 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004899
Douglas Gregor20093b42009-12-09 23:02:17 +00004900 case OR_No_Viable_Function:
4901 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4902 << Args[0]->getType() << DestType.getNonReferenceType()
4903 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004904 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004905 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004906
Douglas Gregor20093b42009-12-09 23:02:17 +00004907 case OR_Deleted: {
4908 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4909 << Args[0]->getType() << DestType.getNonReferenceType()
4910 << Args[0]->getSourceRange();
4911 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004912 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004913 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4914 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004915 if (Ovl == OR_Deleted) {
4916 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004917 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004918 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004919 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004920 }
4921 break;
4922 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004923
Douglas Gregor20093b42009-12-09 23:02:17 +00004924 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004925 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004926 break;
4927 }
4928 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004929
Douglas Gregor20093b42009-12-09 23:02:17 +00004930 case FK_NonConstLValueReferenceBindingToTemporary:
4931 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004932 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004933 Failure == FK_NonConstLValueReferenceBindingToTemporary
4934 ? diag::err_lvalue_reference_bind_to_temporary
4935 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004936 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004937 << DestType.getNonReferenceType()
4938 << Args[0]->getType()
4939 << Args[0]->getSourceRange();
4940 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004941
Douglas Gregor20093b42009-12-09 23:02:17 +00004942 case FK_RValueReferenceBindingToLValue:
4943 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004944 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004945 << Args[0]->getSourceRange();
4946 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004947
Douglas Gregor20093b42009-12-09 23:02:17 +00004948 case FK_ReferenceInitDropsQualifiers:
4949 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4950 << DestType.getNonReferenceType()
4951 << Args[0]->getType()
4952 << Args[0]->getSourceRange();
4953 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004954
Douglas Gregor20093b42009-12-09 23:02:17 +00004955 case FK_ReferenceInitFailed:
4956 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4957 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004958 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004959 << Args[0]->getType()
4960 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004961 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4962 Args[0]->getType()->isObjCObjectPointerType())
4963 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004964 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004965
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004966 case FK_ConversionFailed: {
4967 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004968 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4969 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004970 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004971 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004972 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004973 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004974 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4975 Args[0]->getType()->isObjCObjectPointerType())
4976 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004977 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004978 }
John Wiegley429bb272011-04-08 18:41:53 +00004979
4980 case FK_ConversionFromPropertyFailed:
4981 // No-op. This error has already been reported.
4982 break;
4983
Douglas Gregord87b61f2009-12-10 17:56:55 +00004984 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004985 SourceRange R;
4986
4987 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004988 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004989 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004990 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004991 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004992
Douglas Gregor19311e72010-09-08 21:40:08 +00004993 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4994 if (Kind.isCStyleOrFunctionalCast())
4995 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4996 << R;
4997 else
4998 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4999 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005000 break;
5001 }
5002
5003 case FK_ReferenceBindingToInitList:
5004 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5005 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5006 break;
5007
5008 case FK_InitListBadDestinationType:
5009 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5010 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5011 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005012
Douglas Gregor51c56d62009-12-14 20:49:26 +00005013 case FK_ConstructorOverloadFailed: {
5014 SourceRange ArgsRange;
5015 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005016 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005017 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005018
Douglas Gregor51c56d62009-12-14 20:49:26 +00005019 // FIXME: Using "DestType" for the entity we're printing is probably
5020 // bad.
5021 switch (FailedOverloadResult) {
5022 case OR_Ambiguous:
5023 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5024 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005025 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5026 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005027 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005028
Douglas Gregor51c56d62009-12-14 20:49:26 +00005029 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005030 if (Kind.getKind() == InitializationKind::IK_Default &&
5031 (Entity.getKind() == InitializedEntity::EK_Base ||
5032 Entity.getKind() == InitializedEntity::EK_Member) &&
5033 isa<CXXConstructorDecl>(S.CurContext)) {
5034 // This is implicit default initialization of a member or
5035 // base within a constructor. If no viable function was
5036 // found, notify the user that she needs to explicitly
5037 // initialize this base/member.
5038 CXXConstructorDecl *Constructor
5039 = cast<CXXConstructorDecl>(S.CurContext);
5040 if (Entity.getKind() == InitializedEntity::EK_Base) {
5041 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5042 << Constructor->isImplicit()
5043 << S.Context.getTypeDeclType(Constructor->getParent())
5044 << /*base=*/0
5045 << Entity.getType();
5046
5047 RecordDecl *BaseDecl
5048 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5049 ->getDecl();
5050 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5051 << S.Context.getTagDeclType(BaseDecl);
5052 } else {
5053 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5054 << Constructor->isImplicit()
5055 << S.Context.getTypeDeclType(Constructor->getParent())
5056 << /*member=*/1
5057 << Entity.getName();
5058 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5059
5060 if (const RecordType *Record
5061 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005062 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005063 diag::note_previous_decl)
5064 << S.Context.getTagDeclType(Record->getDecl());
5065 }
5066 break;
5067 }
5068
Douglas Gregor51c56d62009-12-14 20:49:26 +00005069 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5070 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005071 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005072 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005073
Douglas Gregor51c56d62009-12-14 20:49:26 +00005074 case OR_Deleted: {
5075 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5076 << true << DestType << ArgsRange;
5077 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005078 OverloadingResult Ovl
5079 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005080 if (Ovl == OR_Deleted) {
5081 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005082 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005083 } else {
5084 llvm_unreachable("Inconsistent overload resolution?");
5085 }
5086 break;
5087 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005088
Douglas Gregor51c56d62009-12-14 20:49:26 +00005089 case OR_Success:
5090 llvm_unreachable("Conversion did not fail!");
5091 break;
5092 }
5093 break;
5094 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005095
Douglas Gregor99a2e602009-12-16 01:38:02 +00005096 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005097 if (Entity.getKind() == InitializedEntity::EK_Member &&
5098 isa<CXXConstructorDecl>(S.CurContext)) {
5099 // This is implicit default-initialization of a const member in
5100 // a constructor. Complain that it needs to be explicitly
5101 // initialized.
5102 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5103 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5104 << Constructor->isImplicit()
5105 << S.Context.getTypeDeclType(Constructor->getParent())
5106 << /*const=*/1
5107 << Entity.getName();
5108 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5109 << Entity.getName();
5110 } else {
5111 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5112 << DestType << (bool)DestType->getAs<RecordType>();
5113 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005114 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005115
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005116 case FK_Incomplete:
5117 S.RequireCompleteType(Kind.getLocation(), DestType,
5118 diag::err_init_incomplete_type);
5119 break;
5120
Sebastian Redl14b0c192011-09-24 17:48:00 +00005121 case FK_ListInitializationFailed: {
5122 // Run the init list checker again to emit diagnostics.
5123 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5124 QualType DestType = Entity.getType();
5125 InitListChecker DiagnoseInitList(S, Entity, InitList,
5126 DestType, /*VerifyOnly=*/false);
5127 assert(DiagnoseInitList.HadError() &&
5128 "Inconsistent init list check result.");
5129 break;
5130 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005131 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005132
Douglas Gregora41a8c52010-04-22 00:20:18 +00005133 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005134 return true;
5135}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005136
Chris Lattner5f9e2722011-07-23 10:55:15 +00005137void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005138 switch (SequenceKind) {
5139 case FailedSequence: {
5140 OS << "Failed sequence: ";
5141 switch (Failure) {
5142 case FK_TooManyInitsForReference:
5143 OS << "too many initializers for reference";
5144 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005145
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005146 case FK_ArrayNeedsInitList:
5147 OS << "array requires initializer list";
5148 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005149
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005150 case FK_ArrayNeedsInitListOrStringLiteral:
5151 OS << "array requires initializer list or string literal";
5152 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005153
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005154 case FK_ArrayTypeMismatch:
5155 OS << "array type mismatch";
5156 break;
5157
5158 case FK_NonConstantArrayInit:
5159 OS << "non-constant array initializer";
5160 break;
5161
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005162 case FK_AddressOfOverloadFailed:
5163 OS << "address of overloaded function failed";
5164 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005165
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005166 case FK_ReferenceInitOverloadFailed:
5167 OS << "overload resolution for reference initialization failed";
5168 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005169
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005170 case FK_NonConstLValueReferenceBindingToTemporary:
5171 OS << "non-const lvalue reference bound to temporary";
5172 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005173
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005174 case FK_NonConstLValueReferenceBindingToUnrelated:
5175 OS << "non-const lvalue reference bound to unrelated type";
5176 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005177
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005178 case FK_RValueReferenceBindingToLValue:
5179 OS << "rvalue reference bound to an lvalue";
5180 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005181
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005182 case FK_ReferenceInitDropsQualifiers:
5183 OS << "reference initialization drops qualifiers";
5184 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005185
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005186 case FK_ReferenceInitFailed:
5187 OS << "reference initialization failed";
5188 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005189
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005190 case FK_ConversionFailed:
5191 OS << "conversion failed";
5192 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005193
John Wiegley429bb272011-04-08 18:41:53 +00005194 case FK_ConversionFromPropertyFailed:
5195 OS << "conversion from property failed";
5196 break;
5197
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005198 case FK_TooManyInitsForScalar:
5199 OS << "too many initializers for scalar";
5200 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005201
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005202 case FK_ReferenceBindingToInitList:
5203 OS << "referencing binding to initializer list";
5204 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005205
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005206 case FK_InitListBadDestinationType:
5207 OS << "initializer list for non-aggregate, non-scalar type";
5208 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005209
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005210 case FK_UserConversionOverloadFailed:
5211 OS << "overloading failed for user-defined conversion";
5212 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005213
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005214 case FK_ConstructorOverloadFailed:
5215 OS << "constructor overloading failed";
5216 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005217
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005218 case FK_DefaultInitOfConst:
5219 OS << "default initialization of a const variable";
5220 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005221
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005222 case FK_Incomplete:
5223 OS << "initialization of incomplete type";
5224 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005225
5226 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005227 OS << "list initialization checker failure";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005228 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005229 OS << '\n';
5230 return;
5231 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005232
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005233 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005234 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005235 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005236
Sebastian Redl7491c492011-06-05 13:59:11 +00005237 case NormalSequence:
5238 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005239 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005240 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005241
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005242 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5243 if (S != step_begin()) {
5244 OS << " -> ";
5245 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005246
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005247 switch (S->Kind) {
5248 case SK_ResolveAddressOfOverloadedFunction:
5249 OS << "resolve address of overloaded function";
5250 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005251
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005252 case SK_CastDerivedToBaseRValue:
5253 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5254 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005255
Sebastian Redl906082e2010-07-20 04:20:21 +00005256 case SK_CastDerivedToBaseXValue:
5257 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5258 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005259
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005260 case SK_CastDerivedToBaseLValue:
5261 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5262 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005263
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005264 case SK_BindReference:
5265 OS << "bind reference to lvalue";
5266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005267
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005268 case SK_BindReferenceToTemporary:
5269 OS << "bind reference to a temporary";
5270 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005271
Douglas Gregor523d46a2010-04-18 07:40:54 +00005272 case SK_ExtraneousCopyToTemporary:
5273 OS << "extraneous C++03 copy to temporary";
5274 break;
5275
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005276 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00005277 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005278 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005279
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005280 case SK_QualificationConversionRValue:
5281 OS << "qualification conversion (rvalue)";
5282
Sebastian Redl906082e2010-07-20 04:20:21 +00005283 case SK_QualificationConversionXValue:
5284 OS << "qualification conversion (xvalue)";
5285
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005286 case SK_QualificationConversionLValue:
5287 OS << "qualification conversion (lvalue)";
5288 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005289
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005290 case SK_ConversionSequence:
5291 OS << "implicit conversion sequence (";
5292 S->ICS->DebugPrint(); // FIXME: use OS
5293 OS << ")";
5294 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005295
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005296 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005297 OS << "list aggregate initialization";
5298 break;
5299
5300 case SK_ListConstructorCall:
5301 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005302 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005303
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005304 case SK_ConstructorInitialization:
5305 OS << "constructor initialization";
5306 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005307
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005308 case SK_ZeroInitialization:
5309 OS << "zero initialization";
5310 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005311
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005312 case SK_CAssignment:
5313 OS << "C assignment";
5314 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005315
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005316 case SK_StringInit:
5317 OS << "string initialization";
5318 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005319
5320 case SK_ObjCObjectConversion:
5321 OS << "Objective-C object conversion";
5322 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005323
5324 case SK_ArrayInit:
5325 OS << "array initialization";
5326 break;
John McCallf85e1932011-06-15 23:02:42 +00005327
5328 case SK_PassByIndirectCopyRestore:
5329 OS << "pass by indirect copy and restore";
5330 break;
5331
5332 case SK_PassByIndirectRestore:
5333 OS << "pass by indirect restore";
5334 break;
5335
5336 case SK_ProduceObjCObject:
5337 OS << "Objective-C object retension";
5338 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005339 }
5340 }
5341}
5342
5343void InitializationSequence::dump() const {
5344 dump(llvm::errs());
5345}
5346
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005347static void DiagnoseNarrowingInInitList(
5348 Sema& S, QualType EntityType, const Expr *InitE,
5349 bool Constant, const APValue &ConstantValue) {
5350 if (Constant) {
5351 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005352 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005353 ? diag::err_init_list_constant_narrowing
5354 : diag::warn_init_list_constant_narrowing)
5355 << InitE->getSourceRange()
5356 << ConstantValue
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005357 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005358 } else
5359 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005360 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005361 ? diag::err_init_list_variable_narrowing
5362 : diag::warn_init_list_variable_narrowing)
5363 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005364 << InitE->getType().getLocalUnqualifiedType()
5365 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005366
5367 llvm::SmallString<128> StaticCast;
5368 llvm::raw_svector_ostream OS(StaticCast);
5369 OS << "static_cast<";
5370 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5371 // It's important to use the typedef's name if there is one so that the
5372 // fixit doesn't break code using types like int64_t.
5373 //
5374 // FIXME: This will break if the typedef requires qualification. But
5375 // getQualifiedNameAsString() includes non-machine-parsable components.
5376 OS << TT->getDecl();
5377 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5378 OS << BT->getName(S.getLangOptions());
5379 else {
5380 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5381 // with a broken cast.
5382 return;
5383 }
5384 OS << ">(";
5385 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5386 << InitE->getSourceRange()
5387 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5388 << FixItHint::CreateInsertion(
5389 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5390}
5391
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005392//===----------------------------------------------------------------------===//
5393// Initialization helper functions
5394//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005395bool
5396Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5397 ExprResult Init) {
5398 if (Init.isInvalid())
5399 return false;
5400
5401 Expr *InitE = Init.get();
5402 assert(InitE && "No initialization expression");
5403
5404 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5405 SourceLocation());
5406 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005407 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005408}
5409
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005410ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005411Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5412 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005413 ExprResult Init,
5414 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005415 if (Init.isInvalid())
5416 return ExprError();
5417
John McCall15d7d122010-11-11 03:21:53 +00005418 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005419 assert(InitE && "No initialization expression?");
5420
5421 if (EqualLoc.isInvalid())
5422 EqualLoc = InitE->getLocStart();
5423
5424 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5425 EqualLoc);
5426 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5427 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005428
5429 bool Constant = false;
5430 APValue Result;
5431 if (TopLevelOfInitList &&
5432 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5433 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5434 Constant, Result);
5435 }
John McCallf312b1e2010-08-26 23:41:50 +00005436 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005437}