blob: 12df59fb76a78c0c94cf6e95fd6ec986c933fb64 [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) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001618 if (VerifyOnly) {
1619 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001620 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001621 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001622
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001623 // There was no normal field in the struct with the designated
1624 // name. Perform another lookup for this name, which may find
1625 // something that we can't designate (e.g., a member function),
1626 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001627 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001628 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001629 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001630 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001631 // Name lookup didn't find anything. Determine whether this
1632 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001634 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001635 TypoCorrection Corrected = SemaRef.CorrectTypo(
1636 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1637 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1638 RT->getDecl(), false, Sema::CTC_NoKeywords);
1639 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001640 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001641 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001642 std::string CorrectedStr(
1643 Corrected.getAsString(SemaRef.getLangOptions()));
1644 std::string CorrectedQuotedStr(
1645 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001646 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001647 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001648 << FieldName << CurrentObjectType << CorrectedQuotedStr
1649 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001651 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001652 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001653 } else {
1654 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1655 << FieldName << CurrentObjectType;
1656 ++Index;
1657 return true;
1658 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001659 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001660
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001661 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001662 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001663 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001664 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001665 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001666 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001667 ++Index;
1668 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001669 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001670
Francois Picheta0e27f02010-12-22 03:46:10 +00001671 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001672 // The replacement field comes from typo correction; find it
1673 // in the list of fields.
1674 FieldIndex = 0;
1675 Field = RT->getDecl()->field_begin();
1676 for (; Field != FieldEnd; ++Field) {
1677 if (Field->isUnnamedBitfield())
1678 continue;
1679
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001681 Field->getIdentifier() == ReplacementField->getIdentifier())
1682 break;
1683
1684 ++FieldIndex;
1685 }
1686 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001687 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001688
1689 // All of the fields of a union are located at the same place in
1690 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001691 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001692 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001693 if (!VerifyOnly)
1694 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001695 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001696
Douglas Gregor54001c12011-06-29 21:51:31 +00001697 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001698 bool InvalidUse;
1699 if (VerifyOnly)
1700 InvalidUse = !SemaRef.CanUseDecl(*Field);
1701 else
1702 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1703 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001704 ++Index;
1705 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001706 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001707
Sebastian Redl14b0c192011-09-24 17:48:00 +00001708 if (!VerifyOnly) {
1709 // Update the designator with the field declaration.
1710 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Sebastian Redl14b0c192011-09-24 17:48:00 +00001712 // Make sure that our non-designated initializer list has space
1713 // for a subobject corresponding to this field.
1714 if (FieldIndex >= StructuredList->getNumInits())
1715 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1716 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001717
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001718 // This designator names a flexible array member.
1719 if (Field->getType()->isIncompleteArrayType()) {
1720 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001721 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001722 // We can't designate an object within the flexible array
1723 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001724 if (!VerifyOnly) {
1725 DesignatedInitExpr::Designator *NextD
1726 = DIE->getDesignator(DesigIdx + 1);
1727 SemaRef.Diag(NextD->getStartLocation(),
1728 diag::err_designator_into_flexible_array_member)
1729 << SourceRange(NextD->getStartLocation(),
1730 DIE->getSourceRange().getEnd());
1731 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1732 << *Field;
1733 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001734 Invalid = true;
1735 }
1736
Chris Lattner9046c222010-10-10 17:49:49 +00001737 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1738 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001739 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001740 if (!VerifyOnly) {
1741 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1742 diag::err_flexible_array_init_needs_braces)
1743 << DIE->getInit()->getSourceRange();
1744 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1745 << *Field;
1746 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001747 Invalid = true;
1748 }
1749
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001750 // Check GNU flexible array initializer.
1751 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1752 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001753 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001754
1755 if (Invalid) {
1756 ++Index;
1757 return true;
1758 }
1759
1760 // Initialize the array.
1761 bool prevHadError = hadError;
1762 unsigned newStructuredIndex = FieldIndex;
1763 unsigned OldIndex = Index;
1764 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001765
1766 InitializedEntity MemberEntity =
1767 InitializedEntity::InitializeMember(*Field, &Entity);
1768 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001769 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001770
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001771 IList->setInit(OldIndex, DIE);
1772 if (hadError && !prevHadError) {
1773 ++Field;
1774 ++FieldIndex;
1775 if (NextField)
1776 *NextField = Field;
1777 StructuredIndex = FieldIndex;
1778 return true;
1779 }
1780 } else {
1781 // Recurse to check later designated subobjects.
1782 QualType FieldType = (*Field)->getType();
1783 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001784
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001785 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001786 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1788 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001789 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001790 true, false))
1791 return true;
1792 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001793
1794 // Find the position of the next field to be initialized in this
1795 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001796 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001798
1799 // If this the first designator, our caller will continue checking
1800 // the rest of this struct/class/union subobject.
1801 if (IsFirstDesignator) {
1802 if (NextField)
1803 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001804 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001805 return false;
1806 }
1807
Douglas Gregor34e79462009-01-28 23:36:17 +00001808 if (!FinishSubobjectInit)
1809 return false;
1810
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001811 // We've already initialized something in the union; we're done.
1812 if (RT->getDecl()->isUnion())
1813 return hadError;
1814
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001815 // Check the remaining fields within this class/struct/union subobject.
1816 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001817
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001818 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001819 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001820 return hadError && !prevHadError;
1821 }
1822
1823 // C99 6.7.8p6:
1824 //
1825 // If a designator has the form
1826 //
1827 // [ constant-expression ]
1828 //
1829 // then the current object (defined below) shall have array
1830 // type and the expression shall be an integer constant
1831 // expression. If the array is of unknown size, any
1832 // nonnegative value is valid.
1833 //
1834 // Additionally, cope with the GNU extension that permits
1835 // designators of the form
1836 //
1837 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001838 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001839 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001840 if (!VerifyOnly)
1841 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1842 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001843 ++Index;
1844 return true;
1845 }
1846
1847 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001848 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1849 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001850 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001851 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001852 DesignatedEndIndex = DesignatedStartIndex;
1853 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001854 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001855
Mike Stump1eb44332009-09-09 15:08:12 +00001856 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001857 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001858 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001859 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001860 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001861
Chris Lattnere0fd8322011-02-19 22:28:58 +00001862 // Codegen can't handle evaluating array range designators that have side
1863 // effects, because we replicate the AST value for each initialized element.
1864 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1865 // elements with something that has a side effect, so codegen can emit an
1866 // "error unsupported" error instead of miscompiling the app.
1867 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001868 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001869 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001870 }
1871
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001872 if (isa<ConstantArrayType>(AT)) {
1873 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001874 DesignatedStartIndex
1875 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001876 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001877 DesignatedEndIndex
1878 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001879 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1880 if (DesignatedEndIndex >= MaxElements) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001881 if (VerifyOnly)
1882 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1883 diag::err_array_designator_too_large)
1884 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1885 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001886 ++Index;
1887 return true;
1888 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001889 } else {
1890 // Make sure the bit-widths and signedness match.
1891 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001892 DesignatedEndIndex
1893 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001894 else if (DesignatedStartIndex.getBitWidth() <
1895 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001896 DesignatedStartIndex
1897 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001898 DesignatedStartIndex.setIsUnsigned(true);
1899 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001900 }
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Douglas Gregor4c678342009-01-28 21:54:33 +00001902 // Make sure that our non-designated initializer list has space
1903 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001904 if (!VerifyOnly &&
1905 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001906 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001907 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001908
Douglas Gregor34e79462009-01-28 23:36:17 +00001909 // Repeatedly perform subobject initializations in the range
1910 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001911
Douglas Gregor34e79462009-01-28 23:36:17 +00001912 // Move to the next designator
1913 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1914 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001915
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001916 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001917 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001918
Douglas Gregor34e79462009-01-28 23:36:17 +00001919 while (DesignatedStartIndex <= DesignatedEndIndex) {
1920 // Recurse to check later designated subobjects.
1921 QualType ElementType = AT->getElementType();
1922 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001923
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001924 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001925 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1926 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001927 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001928 (DesignatedStartIndex == DesignatedEndIndex),
1929 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001930 return true;
1931
1932 // Move to the next index in the array that we'll be initializing.
1933 ++DesignatedStartIndex;
1934 ElementIndex = DesignatedStartIndex.getZExtValue();
1935 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001936
1937 // If this the first designator, our caller will continue checking
1938 // the rest of this array subobject.
1939 if (IsFirstDesignator) {
1940 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001941 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001942 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001943 return false;
1944 }
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Douglas Gregor34e79462009-01-28 23:36:17 +00001946 if (!FinishSubobjectInit)
1947 return false;
1948
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001949 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001950 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001951 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001952 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001953 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001954 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001955}
1956
Douglas Gregor4c678342009-01-28 21:54:33 +00001957// Get the structured initializer list for a subobject of type
1958// @p CurrentObjectType.
1959InitListExpr *
1960InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1961 QualType CurrentObjectType,
1962 InitListExpr *StructuredList,
1963 unsigned StructuredIndex,
1964 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001965 if (VerifyOnly)
1966 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00001967 Expr *ExistingInit = 0;
1968 if (!StructuredList)
1969 ExistingInit = SyntacticToSemantic[IList];
1970 else if (StructuredIndex < StructuredList->getNumInits())
1971 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor4c678342009-01-28 21:54:33 +00001973 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1974 return Result;
1975
1976 if (ExistingInit) {
1977 // We are creating an initializer list that initializes the
1978 // subobjects of the current object, but there was already an
1979 // initialization that completely initialized the current
1980 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001981 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001982 // struct X { int a, b; };
1983 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001984 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001985 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1986 // designated initializer re-initializes the whole
1987 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001988 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001989 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001990 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001991 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001992 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001993 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001994 << ExistingInit->getSourceRange();
1995 }
1996
Mike Stump1eb44332009-09-09 15:08:12 +00001997 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001998 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1999 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002000 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002001
Douglas Gregor63982352010-07-13 18:40:04 +00002002 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00002003
Douglas Gregorfa219202009-03-20 23:58:33 +00002004 // Pre-allocate storage for the structured initializer list.
2005 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002006 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002007 bool GotNumInits = false;
2008 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002009 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002010 GotNumInits = true;
2011 } else if (Index < IList->getNumInits()) {
2012 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002013 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002014 GotNumInits = true;
2015 }
Douglas Gregor08457732009-03-21 18:13:52 +00002016 }
2017
Mike Stump1eb44332009-09-09 15:08:12 +00002018 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002019 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2020 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2021 NumElements = CAType->getSize().getZExtValue();
2022 // Simple heuristic so that we don't allocate a very large
2023 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002024 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002025 NumElements = 0;
2026 }
John McCall183700f2009-09-21 23:43:11 +00002027 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002028 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002029 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002030 RecordDecl *RDecl = RType->getDecl();
2031 if (RDecl->isUnion())
2032 NumElements = 1;
2033 else
Mike Stump1eb44332009-09-09 15:08:12 +00002034 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002035 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002036 }
2037
Douglas Gregor08457732009-03-21 18:13:52 +00002038 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002039 NumElements = IList->getNumInits();
2040
Ted Kremenek709210f2010-04-13 23:39:13 +00002041 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002042
Douglas Gregor4c678342009-01-28 21:54:33 +00002043 // Link this new initializer list into the structured initializer
2044 // lists.
2045 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002046 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002047 else {
2048 Result->setSyntacticForm(IList);
2049 SyntacticToSemantic[IList] = Result;
2050 }
2051
2052 return Result;
2053}
2054
2055/// Update the initializer at index @p StructuredIndex within the
2056/// structured initializer list to the value @p expr.
2057void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2058 unsigned &StructuredIndex,
2059 Expr *expr) {
2060 // No structured initializer list to update
2061 if (!StructuredList)
2062 return;
2063
Ted Kremenek709210f2010-04-13 23:39:13 +00002064 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2065 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002066 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00002067 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002068 diag::warn_initializer_overrides)
2069 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002070 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002071 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002072 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002073 << PrevInit->getSourceRange();
2074 }
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Douglas Gregor4c678342009-01-28 21:54:33 +00002076 ++StructuredIndex;
2077}
2078
Douglas Gregor05c13a32009-01-22 00:58:24 +00002079/// Check that the given Index expression is a valid array designator
2080/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002081/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002082/// and produces a reasonable diagnostic if there is a
2083/// failure. Returns true if there was an error, false otherwise. If
2084/// everything went okay, Value will receive the value of the constant
2085/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002086static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00002087CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002088 SourceLocation Loc = Index->getSourceRange().getBegin();
2089
2090 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00002091 if (S.VerifyIntegerConstantExpression(Index, &Value))
2092 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002093
Chris Lattner3bf68932009-04-25 21:59:05 +00002094 if (Value.isSigned() && Value.isNegative())
2095 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002096 << Value.toString(10) << Index->getSourceRange();
2097
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002098 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002099 return false;
2100}
2101
John McCall60d7b3a2010-08-24 06:29:42 +00002102ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002103 SourceLocation Loc,
2104 bool GNUSyntax,
2105 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002106 typedef DesignatedInitExpr::Designator ASTDesignator;
2107
2108 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002109 SmallVector<ASTDesignator, 32> Designators;
2110 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002111
2112 // Build designators and check array designator expressions.
2113 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2114 const Designator &D = Desig.getDesignator(Idx);
2115 switch (D.getKind()) {
2116 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002117 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002118 D.getFieldLoc()));
2119 break;
2120
2121 case Designator::ArrayDesignator: {
2122 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2123 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002124 if (!Index->isTypeDependent() &&
2125 !Index->isValueDependent() &&
2126 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002127 Invalid = true;
2128 else {
2129 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002130 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002131 D.getRBracketLoc()));
2132 InitExpressions.push_back(Index);
2133 }
2134 break;
2135 }
2136
2137 case Designator::ArrayRangeDesignator: {
2138 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2139 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2140 llvm::APSInt StartValue;
2141 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002142 bool StartDependent = StartIndex->isTypeDependent() ||
2143 StartIndex->isValueDependent();
2144 bool EndDependent = EndIndex->isTypeDependent() ||
2145 EndIndex->isValueDependent();
2146 if ((!StartDependent &&
2147 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2148 (!EndDependent &&
2149 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002150 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002151 else {
2152 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002153 if (StartDependent || EndDependent) {
2154 // Nothing to compute.
2155 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002156 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002157 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002158 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002159
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002160 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002161 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002162 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002163 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2164 Invalid = true;
2165 } else {
2166 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002167 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002168 D.getEllipsisLoc(),
2169 D.getRBracketLoc()));
2170 InitExpressions.push_back(StartIndex);
2171 InitExpressions.push_back(EndIndex);
2172 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002173 }
2174 break;
2175 }
2176 }
2177 }
2178
2179 if (Invalid || Init.isInvalid())
2180 return ExprError();
2181
2182 // Clear out the expressions within the designation.
2183 Desig.ClearExprs(*this);
2184
2185 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002186 = DesignatedInitExpr::Create(Context,
2187 Designators.data(), Designators.size(),
2188 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002189 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002190
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002191 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002192 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2193 << DIE->getSourceRange();
2194 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002195 Diag(DIE->getLocStart(), diag::ext_designated_init)
2196 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002197
Douglas Gregor05c13a32009-01-22 00:58:24 +00002198 return Owned(DIE);
2199}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002200
Douglas Gregor20093b42009-12-09 23:02:17 +00002201//===----------------------------------------------------------------------===//
2202// Initialization entity
2203//===----------------------------------------------------------------------===//
2204
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002205InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002206 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002207 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002208{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002209 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2210 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002211 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002212 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002213 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002214 Type = VT->getElementType();
2215 } else {
2216 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2217 assert(CT && "Unexpected type");
2218 Kind = EK_ComplexElement;
2219 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002220 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002221}
2222
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002223InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002224 CXXBaseSpecifier *Base,
2225 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002226{
2227 InitializedEntity Result;
2228 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002229 Result.Base = reinterpret_cast<uintptr_t>(Base);
2230 if (IsInheritedVirtualBase)
2231 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002232
Douglas Gregord6542d82009-12-22 15:35:07 +00002233 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002234 return Result;
2235}
2236
Douglas Gregor99a2e602009-12-16 01:38:02 +00002237DeclarationName InitializedEntity::getName() const {
2238 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002239 case EK_Parameter: {
2240 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2241 return (D ? D->getDeclName() : DeclarationName());
2242 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002243
2244 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002245 case EK_Member:
2246 return VariableOrMember->getDeclName();
2247
2248 case EK_Result:
2249 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002250 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002251 case EK_Temporary:
2252 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002253 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002254 case EK_ArrayElement:
2255 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002256 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002257 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002258 return DeclarationName();
2259 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002260
Douglas Gregor99a2e602009-12-16 01:38:02 +00002261 // Silence GCC warning
2262 return DeclarationName();
2263}
2264
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002265DeclaratorDecl *InitializedEntity::getDecl() const {
2266 switch (getKind()) {
2267 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002268 case EK_Member:
2269 return VariableOrMember;
2270
John McCallf85e1932011-06-15 23:02:42 +00002271 case EK_Parameter:
2272 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2273
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002274 case EK_Result:
2275 case EK_Exception:
2276 case EK_New:
2277 case EK_Temporary:
2278 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002279 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002280 case EK_ArrayElement:
2281 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002282 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002283 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002284 return 0;
2285 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002286
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002287 // Silence GCC warning
2288 return 0;
2289}
2290
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002291bool InitializedEntity::allowsNRVO() const {
2292 switch (getKind()) {
2293 case EK_Result:
2294 case EK_Exception:
2295 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002296
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002297 case EK_Variable:
2298 case EK_Parameter:
2299 case EK_Member:
2300 case EK_New:
2301 case EK_Temporary:
2302 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002303 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002304 case EK_ArrayElement:
2305 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002306 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002307 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002308 break;
2309 }
2310
2311 return false;
2312}
2313
Douglas Gregor20093b42009-12-09 23:02:17 +00002314//===----------------------------------------------------------------------===//
2315// Initialization sequence
2316//===----------------------------------------------------------------------===//
2317
2318void InitializationSequence::Step::Destroy() {
2319 switch (Kind) {
2320 case SK_ResolveAddressOfOverloadedFunction:
2321 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002322 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002323 case SK_CastDerivedToBaseLValue:
2324 case SK_BindReference:
2325 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002326 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002327 case SK_UserConversion:
2328 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002329 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002330 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002331 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002332 case SK_ListConstructorCall:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002333 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002334 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002335 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002336 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002337 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002338 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002339 case SK_PassByIndirectCopyRestore:
2340 case SK_PassByIndirectRestore:
2341 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002342 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002343
Douglas Gregor20093b42009-12-09 23:02:17 +00002344 case SK_ConversionSequence:
2345 delete ICS;
2346 }
2347}
2348
Douglas Gregorb70cf442010-03-26 20:14:36 +00002349bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002350 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002351}
2352
2353bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002354 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002355 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002356
Douglas Gregorb70cf442010-03-26 20:14:36 +00002357 switch (getFailureKind()) {
2358 case FK_TooManyInitsForReference:
2359 case FK_ArrayNeedsInitList:
2360 case FK_ArrayNeedsInitListOrStringLiteral:
2361 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2362 case FK_NonConstLValueReferenceBindingToTemporary:
2363 case FK_NonConstLValueReferenceBindingToUnrelated:
2364 case FK_RValueReferenceBindingToLValue:
2365 case FK_ReferenceInitDropsQualifiers:
2366 case FK_ReferenceInitFailed:
2367 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002368 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002369 case FK_TooManyInitsForScalar:
2370 case FK_ReferenceBindingToInitList:
2371 case FK_InitListBadDestinationType:
2372 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002373 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002374 case FK_ArrayTypeMismatch:
2375 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002376 case FK_ListInitializationFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002377 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002378
Douglas Gregorb70cf442010-03-26 20:14:36 +00002379 case FK_ReferenceInitOverloadFailed:
2380 case FK_UserConversionOverloadFailed:
2381 case FK_ConstructorOverloadFailed:
2382 return FailedOverloadResult == OR_Ambiguous;
2383 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002384
Douglas Gregorb70cf442010-03-26 20:14:36 +00002385 return false;
2386}
2387
Douglas Gregord6e44a32010-04-16 22:09:46 +00002388bool InitializationSequence::isConstructorInitialization() const {
2389 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2390}
2391
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002392bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2393 const Expr *Initializer,
2394 bool *isInitializerConstant,
2395 APValue *ConstantValue) const {
2396 if (Steps.empty() || Initializer->isValueDependent())
2397 return false;
2398
2399 const Step &LastStep = Steps.back();
2400 if (LastStep.Kind != SK_ConversionSequence)
2401 return false;
2402
2403 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2404 const StandardConversionSequence *SCS = NULL;
2405 switch (ICS.getKind()) {
2406 case ImplicitConversionSequence::StandardConversion:
2407 SCS = &ICS.Standard;
2408 break;
2409 case ImplicitConversionSequence::UserDefinedConversion:
2410 SCS = &ICS.UserDefined.After;
2411 break;
2412 case ImplicitConversionSequence::AmbiguousConversion:
2413 case ImplicitConversionSequence::EllipsisConversion:
2414 case ImplicitConversionSequence::BadConversion:
2415 return false;
2416 }
2417
2418 // Check if SCS represents a narrowing conversion, according to C++0x
2419 // [dcl.init.list]p7:
2420 //
2421 // A narrowing conversion is an implicit conversion ...
2422 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2423 QualType FromType = SCS->getToType(0);
2424 QualType ToType = SCS->getToType(1);
2425 switch (PossibleNarrowing) {
2426 // * from a floating-point type to an integer type, or
2427 //
2428 // * from an integer type or unscoped enumeration type to a floating-point
2429 // type, except where the source is a constant expression and the actual
2430 // value after conversion will fit into the target type and will produce
2431 // the original value when converted back to the original type, or
2432 case ICK_Floating_Integral:
2433 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2434 *isInitializerConstant = false;
2435 return true;
2436 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2437 llvm::APSInt IntConstantValue;
2438 if (Initializer &&
2439 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2440 // Convert the integer to the floating type.
2441 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2442 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2443 llvm::APFloat::rmNearestTiesToEven);
2444 // And back.
2445 llvm::APSInt ConvertedValue = IntConstantValue;
2446 bool ignored;
2447 Result.convertToInteger(ConvertedValue,
2448 llvm::APFloat::rmTowardZero, &ignored);
2449 // If the resulting value is different, this was a narrowing conversion.
2450 if (IntConstantValue != ConvertedValue) {
2451 *isInitializerConstant = true;
2452 *ConstantValue = APValue(IntConstantValue);
2453 return true;
2454 }
2455 } else {
2456 // Variables are always narrowings.
2457 *isInitializerConstant = false;
2458 return true;
2459 }
2460 }
2461 return false;
2462
2463 // * from long double to double or float, or from double to float, except
2464 // where the source is a constant expression and the actual value after
2465 // conversion is within the range of values that can be represented (even
2466 // if it cannot be represented exactly), or
2467 case ICK_Floating_Conversion:
2468 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2469 // FromType is larger than ToType.
2470 Expr::EvalResult InitializerValue;
2471 // FIXME: Check whether Initializer is a constant expression according
2472 // to C++0x [expr.const], rather than just whether it can be folded.
2473 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2474 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2475 // Constant! (Except for FIXME above.)
2476 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2477 // Convert the source value into the target type.
2478 bool ignored;
2479 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2480 Ctx.getFloatTypeSemantics(ToType),
2481 llvm::APFloat::rmNearestTiesToEven, &ignored);
2482 // If there was no overflow, the source value is within the range of
2483 // values that can be represented.
2484 if (ConvertStatus & llvm::APFloat::opOverflow) {
2485 *isInitializerConstant = true;
2486 *ConstantValue = InitializerValue.Val;
2487 return true;
2488 }
2489 } else {
2490 *isInitializerConstant = false;
2491 return true;
2492 }
2493 }
2494 return false;
2495
2496 // * from an integer type or unscoped enumeration type to an integer type
2497 // that cannot represent all the values of the original type, except where
2498 // the source is a constant expression and the actual value after
2499 // conversion will fit into the target type and will produce the original
2500 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002501 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002502 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2503 // Boolean conversions can be from pointers and pointers to members
2504 // [conv.bool], and those aren't considered narrowing conversions.
2505 return false;
2506 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002507 case ICK_Integral_Conversion: {
2508 assert(FromType->isIntegralOrUnscopedEnumerationType());
2509 assert(ToType->isIntegralOrUnscopedEnumerationType());
2510 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2511 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2512 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2513 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2514
2515 if (FromWidth > ToWidth ||
2516 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2517 // Not all values of FromType can be represented in ToType.
2518 llvm::APSInt InitializerValue;
2519 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2520 *isInitializerConstant = true;
2521 *ConstantValue = APValue(InitializerValue);
2522
2523 // Add a bit to the InitializerValue so we don't have to worry about
2524 // signed vs. unsigned comparisons.
2525 InitializerValue = InitializerValue.extend(
2526 InitializerValue.getBitWidth() + 1);
2527 // Convert the initializer to and from the target width and signed-ness.
2528 llvm::APSInt ConvertedValue = InitializerValue;
2529 ConvertedValue = ConvertedValue.trunc(ToWidth);
2530 ConvertedValue.setIsSigned(ToSigned);
2531 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2532 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2533 // If the result is different, this was a narrowing conversion.
2534 return ConvertedValue != InitializerValue;
2535 } else {
2536 // Variables are always narrowings.
2537 *isInitializerConstant = false;
2538 return true;
2539 }
2540 }
2541 return false;
2542 }
2543
2544 default:
2545 // Other kinds of conversions are not narrowings.
2546 return false;
2547 }
2548}
2549
Douglas Gregor20093b42009-12-09 23:02:17 +00002550void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002551 FunctionDecl *Function,
2552 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002553 Step S;
2554 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2555 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002556 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002557 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 Steps.push_back(S);
2559}
2560
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002561void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002562 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002563 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002564 switch (VK) {
2565 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2566 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2567 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002568 default: llvm_unreachable("No such category");
2569 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002570 S.Type = BaseType;
2571 Steps.push_back(S);
2572}
2573
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002574void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002575 bool BindingTemporary) {
2576 Step S;
2577 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2578 S.Type = T;
2579 Steps.push_back(S);
2580}
2581
Douglas Gregor523d46a2010-04-18 07:40:54 +00002582void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2583 Step S;
2584 S.Kind = SK_ExtraneousCopyToTemporary;
2585 S.Type = T;
2586 Steps.push_back(S);
2587}
2588
Eli Friedman03981012009-12-11 02:42:07 +00002589void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002590 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002591 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002592 Step S;
2593 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002594 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002595 S.Function.Function = Function;
2596 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002597 Steps.push_back(S);
2598}
2599
2600void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002601 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002602 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002603 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002604 switch (VK) {
2605 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002606 S.Kind = SK_QualificationConversionRValue;
2607 break;
John McCall5baba9d2010-08-25 10:28:54 +00002608 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002609 S.Kind = SK_QualificationConversionXValue;
2610 break;
John McCall5baba9d2010-08-25 10:28:54 +00002611 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002612 S.Kind = SK_QualificationConversionLValue;
2613 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002614 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002615 S.Type = Ty;
2616 Steps.push_back(S);
2617}
2618
2619void InitializationSequence::AddConversionSequenceStep(
2620 const ImplicitConversionSequence &ICS,
2621 QualType T) {
2622 Step S;
2623 S.Kind = SK_ConversionSequence;
2624 S.Type = T;
2625 S.ICS = new ImplicitConversionSequence(ICS);
2626 Steps.push_back(S);
2627}
2628
Douglas Gregord87b61f2009-12-10 17:56:55 +00002629void InitializationSequence::AddListInitializationStep(QualType T) {
2630 Step S;
2631 S.Kind = SK_ListInitialization;
2632 S.Type = T;
2633 Steps.push_back(S);
2634}
2635
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002636void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002637InitializationSequence::AddConstructorInitializationStep(
2638 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002639 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002640 QualType T) {
2641 Step S;
2642 S.Kind = SK_ConstructorInitialization;
2643 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002644 S.Function.Function = Constructor;
2645 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002646 Steps.push_back(S);
2647}
2648
Douglas Gregor71d17402009-12-15 00:01:57 +00002649void InitializationSequence::AddZeroInitializationStep(QualType T) {
2650 Step S;
2651 S.Kind = SK_ZeroInitialization;
2652 S.Type = T;
2653 Steps.push_back(S);
2654}
2655
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002656void InitializationSequence::AddCAssignmentStep(QualType T) {
2657 Step S;
2658 S.Kind = SK_CAssignment;
2659 S.Type = T;
2660 Steps.push_back(S);
2661}
2662
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002663void InitializationSequence::AddStringInitStep(QualType T) {
2664 Step S;
2665 S.Kind = SK_StringInit;
2666 S.Type = T;
2667 Steps.push_back(S);
2668}
2669
Douglas Gregor569c3162010-08-07 11:51:51 +00002670void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2671 Step S;
2672 S.Kind = SK_ObjCObjectConversion;
2673 S.Type = T;
2674 Steps.push_back(S);
2675}
2676
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002677void InitializationSequence::AddArrayInitStep(QualType T) {
2678 Step S;
2679 S.Kind = SK_ArrayInit;
2680 S.Type = T;
2681 Steps.push_back(S);
2682}
2683
John McCallf85e1932011-06-15 23:02:42 +00002684void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2685 bool shouldCopy) {
2686 Step s;
2687 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2688 : SK_PassByIndirectRestore);
2689 s.Type = type;
2690 Steps.push_back(s);
2691}
2692
2693void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2694 Step S;
2695 S.Kind = SK_ProduceObjCObject;
2696 S.Type = T;
2697 Steps.push_back(S);
2698}
2699
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002700void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002701 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002702 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002703 this->Failure = Failure;
2704 this->FailedOverloadResult = Result;
2705}
2706
2707//===----------------------------------------------------------------------===//
2708// Attempt initialization
2709//===----------------------------------------------------------------------===//
2710
John McCallf85e1932011-06-15 23:02:42 +00002711static void MaybeProduceObjCObject(Sema &S,
2712 InitializationSequence &Sequence,
2713 const InitializedEntity &Entity) {
2714 if (!S.getLangOptions().ObjCAutoRefCount) return;
2715
2716 /// When initializing a parameter, produce the value if it's marked
2717 /// __attribute__((ns_consumed)).
2718 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2719 if (!Entity.isParameterConsumed())
2720 return;
2721
2722 assert(Entity.getType()->isObjCRetainableType() &&
2723 "consuming an object of unretainable type?");
2724 Sequence.AddProduceObjCObjectStep(Entity.getType());
2725
2726 /// When initializing a return value, if the return type is a
2727 /// retainable type, then returns need to immediately retain the
2728 /// object. If an autorelease is required, it will be done at the
2729 /// last instant.
2730 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2731 if (!Entity.getType()->isObjCRetainableType())
2732 return;
2733
2734 Sequence.AddProduceObjCObjectStep(Entity.getType());
2735 }
2736}
2737
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002738/// \brief Attempt list initialization (C++0x [dcl.init.list])
2739static void TryListInitialization(Sema &S,
2740 const InitializedEntity &Entity,
2741 const InitializationKind &Kind,
2742 InitListExpr *InitList,
2743 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002744 QualType DestType = Entity.getType();
2745
Sebastian Redl14b0c192011-09-24 17:48:00 +00002746 // C++ doesn't allow scalar initialization with more than one argument.
2747 // But C99 complex numbers are scalars and it makes sense there.
2748 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2749 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2750 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2751 return;
2752 }
2753 // FIXME: C++0x defines behavior for these two cases.
2754 if (DestType->isReferenceType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002755 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2756 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002757 }
2758 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002759 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00002760 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002761 }
2762
Sebastian Redl14b0c192011-09-24 17:48:00 +00002763 InitListChecker CheckInitList(S, Entity, InitList,
2764 DestType, /*VerifyOnly=*/true);
2765 if (CheckInitList.HadError()) {
2766 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2767 return;
2768 }
2769
2770 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002771 Sequence.AddListInitializationStep(DestType);
2772}
Douglas Gregor20093b42009-12-09 23:02:17 +00002773
2774/// \brief Try a reference initialization that involves calling a conversion
2775/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002776static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2777 const InitializedEntity &Entity,
2778 const InitializationKind &Kind,
2779 Expr *Initializer,
2780 bool AllowRValues,
2781 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002782 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002783 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2784 QualType T1 = cv1T1.getUnqualifiedType();
2785 QualType cv2T2 = Initializer->getType();
2786 QualType T2 = cv2T2.getUnqualifiedType();
2787
2788 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002789 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002790 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002791 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002792 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002793 ObjCConversion,
2794 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002795 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002796 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002797 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002798 (void)ObjCLifetimeConversion;
2799
Douglas Gregor20093b42009-12-09 23:02:17 +00002800 // Build the candidate set directly in the initialization sequence
2801 // structure, so that it will persist if we fail.
2802 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2803 CandidateSet.clear();
2804
2805 // Determine whether we are allowed to call explicit constructors or
2806 // explicit conversion operators.
2807 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002808
Douglas Gregor20093b42009-12-09 23:02:17 +00002809 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002810 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2811 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002812 // The type we're converting to is a class type. Enumerate its constructors
2813 // to see if there is a suitable conversion.
2814 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002815
Douglas Gregor20093b42009-12-09 23:02:17 +00002816 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002817 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002818 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002819 NamedDecl *D = *Con;
2820 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2821
Douglas Gregor20093b42009-12-09 23:02:17 +00002822 // Find the constructor (which may be a template).
2823 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002824 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002825 if (ConstructorTmpl)
2826 Constructor = cast<CXXConstructorDecl>(
2827 ConstructorTmpl->getTemplatedDecl());
2828 else
John McCall9aa472c2010-03-19 07:35:19 +00002829 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002830
Douglas Gregor20093b42009-12-09 23:02:17 +00002831 if (!Constructor->isInvalidDecl() &&
2832 Constructor->isConvertingConstructor(AllowExplicit)) {
2833 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002834 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002835 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002836 &Initializer, 1, CandidateSet,
2837 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002838 else
John McCall9aa472c2010-03-19 07:35:19 +00002839 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002840 &Initializer, 1, CandidateSet,
2841 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002842 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002843 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002844 }
John McCall572fc622010-08-17 07:23:57 +00002845 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2846 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002847
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002848 const RecordType *T2RecordType = 0;
2849 if ((T2RecordType = T2->getAs<RecordType>()) &&
2850 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002851 // The type we're converting from is a class type, enumerate its conversion
2852 // functions.
2853 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2854
John McCalleec51cf2010-01-20 00:46:10 +00002855 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002856 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002857 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2858 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002859 NamedDecl *D = *I;
2860 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2861 if (isa<UsingShadowDecl>(D))
2862 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002863
Douglas Gregor20093b42009-12-09 23:02:17 +00002864 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2865 CXXConversionDecl *Conv;
2866 if (ConvTemplate)
2867 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2868 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002869 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002870
Douglas Gregor20093b42009-12-09 23:02:17 +00002871 // If the conversion function doesn't return a reference type,
2872 // it can't be considered for this conversion unless we're allowed to
2873 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002874 // FIXME: Do we need to make sure that we only consider conversion
2875 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002876 // break recursion.
2877 if ((AllowExplicit || !Conv->isExplicit()) &&
2878 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2879 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002880 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002881 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002882 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002883 else
John McCall9aa472c2010-03-19 07:35:19 +00002884 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002885 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002886 }
2887 }
2888 }
John McCall572fc622010-08-17 07:23:57 +00002889 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2890 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002891
Douglas Gregor20093b42009-12-09 23:02:17 +00002892 SourceLocation DeclLoc = Initializer->getLocStart();
2893
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002894 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002895 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002896 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002897 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002898 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002899
Douglas Gregor20093b42009-12-09 23:02:17 +00002900 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002901
Chandler Carruth25ca4212011-02-25 19:41:05 +00002902 // This is the overload that will actually be used for the initialization, so
2903 // mark it as used.
2904 S.MarkDeclarationReferenced(DeclLoc, Function);
2905
Eli Friedman03981012009-12-11 02:42:07 +00002906 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002907 if (isa<CXXConversionDecl>(Function))
2908 T2 = Function->getResultType();
2909 else
2910 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002911
2912 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002913 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002914 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002915
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002916 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002917 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002918 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002919 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002920 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002921 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002922 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002923
Douglas Gregor20093b42009-12-09 23:02:17 +00002924 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002925 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002926 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002927 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002928 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002929 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002930 NewDerivedToBase, NewObjCConversion,
2931 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002932 if (NewRefRelationship == Sema::Ref_Incompatible) {
2933 // If the type we've converted to is not reference-related to the
2934 // type we're looking for, then there is another conversion step
2935 // we need to perform to produce a temporary of the right type
2936 // that we'll be binding to.
2937 ImplicitConversionSequence ICS;
2938 ICS.setStandard();
2939 ICS.Standard = Best->FinalConversion;
2940 T2 = ICS.Standard.getToType(2);
2941 Sequence.AddConversionSequenceStep(ICS, T2);
2942 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002943 Sequence.AddDerivedToBaseCastStep(
2944 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002945 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002946 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002947 else if (NewObjCConversion)
2948 Sequence.AddObjCObjectConversionStep(
2949 S.Context.getQualifiedType(T1,
2950 T2.getNonReferenceType().getQualifiers()));
2951
Douglas Gregor20093b42009-12-09 23:02:17 +00002952 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002953 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002954
Douglas Gregor20093b42009-12-09 23:02:17 +00002955 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2956 return OR_Success;
2957}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002958
2959/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2960static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002961 const InitializedEntity &Entity,
2962 const InitializationKind &Kind,
2963 Expr *Initializer,
2964 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002965 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002966 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002967 Qualifiers T1Quals;
2968 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002969 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002970 Qualifiers T2Quals;
2971 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002972 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002973
Douglas Gregor20093b42009-12-09 23:02:17 +00002974 // If the initializer is the address of an overloaded function, try
2975 // to resolve the overloaded function. If all goes well, T2 is the
2976 // type of the resulting function.
2977 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002978 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002979 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002980 T1,
2981 false,
2982 Found)) {
2983 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2984 cv2T2 = Fn->getType();
2985 T2 = cv2T2.getUnqualifiedType();
2986 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002987 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2988 return;
2989 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002990 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002991
Douglas Gregor20093b42009-12-09 23:02:17 +00002992 // Compute some basic properties of the types and the initializer.
2993 bool isLValueRef = DestType->isLValueReferenceType();
2994 bool isRValueRef = !isLValueRef;
2995 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002996 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002997 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002998 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002999 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003000 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003001 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003002
Douglas Gregor20093b42009-12-09 23:02:17 +00003003 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003004 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003005 // "cv2 T2" as follows:
3006 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003007 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003008 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003009 // Note the analogous bullet points for rvlaue refs to functions. Because
3010 // there are no function rvalues in C++, rvalue refs to functions are treated
3011 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003012 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003013 bool T1Function = T1->isFunctionType();
3014 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003015 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003016 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003018 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003020 // reference-compatible with "cv2 T2," or
3021 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003022 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003023 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003024 // can occur. However, we do pay attention to whether it is a bit-field
3025 // to decide whether we're actually binding to a temporary created from
3026 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003027 if (DerivedToBase)
3028 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003029 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003030 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003031 else if (ObjCConversion)
3032 Sequence.AddObjCObjectConversionStep(
3033 S.Context.getQualifiedType(T1, T2Quals));
3034
Chandler Carruth5535c382010-01-12 20:32:25 +00003035 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003036 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003037 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003038 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003039 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003040 return;
3041 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003042
3043 // - has a class type (i.e., T2 is a class type), where T1 is not
3044 // reference-related to T2, and can be implicitly converted to an
3045 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3046 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003047 // applicable conversion functions (13.3.1.6) and choosing the best
3048 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003049 // If we have an rvalue ref to function type here, the rhs must be
3050 // an rvalue.
3051 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3052 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003053 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003054 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003055 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003056 Sequence);
3057 if (ConvOvlResult == OR_Success)
3058 return;
John McCall1d318332010-01-12 00:44:57 +00003059 if (ConvOvlResult != OR_No_Viable_Function) {
3060 Sequence.SetOverloadFailure(
3061 InitializationSequence::FK_ReferenceInitOverloadFailed,
3062 ConvOvlResult);
3063 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003064 }
3065 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003066
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003067 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003068 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003069 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003070 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003071 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3072 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3073 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003074 Sequence.SetOverloadFailure(
3075 InitializationSequence::FK_ReferenceInitOverloadFailed,
3076 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003077 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003078 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003079 ? (RefRelationship == Sema::Ref_Related
3080 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3081 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3082 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003083
Douglas Gregor20093b42009-12-09 23:02:17 +00003084 return;
3085 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003086
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003087 // - If the initializer expression
3088 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3089 // "cv1 T1" is reference-compatible with "cv2 T2"
3090 // Note: functions are handled below.
3091 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003092 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003093 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003094 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003095 (InitCategory.isXValue() ||
3096 (InitCategory.isPRValue() && T2->isRecordType()) ||
3097 (InitCategory.isPRValue() && T2->isArrayType()))) {
3098 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3099 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003100 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3101 // compiler the freedom to perform a copy here or bind to the
3102 // object, while C++0x requires that we bind directly to the
3103 // object. Hence, we always bind to the object without making an
3104 // extra copy. However, in C++03 requires that we check for the
3105 // presence of a suitable copy constructor:
3106 //
3107 // The constructor that would be used to make the copy shall
3108 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003109 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003110 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00003111 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003113 if (DerivedToBase)
3114 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3115 ValueKind);
3116 else if (ObjCConversion)
3117 Sequence.AddObjCObjectConversionStep(
3118 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003119
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003120 if (T1Quals != T2Quals)
3121 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003122 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003123 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003125 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003126
3127 // - has a class type (i.e., T2 is a class type), where T1 is not
3128 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003129 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3130 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003131 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003132 if (RefRelationship == Sema::Ref_Incompatible) {
3133 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3134 Kind, Initializer,
3135 /*AllowRValues=*/true,
3136 Sequence);
3137 if (ConvOvlResult)
3138 Sequence.SetOverloadFailure(
3139 InitializationSequence::FK_ReferenceInitOverloadFailed,
3140 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003141
Douglas Gregor20093b42009-12-09 23:02:17 +00003142 return;
3143 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003144
Douglas Gregor20093b42009-12-09 23:02:17 +00003145 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3146 return;
3147 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003148
3149 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003150 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003151 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003152 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003153
Douglas Gregor20093b42009-12-09 23:02:17 +00003154 // Determine whether we are allowed to call explicit constructors or
3155 // explicit conversion operators.
3156 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003157
3158 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3159
John McCallf85e1932011-06-15 23:02:42 +00003160 ImplicitConversionSequence ICS
3161 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003162 /*SuppressUserConversions*/ false,
3163 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003164 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003165 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3166 /*AllowObjCWritebackConversion=*/false);
3167
3168 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003169 // FIXME: Use the conversion function set stored in ICS to turn
3170 // this into an overloading ambiguity diagnostic. However, we need
3171 // to keep that set as an OverloadCandidateSet rather than as some
3172 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003173 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3174 Sequence.SetOverloadFailure(
3175 InitializationSequence::FK_ReferenceInitOverloadFailed,
3176 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003177 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3178 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003179 else
3180 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003181 return;
John McCallf85e1932011-06-15 23:02:42 +00003182 } else {
3183 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003184 }
3185
3186 // [...] If T1 is reference-related to T2, cv1 must be the
3187 // same cv-qualification as, or greater cv-qualification
3188 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003189 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3190 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003191 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003192 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003193 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3194 return;
3195 }
3196
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003197 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003198 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003200 InitCategory.isLValue()) {
3201 Sequence.SetFailed(
3202 InitializationSequence::FK_RValueReferenceBindingToLValue);
3203 return;
3204 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003205
Douglas Gregor20093b42009-12-09 23:02:17 +00003206 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3207 return;
3208}
3209
3210/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003211/// (C++ [dcl.init.string], C99 6.7.8).
3212static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003213 const InitializedEntity &Entity,
3214 const InitializationKind &Kind,
3215 Expr *Initializer,
3216 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003217 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003218}
3219
Douglas Gregor20093b42009-12-09 23:02:17 +00003220/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3221/// enumerates the constructors of the initialized entity and performs overload
3222/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003223static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003224 const InitializedEntity &Entity,
3225 const InitializationKind &Kind,
3226 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003227 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003228 InitializationSequence &Sequence) {
Richard Trieu898267f2011-09-01 21:44:13 +00003229 // Check constructor arguments for self reference.
3230 if (DeclaratorDecl *DD = Entity.getDecl())
3231 // Parameters arguments are occassionially constructed with itself,
3232 // for instance, in recursive functions. Skip them.
3233 if (!isa<ParmVarDecl>(DD))
3234 for (unsigned i = 0; i < NumArgs; ++i)
3235 S.CheckSelfReference(DD, Args[i]);
3236
Douglas Gregor51c56d62009-12-14 20:49:26 +00003237 // Build the candidate set directly in the initialization sequence
3238 // structure, so that it will persist if we fail.
3239 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3240 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241
Douglas Gregor51c56d62009-12-14 20:49:26 +00003242 // Determine whether we are allowed to call explicit constructors or
3243 // explicit conversion operators.
3244 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3245 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003246 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003247
3248 // The type we're constructing needs to be complete.
3249 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003250 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003251 return;
3252 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003253
Douglas Gregor51c56d62009-12-14 20:49:26 +00003254 // The type we're converting to is a class type. Enumerate its constructors
3255 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003256 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003257 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003258 CXXRecordDecl *DestRecordDecl
3259 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260
Douglas Gregor51c56d62009-12-14 20:49:26 +00003261 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003262 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003263 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003264 NamedDecl *D = *Con;
3265 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003266 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003267
Douglas Gregor51c56d62009-12-14 20:49:26 +00003268 // Find the constructor (which may be a template).
3269 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003270 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003271 if (ConstructorTmpl)
3272 Constructor = cast<CXXConstructorDecl>(
3273 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003274 else {
John McCall9aa472c2010-03-19 07:35:19 +00003275 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003276
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003277 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003278 // suppress user-defined conversions on the arguments.
3279 // FIXME: Move constructors?
3280 if (Kind.getKind() == InitializationKind::IK_Copy &&
3281 Constructor->isCopyConstructor())
3282 SuppressUserConversions = true;
3283 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003284
Douglas Gregor51c56d62009-12-14 20:49:26 +00003285 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003286 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003287 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003288 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003289 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003290 Args, NumArgs, CandidateSet,
3291 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003292 else
John McCall9aa472c2010-03-19 07:35:19 +00003293 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003294 Args, NumArgs, CandidateSet,
3295 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003296 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003297 }
3298
Douglas Gregor51c56d62009-12-14 20:49:26 +00003299 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003300
3301 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003302 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003304 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003305 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003306 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003307 Result);
3308 return;
3309 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003310
3311 // C++0x [dcl.init]p6:
3312 // If a program calls for the default initialization of an object
3313 // of a const-qualified type T, T shall be a class type with a
3314 // user-provided default constructor.
3315 if (Kind.getKind() == InitializationKind::IK_Default &&
3316 Entity.getType().isConstQualified() &&
3317 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3318 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3319 return;
3320 }
3321
Douglas Gregor51c56d62009-12-14 20:49:26 +00003322 // Add the constructor initialization step. Any cv-qualification conversion is
3323 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003324 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003325 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003326 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003327 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003328}
3329
Douglas Gregor71d17402009-12-15 00:01:57 +00003330/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003332 const InitializedEntity &Entity,
3333 const InitializationKind &Kind,
3334 InitializationSequence &Sequence) {
3335 // C++ [dcl.init]p5:
3336 //
3337 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003338 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003339
Douglas Gregor71d17402009-12-15 00:01:57 +00003340 // -- if T is an array type, then each element is value-initialized;
3341 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3342 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003343
Douglas Gregor71d17402009-12-15 00:01:57 +00003344 if (const RecordType *RT = T->getAs<RecordType>()) {
3345 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3346 // -- if T is a class type (clause 9) with a user-declared
3347 // constructor (12.1), then the default constructor for T is
3348 // called (and the initialization is ill-formed if T has no
3349 // accessible default constructor);
3350 //
3351 // FIXME: we really want to refer to a single subobject of the array,
3352 // but Entity doesn't have a way to capture that (yet).
3353 if (ClassDecl->hasUserDeclaredConstructor())
3354 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003355
Douglas Gregor16006c92009-12-16 18:50:27 +00003356 // -- if T is a (possibly cv-qualified) non-union class type
3357 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003358 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003359 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003360 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003361 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003362 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003363 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003364 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003365 }
3366 }
3367
Douglas Gregord6542d82009-12-22 15:35:07 +00003368 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003369}
3370
Douglas Gregor99a2e602009-12-16 01:38:02 +00003371/// \brief Attempt default initialization (C++ [dcl.init]p6).
3372static void TryDefaultInitialization(Sema &S,
3373 const InitializedEntity &Entity,
3374 const InitializationKind &Kind,
3375 InitializationSequence &Sequence) {
3376 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377
Douglas Gregor99a2e602009-12-16 01:38:02 +00003378 // C++ [dcl.init]p6:
3379 // To default-initialize an object of type T means:
3380 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003381 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3382
Douglas Gregor99a2e602009-12-16 01:38:02 +00003383 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3384 // constructor for T is called (and the initialization is ill-formed if
3385 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003386 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003387 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3388 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003389 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390
Douglas Gregor99a2e602009-12-16 01:38:02 +00003391 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392
Douglas Gregor99a2e602009-12-16 01:38:02 +00003393 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003394 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003395 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003396 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003397 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003398 return;
3399 }
3400
3401 // If the destination type has a lifetime property, zero-initialize it.
3402 if (DestType.getQualifiers().hasObjCLifetime()) {
3403 Sequence.AddZeroInitializationStep(Entity.getType());
3404 return;
3405 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003406}
3407
Douglas Gregor20093b42009-12-09 23:02:17 +00003408/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3409/// which enumerates all conversion functions and performs overload resolution
3410/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003411static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003412 const InitializedEntity &Entity,
3413 const InitializationKind &Kind,
3414 Expr *Initializer,
3415 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003416 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003417 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3418 QualType SourceType = Initializer->getType();
3419 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3420 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003421
Douglas Gregor4a520a22009-12-14 17:27:33 +00003422 // Build the candidate set directly in the initialization sequence
3423 // structure, so that it will persist if we fail.
3424 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3425 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003426
Douglas Gregor4a520a22009-12-14 17:27:33 +00003427 // Determine whether we are allowed to call explicit constructors or
3428 // explicit conversion operators.
3429 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003430
Douglas Gregor4a520a22009-12-14 17:27:33 +00003431 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3432 // The type we're converting to is a class type. Enumerate its constructors
3433 // to see if there is a suitable conversion.
3434 CXXRecordDecl *DestRecordDecl
3435 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003436
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003437 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003438 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003439 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003440 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003441 Con != ConEnd; ++Con) {
3442 NamedDecl *D = *Con;
3443 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003444
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003445 // Find the constructor (which may be a template).
3446 CXXConstructorDecl *Constructor = 0;
3447 FunctionTemplateDecl *ConstructorTmpl
3448 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003449 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003450 Constructor = cast<CXXConstructorDecl>(
3451 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003452 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003453 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003454
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003455 if (!Constructor->isInvalidDecl() &&
3456 Constructor->isConvertingConstructor(AllowExplicit)) {
3457 if (ConstructorTmpl)
3458 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3459 /*ExplicitArgs*/ 0,
3460 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003461 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003462 else
3463 S.AddOverloadCandidate(Constructor, FoundDecl,
3464 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003465 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003467 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003468 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003469 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003470
3471 SourceLocation DeclLoc = Initializer->getLocStart();
3472
Douglas Gregor4a520a22009-12-14 17:27:33 +00003473 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3474 // The type we're converting from is a class type, enumerate its conversion
3475 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003476
Eli Friedman33c2da92009-12-20 22:12:03 +00003477 // We can only enumerate the conversion functions for a complete type; if
3478 // the type isn't complete, simply skip this step.
3479 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3480 CXXRecordDecl *SourceRecordDecl
3481 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003482
John McCalleec51cf2010-01-20 00:46:10 +00003483 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003484 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003485 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003486 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003487 I != E; ++I) {
3488 NamedDecl *D = *I;
3489 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3490 if (isa<UsingShadowDecl>(D))
3491 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003492
Eli Friedman33c2da92009-12-20 22:12:03 +00003493 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3494 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003495 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003496 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003497 else
John McCall32daa422010-03-31 01:36:47 +00003498 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003499
Eli Friedman33c2da92009-12-20 22:12:03 +00003500 if (AllowExplicit || !Conv->isExplicit()) {
3501 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003502 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003503 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003504 CandidateSet);
3505 else
John McCall9aa472c2010-03-19 07:35:19 +00003506 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003507 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003508 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003509 }
3510 }
3511 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003512
3513 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003514 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003515 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003516 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003517 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003518 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003519 Result);
3520 return;
3521 }
John McCall1d318332010-01-12 00:44:57 +00003522
Douglas Gregor4a520a22009-12-14 17:27:33 +00003523 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003524 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003525
Douglas Gregor4a520a22009-12-14 17:27:33 +00003526 if (isa<CXXConstructorDecl>(Function)) {
3527 // Add the user-defined conversion step. Any cv-qualification conversion is
3528 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003529 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003530 return;
3531 }
3532
3533 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003534 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003535 if (ConvType->getAs<RecordType>()) {
3536 // If we're converting to a class type, there may be an copy if
3537 // the resulting temporary object (possible to create an object of
3538 // a base class type). That copy is not a separate conversion, so
3539 // we just make a note of the actual destination type (possibly a
3540 // base class of the type returned by the conversion function) and
3541 // let the user-defined conversion step handle the conversion.
3542 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3543 return;
3544 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003545
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003546 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003547
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003548 // If the conversion following the call to the conversion function
3549 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003550 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3551 Best->FinalConversion.Third) {
3552 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003553 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003554 ICS.Standard = Best->FinalConversion;
3555 Sequence.AddConversionSequenceStep(ICS, DestType);
3556 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003557}
3558
John McCallf85e1932011-06-15 23:02:42 +00003559/// The non-zero enum values here are indexes into diagnostic alternatives.
3560enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3561
3562/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003563static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3564 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003565 // Skip parens.
3566 e = e->IgnoreParens();
3567
3568 // Skip address-of nodes.
3569 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3570 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003571 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003572
3573 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003574 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3575 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003576 case CK_Dependent:
3577 case CK_BitCast:
3578 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003579 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003580 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003581
3582 case CK_ArrayToPointerDecay:
3583 return IIK_nonscalar;
3584
3585 case CK_NullToPointer:
3586 return IIK_okay;
3587
3588 default:
3589 break;
3590 }
3591
3592 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003593 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3594 if (!isAddressOf) return IIK_nonlocal;
3595
3596 VarDecl *var;
3597 if (isa<DeclRefExpr>(e)) {
3598 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3599 if (!var) return IIK_nonlocal;
3600 } else {
3601 var = cast<BlockDeclRefExpr>(e)->getDecl();
3602 }
3603
3604 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003605
3606 // If we have a conditional operator, check both sides.
3607 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003608 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003609 return iik;
3610
John McCallc03fa492011-06-27 23:59:58 +00003611 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003612
3613 // These are never scalar.
3614 } else if (isa<ArraySubscriptExpr>(e)) {
3615 return IIK_nonscalar;
3616
3617 // Otherwise, it needs to be a null pointer constant.
3618 } else {
3619 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3620 ? IIK_okay : IIK_nonlocal);
3621 }
3622
3623 return IIK_nonlocal;
3624}
3625
3626/// Check whether the given expression is a valid operand for an
3627/// indirect copy/restore.
3628static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3629 assert(src->isRValue());
3630
John McCallc03fa492011-06-27 23:59:58 +00003631 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003632 if (iik == IIK_okay) return;
3633
3634 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3635 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3636 << src->getSourceRange();
3637}
3638
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003639/// \brief Determine whether we have compatible array types for the
3640/// purposes of GNU by-copy array initialization.
3641static bool hasCompatibleArrayTypes(ASTContext &Context,
3642 const ArrayType *Dest,
3643 const ArrayType *Source) {
3644 // If the source and destination array types are equivalent, we're
3645 // done.
3646 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3647 return true;
3648
3649 // Make sure that the element types are the same.
3650 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3651 return false;
3652
3653 // The only mismatch we allow is when the destination is an
3654 // incomplete array type and the source is a constant array type.
3655 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3656}
3657
John McCallf85e1932011-06-15 23:02:42 +00003658static bool tryObjCWritebackConversion(Sema &S,
3659 InitializationSequence &Sequence,
3660 const InitializedEntity &Entity,
3661 Expr *Initializer) {
3662 bool ArrayDecay = false;
3663 QualType ArgType = Initializer->getType();
3664 QualType ArgPointee;
3665 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3666 ArrayDecay = true;
3667 ArgPointee = ArgArrayType->getElementType();
3668 ArgType = S.Context.getPointerType(ArgPointee);
3669 }
3670
3671 // Handle write-back conversion.
3672 QualType ConvertedArgType;
3673 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3674 ConvertedArgType))
3675 return false;
3676
3677 // We should copy unless we're passing to an argument explicitly
3678 // marked 'out'.
3679 bool ShouldCopy = true;
3680 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3681 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3682
3683 // Do we need an lvalue conversion?
3684 if (ArrayDecay || Initializer->isGLValue()) {
3685 ImplicitConversionSequence ICS;
3686 ICS.setStandard();
3687 ICS.Standard.setAsIdentityConversion();
3688
3689 QualType ResultType;
3690 if (ArrayDecay) {
3691 ICS.Standard.First = ICK_Array_To_Pointer;
3692 ResultType = S.Context.getPointerType(ArgPointee);
3693 } else {
3694 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3695 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3696 }
3697
3698 Sequence.AddConversionSequenceStep(ICS, ResultType);
3699 }
3700
3701 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3702 return true;
3703}
3704
Douglas Gregor20093b42009-12-09 23:02:17 +00003705InitializationSequence::InitializationSequence(Sema &S,
3706 const InitializedEntity &Entity,
3707 const InitializationKind &Kind,
3708 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003709 unsigned NumArgs)
3710 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003711 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003712
Douglas Gregor20093b42009-12-09 23:02:17 +00003713 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003714 // The semantics of initializers are as follows. The destination type is
3715 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003716 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003717 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003718 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003719 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003720
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003721 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003722 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3723 SequenceKind = DependentSequence;
3724 return;
3725 }
3726
Sebastian Redl7491c492011-06-05 13:59:11 +00003727 // Almost everything is a normal sequence.
3728 setSequenceKind(NormalSequence);
3729
John McCall241d5582010-12-07 22:54:16 +00003730 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003731 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3732 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3733 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003734 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003735 return;
3736 }
3737 Args[I] = Result.take();
3738 }
John McCall241d5582010-12-07 22:54:16 +00003739
Douglas Gregor20093b42009-12-09 23:02:17 +00003740 QualType SourceType;
3741 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003742 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003743 Initializer = Args[0];
3744 if (!isa<InitListExpr>(Initializer))
3745 SourceType = Initializer->getType();
3746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003747
3748 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003749 // list-initialized (8.5.4).
3750 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003751 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003752 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003753 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003754
Douglas Gregor20093b42009-12-09 23:02:17 +00003755 // - If the destination type is a reference type, see 8.5.3.
3756 if (DestType->isReferenceType()) {
3757 // C++0x [dcl.init.ref]p1:
3758 // A variable declared to be a T& or T&&, that is, "reference to type T"
3759 // (8.3.2), shall be initialized by an object, or function, of type T or
3760 // by an object that can be converted into a T.
3761 // (Therefore, multiple arguments are not permitted.)
3762 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003763 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003764 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003765 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003766 return;
3767 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003768
Douglas Gregor20093b42009-12-09 23:02:17 +00003769 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003770 if (Kind.getKind() == InitializationKind::IK_Value ||
3771 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003772 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003773 return;
3774 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003775
Douglas Gregor99a2e602009-12-16 01:38:02 +00003776 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003777 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003778 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003779 return;
3780 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003781
John McCallce6c9b72011-02-21 07:22:22 +00003782 // - If the destination type is an array of characters, an array of
3783 // char16_t, an array of char32_t, or an array of wchar_t, and the
3784 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003786 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003787 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3788 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003789 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003790 return;
3791 }
3792
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003793 // Note: as an GNU C extension, we allow initialization of an
3794 // array from a compound literal that creates an array of the same
3795 // type, so long as the initializer has no side effects.
3796 if (!S.getLangOptions().CPlusPlus && Initializer &&
3797 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3798 Initializer->getType()->isArrayType()) {
3799 const ArrayType *SourceAT
3800 = Context.getAsArrayType(Initializer->getType());
3801 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003802 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003803 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003804 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003805 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003806 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003807 }
3808 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003809 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003810 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003811 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003812
Douglas Gregor20093b42009-12-09 23:02:17 +00003813 return;
3814 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003815
John McCallf85e1932011-06-15 23:02:42 +00003816 // Determine whether we should consider writeback conversions for
3817 // Objective-C ARC.
3818 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3819 Entity.getKind() == InitializedEntity::EK_Parameter;
3820
3821 // We're at the end of the line for C: it's either a write-back conversion
3822 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003823 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003824 // If allowed, check whether this is an Objective-C writeback conversion.
3825 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003826 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003827 return;
3828 }
3829
3830 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003831 AddCAssignmentStep(DestType);
3832 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003833 return;
3834 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003835
John McCallf85e1932011-06-15 23:02:42 +00003836 assert(S.getLangOptions().CPlusPlus);
3837
Douglas Gregor20093b42009-12-09 23:02:17 +00003838 // - If the destination type is a (possibly cv-qualified) class type:
3839 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003840 // - If the initialization is direct-initialization, or if it is
3841 // copy-initialization where the cv-unqualified version of the
3842 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003843 // class of the destination, constructors are considered. [...]
3844 if (Kind.getKind() == InitializationKind::IK_Direct ||
3845 (Kind.getKind() == InitializationKind::IK_Copy &&
3846 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3847 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003848 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003849 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003850 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003851 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003852 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003853 // used) to a derived class thereof are enumerated as described in
3854 // 13.3.1.4, and the best one is chosen through overload resolution
3855 // (13.3).
3856 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003857 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003858 return;
3859 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003860
Douglas Gregor99a2e602009-12-16 01:38:02 +00003861 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003862 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003863 return;
3864 }
3865 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003866
3867 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003868 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003869 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003870 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3871 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003872 return;
3873 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003874
Douglas Gregor20093b42009-12-09 23:02:17 +00003875 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003876 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003877 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003878 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003879 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003880
3881 ImplicitConversionSequence ICS
3882 = S.TryImplicitConversion(Initializer, Entity.getType(),
3883 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003884 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003885 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003886 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3887 allowObjCWritebackConversion);
3888
3889 if (ICS.isStandard() &&
3890 ICS.Standard.Second == ICK_Writeback_Conversion) {
3891 // Objective-C ARC writeback conversion.
3892
3893 // We should copy unless we're passing to an argument explicitly
3894 // marked 'out'.
3895 bool ShouldCopy = true;
3896 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3897 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3898
3899 // If there was an lvalue adjustment, add it as a separate conversion.
3900 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3901 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3902 ImplicitConversionSequence LvalueICS;
3903 LvalueICS.setStandard();
3904 LvalueICS.Standard.setAsIdentityConversion();
3905 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3906 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003907 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003908 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003909
3910 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003911 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003912 DeclAccessPair dap;
3913 if (Initializer->getType() == Context.OverloadTy &&
3914 !S.ResolveAddressOfOverloadedFunction(Initializer
3915 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003916 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003917 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003918 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003919 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003920 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003921
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003922 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003923 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003924}
3925
3926InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003927 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003928 StepEnd = Steps.end();
3929 Step != StepEnd; ++Step)
3930 Step->Destroy();
3931}
3932
3933//===----------------------------------------------------------------------===//
3934// Perform initialization
3935//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003936static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003937getAssignmentAction(const InitializedEntity &Entity) {
3938 switch(Entity.getKind()) {
3939 case InitializedEntity::EK_Variable:
3940 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003941 case InitializedEntity::EK_Exception:
3942 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003943 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003944 return Sema::AA_Initializing;
3945
3946 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003947 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003948 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3949 return Sema::AA_Sending;
3950
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003951 return Sema::AA_Passing;
3952
3953 case InitializedEntity::EK_Result:
3954 return Sema::AA_Returning;
3955
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003956 case InitializedEntity::EK_Temporary:
3957 // FIXME: Can we tell apart casting vs. converting?
3958 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003959
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003960 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003961 case InitializedEntity::EK_ArrayElement:
3962 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00003963 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003964 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003965 return Sema::AA_Initializing;
3966 }
3967
3968 return Sema::AA_Converting;
3969}
3970
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003971/// \brief Whether we should binding a created object as a temporary when
3972/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003973static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003974 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003975 case InitializedEntity::EK_ArrayElement:
3976 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003977 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003978 case InitializedEntity::EK_New:
3979 case InitializedEntity::EK_Variable:
3980 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003981 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003982 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00003983 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003984 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003985 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003986 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003987
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003988 case InitializedEntity::EK_Parameter:
3989 case InitializedEntity::EK_Temporary:
3990 return true;
3991 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003992
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003993 llvm_unreachable("missed an InitializedEntity kind?");
3994}
3995
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003996/// \brief Whether the given entity, when initialized with an object
3997/// created for that initialization, requires destruction.
3998static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3999 switch (Entity.getKind()) {
4000 case InitializedEntity::EK_Member:
4001 case InitializedEntity::EK_Result:
4002 case InitializedEntity::EK_New:
4003 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004004 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004005 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004006 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004007 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004008 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004009
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004010 case InitializedEntity::EK_Variable:
4011 case InitializedEntity::EK_Parameter:
4012 case InitializedEntity::EK_Temporary:
4013 case InitializedEntity::EK_ArrayElement:
4014 case InitializedEntity::EK_Exception:
4015 return true;
4016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004017
4018 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004019}
4020
Douglas Gregor523d46a2010-04-18 07:40:54 +00004021/// \brief Make a (potentially elidable) temporary copy of the object
4022/// provided by the given initializer by calling the appropriate copy
4023/// constructor.
4024///
4025/// \param S The Sema object used for type-checking.
4026///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004027/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004028/// the type of the initializer expression or a superclass thereof.
4029///
4030/// \param Enter The entity being initialized.
4031///
4032/// \param CurInit The initializer expression.
4033///
4034/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4035/// is permitted in C++03 (but not C++0x) when binding a reference to
4036/// an rvalue.
4037///
4038/// \returns An expression that copies the initializer expression into
4039/// a temporary object, or an error expression if a copy could not be
4040/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004041static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004042 QualType T,
4043 const InitializedEntity &Entity,
4044 ExprResult CurInit,
4045 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004046 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004047 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004048 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004049 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004050 Class = cast<CXXRecordDecl>(Record->getDecl());
4051 if (!Class)
4052 return move(CurInit);
4053
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004054 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004055 // When certain criteria are met, an implementation is allowed to
4056 // omit the copy/move construction of a class object, even if the
4057 // copy/move constructor and/or destructor for the object have
4058 // side effects. [...]
4059 // - when a temporary class object that has not been bound to a
4060 // reference (12.2) would be copied/moved to a class object
4061 // with the same cv-unqualified type, the copy/move operation
4062 // can be omitted by constructing the temporary object
4063 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004065 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004066 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004067 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004068 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004069 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004070 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004071 switch (Entity.getKind()) {
4072 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004073 Loc = Entity.getReturnLoc();
4074 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004076 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004077 Loc = Entity.getThrowLoc();
4078 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004079
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004080 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004081 Loc = Entity.getDecl()->getLocation();
4082 break;
4083
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004084 case InitializedEntity::EK_ArrayElement:
4085 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004086 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004087 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00004088 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004089 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004090 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004091 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004092 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004093 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00004094 Loc = CurInitExpr->getLocStart();
4095 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004096 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004097
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004098 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004099 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4100 return move(CurInit);
4101
Douglas Gregorcc15f012011-01-21 19:38:21 +00004102 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004103 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00004104 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00004105 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004106 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00004107 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004108 // C++0x [dcl.init]p16, second bullet to class types, this
4109 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00004110 CXXConstructorDecl *Constructor = 0;
4111
4112 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00004113 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00004114 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00004115 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004116 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00004117 continue;
4118
4119 DeclAccessPair FoundDecl
4120 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4121 S.AddOverloadCandidate(Constructor, FoundDecl,
4122 &CurInitExpr, 1, CandidateSet);
4123 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004124 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00004125
4126 // Handle constructor templates.
4127 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4128 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004129 continue;
John McCall9aa472c2010-03-19 07:35:19 +00004130
Douglas Gregor6493cc52010-11-08 17:16:59 +00004131 Constructor = cast<CXXConstructorDecl>(
4132 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004133 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00004134 continue;
4135
4136 // FIXME: Do we need to limit this to copy-constructor-like
4137 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00004138 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00004139 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4140 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4141 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00004142 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004143
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004144 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004145 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004146 case OR_Success:
4147 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004148
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004149 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004150 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4151 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4152 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004153 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004154 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004155 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004156 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004157 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004158 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004159
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004160 case OR_Ambiguous:
4161 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004162 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004163 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004164 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004165 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004166
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004167 case OR_Deleted:
4168 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004169 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004170 << CurInitExpr->getSourceRange();
4171 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004172 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004173 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004174 }
4175
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004176 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004177 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004178 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004179
Anders Carlsson9a68a672010-04-21 18:47:17 +00004180 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004181 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004182
4183 if (IsExtraneousCopy) {
4184 // If this is a totally extraneous copy for C++03 reference
4185 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004186 // expression. We don't generate an (elided) copy operation here
4187 // because doing so would require us to pass down a flag to avoid
4188 // infinite recursion, where each step adds another extraneous,
4189 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004190
Douglas Gregor2559a702010-04-18 07:57:34 +00004191 // Instantiate the default arguments of any extra parameters in
4192 // the selected copy constructor, as if we were going to create a
4193 // proper call to the copy constructor.
4194 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4195 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4196 if (S.RequireCompleteType(Loc, Parm->getType(),
4197 S.PDiag(diag::err_call_incomplete_argument)))
4198 break;
4199
4200 // Build the default argument expression; we don't actually care
4201 // if this succeeds or not, because this routine will complain
4202 // if there was a problem.
4203 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4204 }
4205
Douglas Gregor523d46a2010-04-18 07:40:54 +00004206 return S.Owned(CurInitExpr);
4207 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004208
Chandler Carruth25ca4212011-02-25 19:41:05 +00004209 S.MarkDeclarationReferenced(Loc, Constructor);
4210
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004211 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004212 // constructor call (we might have derived-to-base conversions, or
4213 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004214 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004215 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004216 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004217
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004218 // Actually perform the constructor call.
4219 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004220 move_arg(ConstructorArgs),
4221 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004222 CXXConstructExpr::CK_Complete,
4223 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004224
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004225 // If we're supposed to bind temporaries, do so.
4226 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4227 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4228 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004229}
Douglas Gregor20093b42009-12-09 23:02:17 +00004230
Douglas Gregora41a8c52010-04-22 00:20:18 +00004231void InitializationSequence::PrintInitLocationNote(Sema &S,
4232 const InitializedEntity &Entity) {
4233 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4234 if (Entity.getDecl()->getLocation().isInvalid())
4235 return;
4236
4237 if (Entity.getDecl()->getDeclName())
4238 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4239 << Entity.getDecl()->getDeclName();
4240 else
4241 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4242 }
4243}
4244
Sebastian Redl3b802322011-07-14 19:07:55 +00004245static bool isReferenceBinding(const InitializationSequence::Step &s) {
4246 return s.Kind == InitializationSequence::SK_BindReference ||
4247 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4248}
4249
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004250ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004251InitializationSequence::Perform(Sema &S,
4252 const InitializedEntity &Entity,
4253 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004254 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004255 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004256 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004257 unsigned NumArgs = Args.size();
4258 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004259 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004260 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004261
Sebastian Redl7491c492011-06-05 13:59:11 +00004262 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004263 // If the declaration is a non-dependent, incomplete array type
4264 // that has an initializer, then its type will be completed once
4265 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004266 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004267 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004268 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004269 if (const IncompleteArrayType *ArrayT
4270 = S.Context.getAsIncompleteArrayType(DeclType)) {
4271 // FIXME: We don't currently have the ability to accurately
4272 // compute the length of an initializer list without
4273 // performing full type-checking of the initializer list
4274 // (since we have to determine where braces are implicitly
4275 // introduced and such). So, we fall back to making the array
4276 // type a dependently-sized array type with no specified
4277 // bound.
4278 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4279 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004280
Douglas Gregord87b61f2009-12-10 17:56:55 +00004281 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004282 if (DeclaratorDecl *DD = Entity.getDecl()) {
4283 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4284 TypeLoc TL = TInfo->getTypeLoc();
4285 if (IncompleteArrayTypeLoc *ArrayLoc
4286 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4287 Brackets = ArrayLoc->getBracketsRange();
4288 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004289 }
4290
4291 *ResultType
4292 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4293 /*NumElts=*/0,
4294 ArrayT->getSizeModifier(),
4295 ArrayT->getIndexTypeCVRQualifiers(),
4296 Brackets);
4297 }
4298
4299 }
4300 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004301 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4302 Kind.isExplicitCast());
4303 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004304 }
4305
Sebastian Redl7491c492011-06-05 13:59:11 +00004306 // No steps means no initialization.
4307 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004308 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309
Douglas Gregord6542d82009-12-22 15:35:07 +00004310 QualType DestType = Entity.getType().getNonReferenceType();
4311 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004312 // the same as Entity.getDecl()->getType() in cases involving type merging,
4313 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004314 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004315 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004316 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004317
John McCall60d7b3a2010-08-24 06:29:42 +00004318 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004319
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004320 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004321 // grab the only argument out the Args and place it into the "current"
4322 // initializer.
4323 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004324 case SK_ResolveAddressOfOverloadedFunction:
4325 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004326 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004327 case SK_CastDerivedToBaseLValue:
4328 case SK_BindReference:
4329 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004330 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004331 case SK_UserConversion:
4332 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004333 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004334 case SK_QualificationConversionRValue:
4335 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004336 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004337 case SK_ListInitialization:
4338 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004339 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004340 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004341 case SK_ArrayInit:
4342 case SK_PassByIndirectCopyRestore:
4343 case SK_PassByIndirectRestore:
4344 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004345 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004346 CurInit = Args.get()[0];
4347 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004348
4349 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004350 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4351 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4352 if (CurInit.isInvalid())
4353 return ExprError();
4354 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004355 break;
John McCallf6a16482010-12-04 03:47:34 +00004356 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004357
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004358 case SK_ConstructorInitialization:
4359 case SK_ZeroInitialization:
4360 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004361 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004362
4363 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004364 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004365 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004366 for (step_iterator Step = step_begin(), StepEnd = step_end();
4367 Step != StepEnd; ++Step) {
4368 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004369 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004370
John Wiegley429bb272011-04-08 18:41:53 +00004371 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004372
Douglas Gregor20093b42009-12-09 23:02:17 +00004373 switch (Step->Kind) {
4374 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004375 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004376 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004377 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004378 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004379 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004380 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004381 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004382 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004383
Douglas Gregor20093b42009-12-09 23:02:17 +00004384 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004385 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004386 case SK_CastDerivedToBaseLValue: {
4387 // We have a derived-to-base cast that produces either an rvalue or an
4388 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004389
John McCallf871d0c2010-08-07 06:22:56 +00004390 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004391
Douglas Gregor20093b42009-12-09 23:02:17 +00004392 // Casts to inaccessible base classes are allowed with C-style casts.
4393 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4394 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004395 CurInit.get()->getLocStart(),
4396 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004397 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004398 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004399
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004400 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4401 QualType T = SourceType;
4402 if (const PointerType *Pointer = T->getAs<PointerType>())
4403 T = Pointer->getPointeeType();
4404 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004405 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004406 cast<CXXRecordDecl>(RecordTy->getDecl()));
4407 }
4408
John McCall5baba9d2010-08-25 10:28:54 +00004409 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004410 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004411 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004412 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004413 VK_XValue :
4414 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004415 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4416 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004417 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004418 CurInit.get(),
4419 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004420 break;
4421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004422
Douglas Gregor20093b42009-12-09 23:02:17 +00004423 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004424 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004425 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4426 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004427 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004428 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004429 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004430 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004431 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004432 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004433
John Wiegley429bb272011-04-08 18:41:53 +00004434 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004435 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004436 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4437 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004438 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004439 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004440 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004441 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004442
Douglas Gregor20093b42009-12-09 23:02:17 +00004443 // Reference binding does not have any corresponding ASTs.
4444
4445 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004446 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004447 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004448
Douglas Gregor20093b42009-12-09 23:02:17 +00004449 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004450
Douglas Gregor20093b42009-12-09 23:02:17 +00004451 case SK_BindReferenceToTemporary:
4452 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004453 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004454 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004455
Douglas Gregor03e80032011-06-21 17:03:29 +00004456 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004457 CurInit = new (S.Context) MaterializeTemporaryExpr(
4458 Entity.getType().getNonReferenceType(),
4459 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004460 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004461
4462 // If we're binding to an Objective-C object that has lifetime, we
4463 // need cleanups.
4464 if (S.getLangOptions().ObjCAutoRefCount &&
4465 CurInit.get()->getType()->isObjCLifetimeType())
4466 S.ExprNeedsCleanups = true;
4467
Douglas Gregor20093b42009-12-09 23:02:17 +00004468 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004469
Douglas Gregor523d46a2010-04-18 07:40:54 +00004470 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004471 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004472 /*IsExtraneousCopy=*/true);
4473 break;
4474
Douglas Gregor20093b42009-12-09 23:02:17 +00004475 case SK_UserConversion: {
4476 // We have a user-defined conversion that invokes either a constructor
4477 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004478 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004479 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004480 FunctionDecl *Fn = Step->Function.Function;
4481 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004482 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004483 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004484 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004485 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004486 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004487 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004488 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004489
Douglas Gregor20093b42009-12-09 23:02:17 +00004490 // Determine the arguments required to actually perform the constructor
4491 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004492 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004493 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004494 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004495 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004496 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004497
Douglas Gregor20093b42009-12-09 23:02:17 +00004498 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004500 move_arg(ConstructorArgs),
4501 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004502 CXXConstructExpr::CK_Complete,
4503 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004504 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004505 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004506
Anders Carlsson9a68a672010-04-21 18:47:17 +00004507 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004508 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004509 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510
John McCall2de56d12010-08-25 11:45:40 +00004511 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004512 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4513 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4514 S.IsDerivedFrom(SourceType, Class))
4515 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004516
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004517 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004518 } else {
4519 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004520 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004521 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004522 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004523 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004524 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004525
4526 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004527 // derived-to-base conversion? I believe the answer is "no", because
4528 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004529 ExprResult CurInitExprRes =
4530 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4531 FoundFn, Conversion);
4532 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004533 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004534 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004535
Douglas Gregor20093b42009-12-09 23:02:17 +00004536 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004537 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004538 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004539 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540
John McCall2de56d12010-08-25 11:45:40 +00004541 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004542
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004543 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004544 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004545
Sebastian Redl3b802322011-07-14 19:07:55 +00004546 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004547 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004548 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004549 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004550 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004551 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004552 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004553 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004554 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004555 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004556 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4557 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004558 }
4559 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004560
Sebastian Redl906082e2010-07-20 04:20:21 +00004561 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004562 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004563 CurInit.get()->getType(),
4564 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004565 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004566
Douglas Gregor2f599792010-04-02 18:24:57 +00004567 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004568 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4569 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004570
Douglas Gregor20093b42009-12-09 23:02:17 +00004571 break;
4572 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004573
Douglas Gregor20093b42009-12-09 23:02:17 +00004574 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004575 case SK_QualificationConversionXValue:
4576 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004577 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004578 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004579 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004580 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004581 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004582 VK_XValue :
4583 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004584 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004585 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004586 }
4587
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004588 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004589 Sema::CheckedConversionKind CCK
4590 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4591 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4592 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4593 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004594 ExprResult CurInitExprRes =
4595 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004596 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004597 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004598 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004599 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004600 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004601 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004602
Douglas Gregord87b61f2009-12-10 17:56:55 +00004603 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004604 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004605 QualType Ty = Step->Type;
Sebastian Redl14b0c192011-09-24 17:48:00 +00004606 InitListChecker PerformInitList(S, Entity, InitList,
4607 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false);
4608 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00004609 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004610
4611 CurInit.release();
Sebastian Redl14b0c192011-09-24 17:48:00 +00004612 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004613 break;
4614 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004615
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004616 case SK_ListConstructorCall:
4617 assert(false && "List constructor calls not yet supported.");
4618
Douglas Gregor51c56d62009-12-14 20:49:26 +00004619 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004620 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004621 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004622 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004623
Douglas Gregor51c56d62009-12-14 20:49:26 +00004624 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004625 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004626 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4627 ? Kind.getEqualLoc()
4628 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004629
4630 if (Kind.getKind() == InitializationKind::IK_Default) {
4631 // Force even a trivial, implicit default constructor to be
4632 // semantically checked. We do this explicitly because we don't build
4633 // the definition for completely trivial constructors.
4634 CXXRecordDecl *ClassDecl = Constructor->getParent();
4635 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004636 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004637 ClassDecl->hasTrivialDefaultConstructor() &&
4638 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004639 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4640 }
4641
Douglas Gregor51c56d62009-12-14 20:49:26 +00004642 // Determine the arguments required to actually perform the constructor
4643 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004644 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004645 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004646 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004647
4648
Douglas Gregor91be6f52010-03-02 17:18:33 +00004649 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004650 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004651 (Kind.getKind() == InitializationKind::IK_Direct ||
4652 Kind.getKind() == InitializationKind::IK_Value)) {
4653 // An explicitly-constructed temporary, e.g., X(1, 2).
4654 unsigned NumExprs = ConstructorArgs.size();
4655 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004656 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004657 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658
Douglas Gregorab6677e2010-09-08 00:15:04 +00004659 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4660 if (!TSInfo)
4661 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662
Douglas Gregor91be6f52010-03-02 17:18:33 +00004663 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4664 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004665 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004666 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004667 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004668 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004669 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004670 } else {
4671 CXXConstructExpr::ConstructionKind ConstructKind =
4672 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004673
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004674 if (Entity.getKind() == InitializedEntity::EK_Base) {
4675 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004676 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004677 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004678 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004679 ConstructKind = CXXConstructExpr::CK_Delegating;
4680 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004681
Chandler Carruth428edaf2010-10-25 08:47:36 +00004682 // Only get the parenthesis range if it is a direct construction.
4683 SourceRange parenRange =
4684 Kind.getKind() == InitializationKind::IK_Direct ?
4685 Kind.getParenRange() : SourceRange();
4686
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004687 // If the entity allows NRVO, mark the construction as elidable
4688 // unconditionally.
4689 if (Entity.allowsNRVO())
4690 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4691 Constructor, /*Elidable=*/true,
4692 move_arg(ConstructorArgs),
4693 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004694 ConstructKind,
4695 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004696 else
4697 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004698 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004699 move_arg(ConstructorArgs),
4700 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004701 ConstructKind,
4702 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004703 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004704 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004705 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004706
4707 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004708 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004709 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004710 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004711
Douglas Gregor2f599792010-04-02 18:24:57 +00004712 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004713 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004714
Douglas Gregor51c56d62009-12-14 20:49:26 +00004715 break;
4716 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717
Douglas Gregor71d17402009-12-15 00:01:57 +00004718 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004719 step_iterator NextStep = Step;
4720 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004721 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004722 NextStep->Kind == SK_ConstructorInitialization) {
4723 // The need for zero-initialization is recorded directly into
4724 // the call to the object's constructor within the next step.
4725 ConstructorInitRequiresZeroInit = true;
4726 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4727 S.getLangOptions().CPlusPlus &&
4728 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004729 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4730 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004731 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004732 Kind.getRange().getBegin());
4733
4734 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4735 TSInfo->getType().getNonLValueExprType(S.Context),
4736 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004737 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004738 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004739 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004740 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004741 break;
4742 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004743
4744 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004745 QualType SourceType = CurInit.get()->getType();
4746 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004747 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004748 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4749 if (Result.isInvalid())
4750 return ExprError();
4751 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004752
4753 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004754 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004755 if (ConvTy != Sema::Compatible &&
4756 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004757 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004758 == Sema::Compatible)
4759 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004760 if (CurInitExprRes.isInvalid())
4761 return ExprError();
4762 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004763
Douglas Gregora41a8c52010-04-22 00:20:18 +00004764 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004765 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4766 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004767 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004768 getAssignmentAction(Entity),
4769 &Complained)) {
4770 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004771 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004772 } else if (Complained)
4773 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004774 break;
4775 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004776
4777 case SK_StringInit: {
4778 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004779 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004780 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004781 break;
4782 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004783
4784 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004785 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004786 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004787 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004788 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004789
4790 case SK_ArrayInit:
4791 // Okay: we checked everything before creating this step. Note that
4792 // this is a GNU extension.
4793 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004794 << Step->Type << CurInit.get()->getType()
4795 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004796
4797 // If the destination type is an incomplete array type, update the
4798 // type accordingly.
4799 if (ResultType) {
4800 if (const IncompleteArrayType *IncompleteDest
4801 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4802 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004803 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004804 *ResultType = S.Context.getConstantArrayType(
4805 IncompleteDest->getElementType(),
4806 ConstantSource->getSize(),
4807 ArrayType::Normal, 0);
4808 }
4809 }
4810 }
John McCallf85e1932011-06-15 23:02:42 +00004811 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004812
John McCallf85e1932011-06-15 23:02:42 +00004813 case SK_PassByIndirectCopyRestore:
4814 case SK_PassByIndirectRestore:
4815 checkIndirectCopyRestoreSource(S, CurInit.get());
4816 CurInit = S.Owned(new (S.Context)
4817 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4818 Step->Kind == SK_PassByIndirectCopyRestore));
4819 break;
4820
4821 case SK_ProduceObjCObject:
4822 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00004823 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00004824 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004825 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004826 }
4827 }
John McCall15d7d122010-11-11 03:21:53 +00004828
4829 // Diagnose non-fatal problems with the completed initialization.
4830 if (Entity.getKind() == InitializedEntity::EK_Member &&
4831 cast<FieldDecl>(Entity.getDecl())->isBitField())
4832 S.CheckBitFieldInitialization(Kind.getLocation(),
4833 cast<FieldDecl>(Entity.getDecl()),
4834 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004835
Douglas Gregor20093b42009-12-09 23:02:17 +00004836 return move(CurInit);
4837}
4838
4839//===----------------------------------------------------------------------===//
4840// Diagnose initialization failures
4841//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004842bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004843 const InitializedEntity &Entity,
4844 const InitializationKind &Kind,
4845 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004846 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004847 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004848
Douglas Gregord6542d82009-12-22 15:35:07 +00004849 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004850 switch (Failure) {
4851 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004852 // FIXME: Customize for the initialized entity?
4853 if (NumArgs == 0)
4854 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4855 << DestType.getNonReferenceType();
4856 else // FIXME: diagnostic below could be better!
4857 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4858 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004859 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004860
Douglas Gregor20093b42009-12-09 23:02:17 +00004861 case FK_ArrayNeedsInitList:
4862 case FK_ArrayNeedsInitListOrStringLiteral:
4863 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4864 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4865 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004866
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004867 case FK_ArrayTypeMismatch:
4868 case FK_NonConstantArrayInit:
4869 S.Diag(Kind.getLocation(),
4870 (Failure == FK_ArrayTypeMismatch
4871 ? diag::err_array_init_different_type
4872 : diag::err_array_init_non_constant_array))
4873 << DestType.getNonReferenceType()
4874 << Args[0]->getType()
4875 << Args[0]->getSourceRange();
4876 break;
4877
John McCall6bb80172010-03-30 21:47:33 +00004878 case FK_AddressOfOverloadFailed: {
4879 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004880 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004881 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004882 true,
4883 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004884 break;
John McCall6bb80172010-03-30 21:47:33 +00004885 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004886
Douglas Gregor20093b42009-12-09 23:02:17 +00004887 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004888 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004889 switch (FailedOverloadResult) {
4890 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004891 if (Failure == FK_UserConversionOverloadFailed)
4892 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4893 << Args[0]->getType() << DestType
4894 << Args[0]->getSourceRange();
4895 else
4896 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4897 << DestType << Args[0]->getType()
4898 << Args[0]->getSourceRange();
4899
John McCall120d63c2010-08-24 20:38:10 +00004900 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004901 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004902
Douglas Gregor20093b42009-12-09 23:02:17 +00004903 case OR_No_Viable_Function:
4904 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4905 << Args[0]->getType() << DestType.getNonReferenceType()
4906 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004907 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004908 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004909
Douglas Gregor20093b42009-12-09 23:02:17 +00004910 case OR_Deleted: {
4911 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4912 << Args[0]->getType() << DestType.getNonReferenceType()
4913 << Args[0]->getSourceRange();
4914 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004915 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004916 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4917 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004918 if (Ovl == OR_Deleted) {
4919 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004920 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004921 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004922 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004923 }
4924 break;
4925 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004926
Douglas Gregor20093b42009-12-09 23:02:17 +00004927 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004928 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004929 break;
4930 }
4931 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004932
Douglas Gregor20093b42009-12-09 23:02:17 +00004933 case FK_NonConstLValueReferenceBindingToTemporary:
4934 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004935 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004936 Failure == FK_NonConstLValueReferenceBindingToTemporary
4937 ? diag::err_lvalue_reference_bind_to_temporary
4938 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004939 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004940 << DestType.getNonReferenceType()
4941 << Args[0]->getType()
4942 << Args[0]->getSourceRange();
4943 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004944
Douglas Gregor20093b42009-12-09 23:02:17 +00004945 case FK_RValueReferenceBindingToLValue:
4946 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004947 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004948 << Args[0]->getSourceRange();
4949 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004950
Douglas Gregor20093b42009-12-09 23:02:17 +00004951 case FK_ReferenceInitDropsQualifiers:
4952 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4953 << DestType.getNonReferenceType()
4954 << Args[0]->getType()
4955 << Args[0]->getSourceRange();
4956 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004957
Douglas Gregor20093b42009-12-09 23:02:17 +00004958 case FK_ReferenceInitFailed:
4959 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4960 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004961 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004962 << Args[0]->getType()
4963 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004964 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4965 Args[0]->getType()->isObjCObjectPointerType())
4966 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004967 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004968
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004969 case FK_ConversionFailed: {
4970 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004971 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4972 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004973 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004974 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004975 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004976 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004977 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4978 Args[0]->getType()->isObjCObjectPointerType())
4979 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004980 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004981 }
John Wiegley429bb272011-04-08 18:41:53 +00004982
4983 case FK_ConversionFromPropertyFailed:
4984 // No-op. This error has already been reported.
4985 break;
4986
Douglas Gregord87b61f2009-12-10 17:56:55 +00004987 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004988 SourceRange R;
4989
4990 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004991 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004992 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004993 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004994 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004995
Douglas Gregor19311e72010-09-08 21:40:08 +00004996 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4997 if (Kind.isCStyleOrFunctionalCast())
4998 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4999 << R;
5000 else
5001 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5002 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005003 break;
5004 }
5005
5006 case FK_ReferenceBindingToInitList:
5007 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5008 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5009 break;
5010
5011 case FK_InitListBadDestinationType:
5012 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5013 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5014 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015
Douglas Gregor51c56d62009-12-14 20:49:26 +00005016 case FK_ConstructorOverloadFailed: {
5017 SourceRange ArgsRange;
5018 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005019 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005020 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005021
Douglas Gregor51c56d62009-12-14 20:49:26 +00005022 // FIXME: Using "DestType" for the entity we're printing is probably
5023 // bad.
5024 switch (FailedOverloadResult) {
5025 case OR_Ambiguous:
5026 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5027 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005028 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5029 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005030 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005031
Douglas Gregor51c56d62009-12-14 20:49:26 +00005032 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005033 if (Kind.getKind() == InitializationKind::IK_Default &&
5034 (Entity.getKind() == InitializedEntity::EK_Base ||
5035 Entity.getKind() == InitializedEntity::EK_Member) &&
5036 isa<CXXConstructorDecl>(S.CurContext)) {
5037 // This is implicit default initialization of a member or
5038 // base within a constructor. If no viable function was
5039 // found, notify the user that she needs to explicitly
5040 // initialize this base/member.
5041 CXXConstructorDecl *Constructor
5042 = cast<CXXConstructorDecl>(S.CurContext);
5043 if (Entity.getKind() == InitializedEntity::EK_Base) {
5044 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5045 << Constructor->isImplicit()
5046 << S.Context.getTypeDeclType(Constructor->getParent())
5047 << /*base=*/0
5048 << Entity.getType();
5049
5050 RecordDecl *BaseDecl
5051 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5052 ->getDecl();
5053 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5054 << S.Context.getTagDeclType(BaseDecl);
5055 } else {
5056 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5057 << Constructor->isImplicit()
5058 << S.Context.getTypeDeclType(Constructor->getParent())
5059 << /*member=*/1
5060 << Entity.getName();
5061 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5062
5063 if (const RecordType *Record
5064 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005065 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005066 diag::note_previous_decl)
5067 << S.Context.getTagDeclType(Record->getDecl());
5068 }
5069 break;
5070 }
5071
Douglas Gregor51c56d62009-12-14 20:49:26 +00005072 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5073 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005074 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005075 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005076
Douglas Gregor51c56d62009-12-14 20:49:26 +00005077 case OR_Deleted: {
5078 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5079 << true << DestType << ArgsRange;
5080 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005081 OverloadingResult Ovl
5082 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005083 if (Ovl == OR_Deleted) {
5084 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005085 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005086 } else {
5087 llvm_unreachable("Inconsistent overload resolution?");
5088 }
5089 break;
5090 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091
Douglas Gregor51c56d62009-12-14 20:49:26 +00005092 case OR_Success:
5093 llvm_unreachable("Conversion did not fail!");
5094 break;
5095 }
5096 break;
5097 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005098
Douglas Gregor99a2e602009-12-16 01:38:02 +00005099 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005100 if (Entity.getKind() == InitializedEntity::EK_Member &&
5101 isa<CXXConstructorDecl>(S.CurContext)) {
5102 // This is implicit default-initialization of a const member in
5103 // a constructor. Complain that it needs to be explicitly
5104 // initialized.
5105 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5106 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5107 << Constructor->isImplicit()
5108 << S.Context.getTypeDeclType(Constructor->getParent())
5109 << /*const=*/1
5110 << Entity.getName();
5111 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5112 << Entity.getName();
5113 } else {
5114 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5115 << DestType << (bool)DestType->getAs<RecordType>();
5116 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005117 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005118
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005119 case FK_Incomplete:
5120 S.RequireCompleteType(Kind.getLocation(), DestType,
5121 diag::err_init_incomplete_type);
5122 break;
5123
Sebastian Redl14b0c192011-09-24 17:48:00 +00005124 case FK_ListInitializationFailed: {
5125 // Run the init list checker again to emit diagnostics.
5126 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5127 QualType DestType = Entity.getType();
5128 InitListChecker DiagnoseInitList(S, Entity, InitList,
5129 DestType, /*VerifyOnly=*/false);
5130 assert(DiagnoseInitList.HadError() &&
5131 "Inconsistent init list check result.");
5132 break;
5133 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005134 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005135
Douglas Gregora41a8c52010-04-22 00:20:18 +00005136 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005137 return true;
5138}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005139
Chris Lattner5f9e2722011-07-23 10:55:15 +00005140void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005141 switch (SequenceKind) {
5142 case FailedSequence: {
5143 OS << "Failed sequence: ";
5144 switch (Failure) {
5145 case FK_TooManyInitsForReference:
5146 OS << "too many initializers for reference";
5147 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005148
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005149 case FK_ArrayNeedsInitList:
5150 OS << "array requires initializer list";
5151 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005152
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005153 case FK_ArrayNeedsInitListOrStringLiteral:
5154 OS << "array requires initializer list or string literal";
5155 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005156
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005157 case FK_ArrayTypeMismatch:
5158 OS << "array type mismatch";
5159 break;
5160
5161 case FK_NonConstantArrayInit:
5162 OS << "non-constant array initializer";
5163 break;
5164
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005165 case FK_AddressOfOverloadFailed:
5166 OS << "address of overloaded function failed";
5167 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005168
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005169 case FK_ReferenceInitOverloadFailed:
5170 OS << "overload resolution for reference initialization failed";
5171 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005172
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005173 case FK_NonConstLValueReferenceBindingToTemporary:
5174 OS << "non-const lvalue reference bound to temporary";
5175 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005176
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005177 case FK_NonConstLValueReferenceBindingToUnrelated:
5178 OS << "non-const lvalue reference bound to unrelated type";
5179 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005180
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005181 case FK_RValueReferenceBindingToLValue:
5182 OS << "rvalue reference bound to an lvalue";
5183 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005184
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005185 case FK_ReferenceInitDropsQualifiers:
5186 OS << "reference initialization drops qualifiers";
5187 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005188
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005189 case FK_ReferenceInitFailed:
5190 OS << "reference initialization failed";
5191 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005192
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005193 case FK_ConversionFailed:
5194 OS << "conversion failed";
5195 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005196
John Wiegley429bb272011-04-08 18:41:53 +00005197 case FK_ConversionFromPropertyFailed:
5198 OS << "conversion from property failed";
5199 break;
5200
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005201 case FK_TooManyInitsForScalar:
5202 OS << "too many initializers for scalar";
5203 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005204
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005205 case FK_ReferenceBindingToInitList:
5206 OS << "referencing binding to initializer list";
5207 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005208
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005209 case FK_InitListBadDestinationType:
5210 OS << "initializer list for non-aggregate, non-scalar type";
5211 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005212
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005213 case FK_UserConversionOverloadFailed:
5214 OS << "overloading failed for user-defined conversion";
5215 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005216
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005217 case FK_ConstructorOverloadFailed:
5218 OS << "constructor overloading failed";
5219 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005220
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005221 case FK_DefaultInitOfConst:
5222 OS << "default initialization of a const variable";
5223 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005224
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005225 case FK_Incomplete:
5226 OS << "initialization of incomplete type";
5227 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005228
5229 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005230 OS << "list initialization checker failure";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005231 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005232 OS << '\n';
5233 return;
5234 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005235
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005236 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005237 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005238 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005239
Sebastian Redl7491c492011-06-05 13:59:11 +00005240 case NormalSequence:
5241 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005242 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005244
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005245 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5246 if (S != step_begin()) {
5247 OS << " -> ";
5248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005249
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005250 switch (S->Kind) {
5251 case SK_ResolveAddressOfOverloadedFunction:
5252 OS << "resolve address of overloaded function";
5253 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005254
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005255 case SK_CastDerivedToBaseRValue:
5256 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5257 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005258
Sebastian Redl906082e2010-07-20 04:20:21 +00005259 case SK_CastDerivedToBaseXValue:
5260 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5261 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005262
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005263 case SK_CastDerivedToBaseLValue:
5264 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5265 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005266
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005267 case SK_BindReference:
5268 OS << "bind reference to lvalue";
5269 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005270
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005271 case SK_BindReferenceToTemporary:
5272 OS << "bind reference to a temporary";
5273 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005274
Douglas Gregor523d46a2010-04-18 07:40:54 +00005275 case SK_ExtraneousCopyToTemporary:
5276 OS << "extraneous C++03 copy to temporary";
5277 break;
5278
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005279 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00005280 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005281 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005282
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005283 case SK_QualificationConversionRValue:
5284 OS << "qualification conversion (rvalue)";
5285
Sebastian Redl906082e2010-07-20 04:20:21 +00005286 case SK_QualificationConversionXValue:
5287 OS << "qualification conversion (xvalue)";
5288
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005289 case SK_QualificationConversionLValue:
5290 OS << "qualification conversion (lvalue)";
5291 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005292
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005293 case SK_ConversionSequence:
5294 OS << "implicit conversion sequence (";
5295 S->ICS->DebugPrint(); // FIXME: use OS
5296 OS << ")";
5297 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005298
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005299 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005300 OS << "list aggregate initialization";
5301 break;
5302
5303 case SK_ListConstructorCall:
5304 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005305 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005306
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005307 case SK_ConstructorInitialization:
5308 OS << "constructor initialization";
5309 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005310
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005311 case SK_ZeroInitialization:
5312 OS << "zero initialization";
5313 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005314
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005315 case SK_CAssignment:
5316 OS << "C assignment";
5317 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005318
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005319 case SK_StringInit:
5320 OS << "string initialization";
5321 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005322
5323 case SK_ObjCObjectConversion:
5324 OS << "Objective-C object conversion";
5325 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005326
5327 case SK_ArrayInit:
5328 OS << "array initialization";
5329 break;
John McCallf85e1932011-06-15 23:02:42 +00005330
5331 case SK_PassByIndirectCopyRestore:
5332 OS << "pass by indirect copy and restore";
5333 break;
5334
5335 case SK_PassByIndirectRestore:
5336 OS << "pass by indirect restore";
5337 break;
5338
5339 case SK_ProduceObjCObject:
5340 OS << "Objective-C object retension";
5341 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005342 }
5343 }
5344}
5345
5346void InitializationSequence::dump() const {
5347 dump(llvm::errs());
5348}
5349
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005350static void DiagnoseNarrowingInInitList(
5351 Sema& S, QualType EntityType, const Expr *InitE,
5352 bool Constant, const APValue &ConstantValue) {
5353 if (Constant) {
5354 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005355 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005356 ? diag::err_init_list_constant_narrowing
5357 : diag::warn_init_list_constant_narrowing)
5358 << InitE->getSourceRange()
5359 << ConstantValue
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005360 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005361 } else
5362 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005363 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005364 ? diag::err_init_list_variable_narrowing
5365 : diag::warn_init_list_variable_narrowing)
5366 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005367 << InitE->getType().getLocalUnqualifiedType()
5368 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005369
5370 llvm::SmallString<128> StaticCast;
5371 llvm::raw_svector_ostream OS(StaticCast);
5372 OS << "static_cast<";
5373 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5374 // It's important to use the typedef's name if there is one so that the
5375 // fixit doesn't break code using types like int64_t.
5376 //
5377 // FIXME: This will break if the typedef requires qualification. But
5378 // getQualifiedNameAsString() includes non-machine-parsable components.
5379 OS << TT->getDecl();
5380 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5381 OS << BT->getName(S.getLangOptions());
5382 else {
5383 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5384 // with a broken cast.
5385 return;
5386 }
5387 OS << ">(";
5388 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5389 << InitE->getSourceRange()
5390 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5391 << FixItHint::CreateInsertion(
5392 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5393}
5394
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005395//===----------------------------------------------------------------------===//
5396// Initialization helper functions
5397//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005398bool
5399Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5400 ExprResult Init) {
5401 if (Init.isInvalid())
5402 return false;
5403
5404 Expr *InitE = Init.get();
5405 assert(InitE && "No initialization expression");
5406
5407 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5408 SourceLocation());
5409 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005410 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005411}
5412
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005413ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005414Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5415 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005416 ExprResult Init,
5417 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005418 if (Init.isInvalid())
5419 return ExprError();
5420
John McCall15d7d122010-11-11 03:21:53 +00005421 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005422 assert(InitE && "No initialization expression?");
5423
5424 if (EqualLoc.isInvalid())
5425 EqualLoc = InitE->getLocStart();
5426
5427 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5428 EqualLoc);
5429 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5430 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005431
5432 bool Constant = false;
5433 APValue Result;
5434 if (TopLevelOfInitList &&
5435 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5436 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5437 Constant, Result);
5438 }
John McCallf312b1e2010-08-26 23:41:50 +00005439 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005440}