blob: 9c85ceca74e8f18cabd01840eb026914de486db9 [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//
Chris Lattnerdd8e0062009-02-24 22:27:37 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
13//
Chris Lattner8b419b92009-02-24 22:48:58 +000014// This file also implements Sema::CheckInitializerTypes.
Steve Naroff0cca7492008-05-01 22:18:59 +000015//
16//===----------------------------------------------------------------------===//
17
Douglas Gregor20093b42009-12-09 23:02:17 +000018#include "SemaInit.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000020#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000022#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000023#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000024#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000025#include "llvm/Support/ErrorHandling.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
Chris Lattner79e079d2009-02-24 23:10:27 +000033static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000034 const ArrayType *AT = Context.getAsArrayType(DeclType);
35 if (!AT) return 0;
36
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000052 // char array can be initialized with a narrow string.
53 // Only allow char x[] = "foo"; not char x[] = L"foo";
54 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000055 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000056
Eli Friedmanbb6415c2009-05-31 10:54:53 +000057 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
58 // correction from DR343): "An array with element type compatible with a
59 // qualified or unqualified version of wchar_t may be initialized by a wide
60 // string literal, optionally enclosed in braces."
61 if (Context.typesAreCompatible(Context.getWCharType(),
62 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000063 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattnerdd8e0062009-02-24 22:27:37 +000065 return 0;
66}
67
Mike Stump1eb44332009-09-09 15:08:12 +000068static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner95e8d652009-02-24 22:46:58 +000069 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000070 // Get the type before calling CheckSingleAssignmentConstraints(), since
71 // it can promote the expression.
Mike Stump1eb44332009-09-09 15:08:12 +000072 QualType InitType = Init->getType();
73
Chris Lattner95e8d652009-02-24 22:46:58 +000074 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000075 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000076 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor68647482009-12-16 03:45:30 +000077 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000078 ImplicitConversionSequence ICS;
79 OverloadCandidateSet CandidateSet;
80 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
81 CandidateSet,
Douglas Gregor20093b42009-12-09 23:02:17 +000082 true, false, false) != OR_Ambiguous)
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000083 return S.Diag(Init->getSourceRange().getBegin(),
84 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +000085 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000086 << Init->getSourceRange();
87 S.Diag(Init->getSourceRange().getBegin(),
88 diag::err_typecheck_convert_ambiguous)
89 << DeclType << Init->getType() << Init->getSourceRange();
90 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
91 return true;
92 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +000093 return false;
94 }
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattner95e8d652009-02-24 22:46:58 +000096 Sema::AssignConvertType ConvTy =
97 S.CheckSingleAssignmentConstraints(DeclType, Init);
98 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor68647482009-12-16 03:45:30 +000099 InitType, Init, Sema::AA_Initializing);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000100}
101
Chris Lattner79e079d2009-02-24 23:10:27 +0000102static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
103 // Get the length of the string as parsed.
104 uint64_t StrLength =
105 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
106
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Chris Lattner79e079d2009-02-24 23:10:27 +0000108 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000109 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000110 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000111 // being initialized to a string literal.
112 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000113 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000114 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000115 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
116 ConstVal,
117 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000118 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Eli Friedman8718a6a2009-05-29 18:22:49 +0000121 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Eli Friedman8718a6a2009-05-29 18:22:49 +0000123 // C99 6.7.8p14. We have an array of character type with known size. However,
124 // the size may be smaller or larger than the string we are initializing.
125 // FIXME: Avoid truncation for 64-bit length strings.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Eli Friedman8718a6a2009-05-29 18:22:49 +0000131 // Set the type to the actual size that we are initializing. If we have
132 // something like:
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
135 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000136}
137
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000138//===----------------------------------------------------------------------===//
139// Semantic checking for initializer lists.
140//===----------------------------------------------------------------------===//
141
Douglas Gregor9e80f722009-01-29 01:05:33 +0000142/// @brief Semantic checking for initializer lists.
143///
144/// The InitListChecker class contains a set of routines that each
145/// handle the initialization of a certain kind of entity, e.g.,
146/// arrays, vectors, struct/union types, scalars, etc. The
147/// InitListChecker itself performs a recursive walk of the subobject
148/// structure of the type to be initialized, while stepping through
149/// the initializer list one element at a time. The IList and Index
150/// parameters to each of the Check* routines contain the active
151/// (syntactic) initializer list and the index into that initializer
152/// list that represents the current initializer. Each routine is
153/// responsible for moving that Index forward as it consumes elements.
154///
155/// Each Check* routine also has a StructuredList/StructuredIndex
156/// arguments, which contains the current the "structured" (semantic)
157/// initializer list and the index into that initializer list where we
158/// are copying initializers as we map them over to the semantic
159/// list. Once we have completed our recursive walk of the subobject
160/// structure, we will have constructed a full semantic initializer
161/// list.
162///
163/// C99 designators cause changes in the initializer list traversal,
164/// because they make the initialization "jump" into a specific
165/// subobject and then continue the initialization from that
166/// point. CheckDesignatedInitializer() recursively steps into the
167/// designated subobject and manages backing out the recursion to
168/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000169namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000170class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000171 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000172 bool hadError;
173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000175
176 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000177 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000178 unsigned &StructuredIndex,
179 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000180 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000181 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000182 unsigned &StructuredIndex,
183 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000184 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
185 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000186 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000187 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000188 unsigned &StructuredIndex,
189 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000190 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000191 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000192 InitListExpr *StructuredList,
193 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000194 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000198 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000202 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000203 InitListExpr *StructuredList,
204 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000205 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
206 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000207 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000208 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000209 unsigned &StructuredIndex,
210 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000211 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
212 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000213 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000216 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000217 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000218 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219 RecordDecl::field_iterator *NextField,
220 llvm::APSInt *NextElementIndex,
221 unsigned &Index,
222 InitListExpr *StructuredList,
223 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000224 bool FinishSubobjectInit,
225 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000226 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
227 QualType CurrentObjectType,
228 InitListExpr *StructuredList,
229 unsigned StructuredIndex,
230 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000231 void UpdateStructuredListElement(InitListExpr *StructuredList,
232 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000233 Expr *expr);
234 int numArrayElements(QualType DeclType);
235 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000236
Douglas Gregord6d37de2009-12-22 00:05:34 +0000237 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
238 const InitializedEntity &ParentEntity,
239 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000240 void FillInValueInitializations(const InitializedEntity &Entity,
241 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000243 InitListChecker(Sema &S, const InitializedEntity &Entity,
244 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000245 bool HadError() { return hadError; }
246
247 // @brief Retrieves the fully-structured initializer list used for
248 // semantic analysis and code generation.
249 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
250};
Chris Lattner8b419b92009-02-24 22:48:58 +0000251} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE,
256 bool &RequiresSecondPass) {
257 SourceLocation Loc = ILE->getSourceRange().getBegin();
258 unsigned NumInits = ILE->getNumInits();
259 InitializedEntity MemberEntity
260 = InitializedEntity::InitializeMember(Field, &ParentEntity);
261 if (Init >= NumInits || !ILE->getInit(Init)) {
262 // FIXME: We probably don't need to handle references
263 // specially here, since value-initialization of references is
264 // handled in InitializationSequence.
265 if (Field->getType()->isReferenceType()) {
266 // C++ [dcl.init.aggr]p9:
267 // If an incomplete or empty initializer-list leaves a
268 // member of reference type uninitialized, the program is
269 // ill-formed.
270 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
271 << Field->getType()
272 << ILE->getSyntacticForm()->getSourceRange();
273 SemaRef.Diag(Field->getLocation(),
274 diag::note_uninit_reference_member);
275 hadError = true;
276 return;
277 }
278
279 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
280 true);
281 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
282 if (!InitSeq) {
283 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
284 hadError = true;
285 return;
286 }
287
288 Sema::OwningExprResult MemberInit
289 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
290 Sema::MultiExprArg(SemaRef, 0, 0));
291 if (MemberInit.isInvalid()) {
292 hadError = true;
293 return;
294 }
295
296 if (hadError) {
297 // Do nothing
298 } else if (Init < NumInits) {
299 ILE->setInit(Init, MemberInit.takeAs<Expr>());
300 } else if (InitSeq.getKind()
301 == InitializationSequence::ConstructorInitialization) {
302 // Value-initialization requires a constructor call, so
303 // extend the initializer list to include the constructor
304 // call and make a note that we'll need to take another pass
305 // through the initializer list.
306 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
307 RequiresSecondPass = true;
308 }
309 } else if (InitListExpr *InnerILE
310 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
311 FillInValueInitializations(MemberEntity, InnerILE,
312 RequiresSecondPass);
313}
314
Douglas Gregor4c678342009-01-28 21:54:33 +0000315/// Recursively replaces NULL values within the given initializer list
316/// with expressions that perform value-initialization of the
317/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000318void
319InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
320 InitListExpr *ILE,
321 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000322 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000323 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000324 SourceLocation Loc = ILE->getSourceRange().getBegin();
325 if (ILE->getSyntacticForm())
326 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Ted Kremenek6217b802009-07-29 21:53:49 +0000328 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 if (RType->getDecl()->isUnion() &&
330 ILE->getInitializedFieldInUnion())
331 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
332 Entity, ILE, RequiresSecondPass);
333 else {
334 unsigned Init = 0;
335 for (RecordDecl::field_iterator
336 Field = RType->getDecl()->field_begin(),
337 FieldEnd = RType->getDecl()->field_end();
338 Field != FieldEnd; ++Field) {
339 if (Field->isUnnamedBitfield())
340 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000341
Douglas Gregord6d37de2009-12-22 00:05:34 +0000342 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000343 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000344
345 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
346 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000347 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000348
Douglas Gregord6d37de2009-12-22 00:05:34 +0000349 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000350
Douglas Gregord6d37de2009-12-22 00:05:34 +0000351 // Only look at the first initialization of a union.
352 if (RType->getDecl()->isUnion())
353 break;
354 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000355 }
356
357 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000358 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000359
360 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000362 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000363 unsigned NumInits = ILE->getNumInits();
364 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000365 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000366 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000367 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
368 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000369 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
370 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000371 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000372 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000373 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000374 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
375 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000376 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000377 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000379
Douglas Gregor87fd7032009-02-02 17:43:21 +0000380 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000381 if (hadError)
382 return;
383
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000384 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
385 ElementEntity.setElementIndex(Init);
386
Douglas Gregor87fd7032009-02-02 17:43:21 +0000387 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000388 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
389 true);
390 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
391 if (!InitSeq) {
392 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000393 hadError = true;
394 return;
395 }
396
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000397 Sema::OwningExprResult ElementInit
398 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
399 Sema::MultiExprArg(SemaRef, 0, 0));
400 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000401 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000402 return;
403 }
404
405 if (hadError) {
406 // Do nothing
407 } else if (Init < NumInits) {
408 ILE->setInit(Init, ElementInit.takeAs<Expr>());
409 } else if (InitSeq.getKind()
410 == InitializationSequence::ConstructorInitialization) {
411 // Value-initialization requires a constructor call, so
412 // extend the initializer list to include the constructor
413 // call and make a note that we'll need to take another pass
414 // through the initializer list.
415 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
416 RequiresSecondPass = true;
417 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000418 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000419 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
420 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000421 }
422}
423
Chris Lattner68355a52009-01-29 05:10:57 +0000424
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000425InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
426 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000427 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000428 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000429
Eli Friedmanb85f7072008-05-19 19:16:24 +0000430 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000431 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000432 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000433 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000434 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
435 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000436
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000437 if (!hadError) {
438 bool RequiresSecondPass = false;
439 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000440 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000441 FillInValueInitializations(Entity, FullyStructuredList,
442 RequiresSecondPass);
443 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000444}
445
446int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000447 // FIXME: use a proper constant
448 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000449 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000450 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000451 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
452 }
453 return maxElements;
454}
455
456int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000457 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000458 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000459 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000460 Field = structDecl->field_begin(),
461 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000462 Field != FieldEnd; ++Field) {
463 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
464 ++InitializableMembers;
465 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000466 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000467 return std::min(InitializableMembers, 1);
468 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000469}
470
Mike Stump1eb44332009-09-09 15:08:12 +0000471void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000472 QualType T, unsigned &Index,
473 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000474 unsigned &StructuredIndex,
475 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000476 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Steve Naroff0cca7492008-05-01 22:18:59 +0000478 if (T->isArrayType())
479 maxElements = numArrayElements(T);
480 else if (T->isStructureType() || T->isUnionType())
481 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000482 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000483 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000484 else
485 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000486
Eli Friedman402256f2008-05-25 13:49:22 +0000487 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000488 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000489 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000490 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000491 hadError = true;
492 return;
493 }
494
Douglas Gregor4c678342009-01-28 21:54:33 +0000495 // Build a structured initializer list corresponding to this subobject.
496 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000497 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
498 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000499 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
500 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000501 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000502
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000504 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000505 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000506 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000507 StructuredSubobjectInitIndex,
508 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000509 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000510 StructuredSubobjectInitList->setType(T);
511
Douglas Gregored8a93d2009-03-01 17:12:46 +0000512 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000513 // range corresponds with the end of the last initializer it used.
514 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000515 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000516 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
517 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
518 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000519}
520
Steve Naroffa647caa2008-05-06 00:23:44 +0000521void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000522 unsigned &Index,
523 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000524 unsigned &StructuredIndex,
525 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000526 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000527 SyntacticToSemantic[IList] = StructuredList;
528 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000529 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000530 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000531 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000532 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000533 if (hadError)
534 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000535
Eli Friedman638e1442008-05-25 13:22:35 +0000536 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000537 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000538 if (StructuredIndex == 1 &&
539 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000540 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000541 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000542 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000543 hadError = true;
544 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000545 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000546 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000547 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000548 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000549 // Don't complain for incomplete types, since we'll get an error
550 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000551 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000552 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000553 CurrentObjectType->isArrayType()? 0 :
554 CurrentObjectType->isVectorType()? 1 :
555 CurrentObjectType->isScalarType()? 2 :
556 CurrentObjectType->isUnionType()? 3 :
557 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000558
559 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000560 if (SemaRef.getLangOptions().CPlusPlus) {
561 DK = diag::err_excess_initializers;
562 hadError = true;
563 }
Nate Begeman08634522009-07-07 21:53:06 +0000564 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
565 DK = diag::err_excess_initializers;
566 hadError = true;
567 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000568
Chris Lattner08202542009-02-24 22:50:46 +0000569 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000570 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000571 }
572 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000573
Eli Friedman759f2522009-05-16 11:45:48 +0000574 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000575 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000576 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000577 << CodeModificationHint::CreateRemoval(IList->getLocStart())
578 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000579}
580
Eli Friedmanb85f7072008-05-19 19:16:24 +0000581void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000582 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000583 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000584 unsigned &Index,
585 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000586 unsigned &StructuredIndex,
587 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000588 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000589 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000590 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000591 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000592 } else if (DeclType->isAggregateType()) {
593 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000594 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000595 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000596 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000597 StructuredList, StructuredIndex,
598 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000599 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000600 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000601 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000602 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000603 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
604 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000605 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000607 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
608 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000609 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000610 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000611 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000612 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000613 } else if (DeclType->isRecordType()) {
614 // C++ [dcl.init]p14:
615 // [...] If the class is an aggregate (8.5.1), and the initializer
616 // is a brace-enclosed list, see 8.5.1.
617 //
618 // Note: 8.5.1 is handled below; here, we diagnose the case where
619 // we have an initializer list and a destination type that is not
620 // an aggregate.
621 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000622 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000623 << DeclType << IList->getSourceRange();
624 hadError = true;
625 } else if (DeclType->isReferenceType()) {
626 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000627 } else {
628 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000629 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000630 assert(0 && "Unsupported initializer type");
631 }
632}
633
Eli Friedmanb85f7072008-05-19 19:16:24 +0000634void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000635 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000636 unsigned &Index,
637 InitListExpr *StructuredList,
638 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000639 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000640 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
641 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000642 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000643 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000644 = getStructuredSubobjectInit(IList, Index, ElemType,
645 StructuredList, StructuredIndex,
646 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000647 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000648 newStructuredList, newStructuredIndex);
649 ++StructuredIndex;
650 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000651 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
652 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000653 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000654 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000655 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000656 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000657 } else if (ElemType->isReferenceType()) {
658 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000659 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000660 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000661 // C++ [dcl.init.aggr]p12:
662 // All implicit type conversions (clause 4) are considered when
663 // initializing the aggregate member with an ini- tializer from
664 // an initializer-list. If the initializer can initialize a
665 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000666 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000667 = SemaRef.TryCopyInitialization(expr, ElemType,
668 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000669 /*ForceRValue=*/false,
670 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000671
Douglas Gregor930d8b52009-01-30 22:09:00 +0000672 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000673 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000674 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000675 hadError = true;
676 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
677 ++Index;
678 return;
679 }
680
681 // Fall through for subaggregate initialization
682 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000683 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000684 //
685 // The initializer for a structure or union object that has
686 // automatic storage duration shall be either an initializer
687 // list as described below, or a single expression that has
688 // compatible structure or union type. In the latter case, the
689 // initial value of the object, including unnamed members, is
690 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000691 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000692 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000693 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
694 ++Index;
695 return;
696 }
697
698 // Fall through for subaggregate initialization
699 }
700
701 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000702 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000703 // [...] Otherwise, if the member is itself a non-empty
704 // subaggregate, brace elision is assumed and the initializer is
705 // considered for the initialization of the first member of
706 // the subaggregate.
707 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000708 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000709 StructuredIndex);
710 ++StructuredIndex;
711 } else {
712 // We cannot initialize this element, so let
713 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000714 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000715 hadError = true;
716 ++Index;
717 ++StructuredIndex;
718 }
719 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000720}
721
Douglas Gregor930d8b52009-01-30 22:09:00 +0000722void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000723 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000724 InitListExpr *StructuredList,
725 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000726 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000727 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000728 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000729 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000730 diag::err_many_braces_around_scalar_init)
731 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000732 hadError = true;
733 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000734 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000735 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000736 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000737 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000738 diag::err_designator_for_scalar_init)
739 << DeclType << expr->getSourceRange();
740 hadError = true;
741 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000742 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000743 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000744 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000745
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000746 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000747 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000748 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000749 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000750 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000751 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000752 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000753 if (hadError)
754 ++StructuredIndex;
755 else
756 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000757 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000758 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000759 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000760 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000761 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000762 ++Index;
763 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000764 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000765 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000766}
767
Douglas Gregor930d8b52009-01-30 22:09:00 +0000768void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
769 unsigned &Index,
770 InitListExpr *StructuredList,
771 unsigned &StructuredIndex) {
772 if (Index < IList->getNumInits()) {
773 Expr *expr = IList->getInit(Index);
774 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000775 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000776 << DeclType << IList->getSourceRange();
777 hadError = true;
778 ++Index;
779 ++StructuredIndex;
780 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000781 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000782
783 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000784 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000785 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000786 /*SuppressUserConversions=*/false,
787 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000788 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000789 hadError = true;
790 else if (savExpr != expr) {
791 // The type was promoted, update initializer list.
792 IList->setInit(Index, expr);
793 }
794 if (hadError)
795 ++StructuredIndex;
796 else
797 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
798 ++Index;
799 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000800 // FIXME: It would be wonderful if we could point at the actual member. In
801 // general, it would be useful to pass location information down the stack,
802 // so that we know the location (or decl) of the "current object" being
803 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000804 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000805 diag::err_init_reference_member_uninitialized)
806 << DeclType
807 << IList->getSourceRange();
808 hadError = true;
809 ++Index;
810 ++StructuredIndex;
811 return;
812 }
813}
814
Mike Stump1eb44332009-09-09 15:08:12 +0000815void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000816 unsigned &Index,
817 InitListExpr *StructuredList,
818 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000819 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000820 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000821 unsigned maxElements = VT->getNumElements();
822 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000823 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Nate Begeman2ef13e52009-08-10 23:49:36 +0000825 if (!SemaRef.getLangOptions().OpenCL) {
826 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
827 // Don't attempt to go past the end of the init list
828 if (Index >= IList->getNumInits())
829 break;
830 CheckSubElementType(IList, elementType, Index,
831 StructuredList, StructuredIndex);
832 }
833 } else {
834 // OpenCL initializers allows vectors to be constructed from vectors.
835 for (unsigned i = 0; i < maxElements; ++i) {
836 // Don't attempt to go past the end of the init list
837 if (Index >= IList->getNumInits())
838 break;
839 QualType IType = IList->getInit(Index)->getType();
840 if (!IType->isVectorType()) {
841 CheckSubElementType(IList, elementType, Index,
842 StructuredList, StructuredIndex);
843 ++numEltsInit;
844 } else {
John McCall183700f2009-09-21 23:43:11 +0000845 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000846 unsigned numIElts = IVT->getNumElements();
847 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
848 numIElts);
849 CheckSubElementType(IList, VecType, Index,
850 StructuredList, StructuredIndex);
851 numEltsInit += numIElts;
852 }
853 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000854 }
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Nate Begeman2ef13e52009-08-10 23:49:36 +0000856 // OpenCL & AltiVec require all elements to be initialized.
857 if (numEltsInit != maxElements)
858 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
859 SemaRef.Diag(IList->getSourceRange().getBegin(),
860 diag::err_vector_incorrect_num_initializers)
861 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000862 }
863}
864
Mike Stump1eb44332009-09-09 15:08:12 +0000865void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000866 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000867 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000868 unsigned &Index,
869 InitListExpr *StructuredList,
870 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000871 // Check for the special-case of initializing an array with a string.
872 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000873 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
874 SemaRef.Context)) {
875 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000876 // We place the string literal directly into the resulting
877 // initializer list. This is the only place where the structure
878 // of the structured initializer list doesn't match exactly,
879 // because doing so would involve allocating one character
880 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000881 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000882 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000883 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000884 return;
885 }
886 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000887 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000888 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000889 // Check for VLAs; in standard C it would be possible to check this
890 // earlier, but I don't know where clang accepts VLAs (gcc accepts
891 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000892 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000893 diag::err_variable_object_no_init)
894 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000895 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000896 ++Index;
897 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000898 return;
899 }
900
Douglas Gregor05c13a32009-01-22 00:58:24 +0000901 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000902 llvm::APSInt maxElements(elementIndex.getBitWidth(),
903 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000904 bool maxElementsKnown = false;
905 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000906 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000907 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000908 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000909 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000910 maxElementsKnown = true;
911 }
912
Chris Lattner08202542009-02-24 22:50:46 +0000913 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000914 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000915 while (Index < IList->getNumInits()) {
916 Expr *Init = IList->getInit(Index);
917 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000918 // If we're not the subobject that matches up with the '{' for
919 // the designator, we shouldn't be handling the
920 // designator. Return immediately.
921 if (!SubobjectIsDesignatorContext)
922 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000923
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000924 // Handle this designated initializer. elementIndex will be
925 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +0000926 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000927 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000928 StructuredList, StructuredIndex, true,
929 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000930 hadError = true;
931 continue;
932 }
933
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000934 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
935 maxElements.extend(elementIndex.getBitWidth());
936 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
937 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000938 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000939
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000940 // If the array is of incomplete type, keep track of the number of
941 // elements in the initializer.
942 if (!maxElementsKnown && elementIndex > maxElements)
943 maxElements = elementIndex;
944
Douglas Gregor05c13a32009-01-22 00:58:24 +0000945 continue;
946 }
947
948 // If we know the maximum number of elements, and we've already
949 // hit it, stop consuming elements in the initializer list.
950 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000951 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000952
953 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000954 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000955 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000956 ++elementIndex;
957
958 // If the array is of incomplete type, keep track of the number of
959 // elements in the initializer.
960 if (!maxElementsKnown && elementIndex > maxElements)
961 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +0000962 }
Eli Friedman587cbdf2009-05-29 20:17:55 +0000963 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000964 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000965 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000966 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000967 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000968 // Sizing an array implicitly to zero is not allowed by ISO C,
969 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +0000970 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000971 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +0000972 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000973
Mike Stump1eb44332009-09-09 15:08:12 +0000974 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +0000975 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +0000976 }
977}
978
Mike Stump1eb44332009-09-09 15:08:12 +0000979void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
980 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000981 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +0000982 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000983 unsigned &Index,
984 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000985 unsigned &StructuredIndex,
986 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000987 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Eli Friedmanb85f7072008-05-19 19:16:24 +0000989 // If the record is invalid, some of it's members are invalid. To avoid
990 // confusion, we forgo checking the intializer for the entire record.
991 if (structDecl->isInvalidDecl()) {
992 hadError = true;
993 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000994 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000995
996 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
997 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +0000998 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000999 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001000 Field != FieldEnd; ++Field) {
1001 if (Field->getDeclName()) {
1002 StructuredList->setInitializedFieldInUnion(*Field);
1003 break;
1004 }
1005 }
1006 return;
1007 }
1008
Douglas Gregor05c13a32009-01-22 00:58:24 +00001009 // If structDecl is a forward declaration, this loop won't do
1010 // anything except look at designated initializers; That's okay,
1011 // because an error should get printed out elsewhere. It might be
1012 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001013 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001014 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001015 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001016 while (Index < IList->getNumInits()) {
1017 Expr *Init = IList->getInit(Index);
1018
1019 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001020 // If we're not the subobject that matches up with the '{' for
1021 // the designator, we shouldn't be handling the
1022 // designator. Return immediately.
1023 if (!SubobjectIsDesignatorContext)
1024 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001025
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001026 // Handle this designated initializer. Field will be updated to
1027 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001028 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001029 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001030 StructuredList, StructuredIndex,
1031 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001032 hadError = true;
1033
Douglas Gregordfb5e592009-02-12 19:00:39 +00001034 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001035 continue;
1036 }
1037
1038 if (Field == FieldEnd) {
1039 // We've run out of fields. We're done.
1040 break;
1041 }
1042
Douglas Gregordfb5e592009-02-12 19:00:39 +00001043 // We've already initialized a member of a union. We're done.
1044 if (InitializedSomething && DeclType->isUnionType())
1045 break;
1046
Douglas Gregor44b43212008-12-11 16:49:14 +00001047 // If we've hit the flexible array member at the end, we're done.
1048 if (Field->getType()->isIncompleteArrayType())
1049 break;
1050
Douglas Gregor0bb76892009-01-29 16:53:55 +00001051 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001052 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001053 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001054 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001055 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001056
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001057 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001058 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001059 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001060
1061 if (DeclType->isUnionType()) {
1062 // Initialize the first field within the union.
1063 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001064 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001065
1066 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001067 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001068
Mike Stump1eb44332009-09-09 15:08:12 +00001069 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001070 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001071 return;
1072
1073 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001074 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001075 (!isa<InitListExpr>(IList->getInit(Index)) ||
1076 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001077 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001078 diag::err_flexible_array_init_nonempty)
1079 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001080 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001081 << *Field;
1082 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001083 ++Index;
1084 return;
1085 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001086 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001087 diag::ext_flexible_array_init)
1088 << IList->getInit(Index)->getSourceRange().getBegin();
1089 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1090 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001091 }
1092
Douglas Gregora6457962009-03-20 00:32:56 +00001093 if (isa<InitListExpr>(IList->getInit(Index)))
1094 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1095 StructuredIndex);
1096 else
1097 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1098 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001099}
Steve Naroff0cca7492008-05-01 22:18:59 +00001100
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001101/// \brief Expand a field designator that refers to a member of an
1102/// anonymous struct or union into a series of field designators that
1103/// refers to the field within the appropriate subobject.
1104///
1105/// Field/FieldIndex will be updated to point to the (new)
1106/// currently-designated field.
1107static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001108 DesignatedInitExpr *DIE,
1109 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001110 FieldDecl *Field,
1111 RecordDecl::field_iterator &FieldIter,
1112 unsigned &FieldIndex) {
1113 typedef DesignatedInitExpr::Designator Designator;
1114
1115 // Build the path from the current object to the member of the
1116 // anonymous struct/union (backwards).
1117 llvm::SmallVector<FieldDecl *, 4> Path;
1118 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001120 // Build the replacement designators.
1121 llvm::SmallVector<Designator, 4> Replacements;
1122 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1123 FI = Path.rbegin(), FIEnd = Path.rend();
1124 FI != FIEnd; ++FI) {
1125 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001126 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001127 DIE->getDesignator(DesigIdx)->getDotLoc(),
1128 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1129 else
1130 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1131 SourceLocation()));
1132 Replacements.back().setField(*FI);
1133 }
1134
1135 // Expand the current designator into the set of replacement
1136 // designators, so we have a full subobject path down to where the
1137 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001138 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001139 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001141 // Update FieldIter/FieldIndex;
1142 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001143 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001144 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001145 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001146 FieldIter != FEnd; ++FieldIter) {
1147 if (FieldIter->isUnnamedBitfield())
1148 continue;
1149
1150 if (*FieldIter == Path.back())
1151 return;
1152
1153 ++FieldIndex;
1154 }
1155
1156 assert(false && "Unable to find anonymous struct/union field");
1157}
1158
Douglas Gregor05c13a32009-01-22 00:58:24 +00001159/// @brief Check the well-formedness of a C99 designated initializer.
1160///
1161/// Determines whether the designated initializer @p DIE, which
1162/// resides at the given @p Index within the initializer list @p
1163/// IList, is well-formed for a current object of type @p DeclType
1164/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001165/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001166/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001167///
1168/// @param IList The initializer list in which this designated
1169/// initializer occurs.
1170///
Douglas Gregor71199712009-04-15 04:56:10 +00001171/// @param DIE The designated initializer expression.
1172///
1173/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001174///
1175/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1176/// into which the designation in @p DIE should refer.
1177///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001178/// @param NextField If non-NULL and the first designator in @p DIE is
1179/// a field, this will be set to the field declaration corresponding
1180/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001181///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001182/// @param NextElementIndex If non-NULL and the first designator in @p
1183/// DIE is an array designator or GNU array-range designator, this
1184/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001185///
1186/// @param Index Index into @p IList where the designated initializer
1187/// @p DIE occurs.
1188///
Douglas Gregor4c678342009-01-28 21:54:33 +00001189/// @param StructuredList The initializer list expression that
1190/// describes all of the subobject initializers in the order they'll
1191/// actually be initialized.
1192///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001193/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001194bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001195InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001196 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001197 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001198 QualType &CurrentObjectType,
1199 RecordDecl::field_iterator *NextField,
1200 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001201 unsigned &Index,
1202 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001203 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001204 bool FinishSubobjectInit,
1205 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001206 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001207 // Check the actual initialization for the designated object type.
1208 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001209
1210 // Temporarily remove the designator expression from the
1211 // initializer list that the child calls see, so that we don't try
1212 // to re-process the designator.
1213 unsigned OldIndex = Index;
1214 IList->setInit(OldIndex, DIE->getInit());
1215
1216 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001217 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001218
1219 // Restore the designated initializer expression in the syntactic
1220 // form of the initializer list.
1221 if (IList->getInit(OldIndex) != DIE->getInit())
1222 DIE->setInit(IList->getInit(OldIndex));
1223 IList->setInit(OldIndex, DIE);
1224
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001225 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001226 }
1227
Douglas Gregor71199712009-04-15 04:56:10 +00001228 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001229 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001230 "Need a non-designated initializer list to start from");
1231
Douglas Gregor71199712009-04-15 04:56:10 +00001232 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001233 // Determine the structural initializer list that corresponds to the
1234 // current subobject.
1235 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001236 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001237 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001238 SourceRange(D->getStartLocation(),
1239 DIE->getSourceRange().getEnd()));
1240 assert(StructuredList && "Expected a structured initializer list");
1241
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001242 if (D->isFieldDesignator()) {
1243 // C99 6.7.8p7:
1244 //
1245 // If a designator has the form
1246 //
1247 // . identifier
1248 //
1249 // then the current object (defined below) shall have
1250 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001251 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001252 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001253 if (!RT) {
1254 SourceLocation Loc = D->getDotLoc();
1255 if (Loc.isInvalid())
1256 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001257 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1258 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001259 ++Index;
1260 return true;
1261 }
1262
Douglas Gregor4c678342009-01-28 21:54:33 +00001263 // Note: we perform a linear search of the fields here, despite
1264 // the fact that we have a faster lookup method, because we always
1265 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001266 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001267 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001268 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001269 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001270 Field = RT->getDecl()->field_begin(),
1271 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001272 for (; Field != FieldEnd; ++Field) {
1273 if (Field->isUnnamedBitfield())
1274 continue;
1275
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001276 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001277 break;
1278
1279 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001280 }
1281
Douglas Gregor4c678342009-01-28 21:54:33 +00001282 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001283 // There was no normal field in the struct with the designated
1284 // name. Perform another lookup for this name, which may find
1285 // something that we can't designate (e.g., a member function),
1286 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001287 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001288 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001289 if (Lookup.first == Lookup.second) {
1290 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001291 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001292 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001293 ++Index;
1294 return true;
1295 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1296 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1297 ->isAnonymousStructOrUnion()) {
1298 // Handle an field designator that refers to a member of an
1299 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001300 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001301 cast<FieldDecl>(*Lookup.first),
1302 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001303 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001304 } else {
1305 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001306 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001307 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001308 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001309 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001310 ++Index;
1311 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001312 }
1313 } else if (!KnownField &&
1314 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001315 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001316 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1317 Field, FieldIndex);
1318 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001319 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001320
1321 // All of the fields of a union are located at the same place in
1322 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001323 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001324 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001325 StructuredList->setInitializedFieldInUnion(*Field);
1326 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001327
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001328 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001329 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Douglas Gregor4c678342009-01-28 21:54:33 +00001331 // Make sure that our non-designated initializer list has space
1332 // for a subobject corresponding to this field.
1333 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001334 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001335
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001336 // This designator names a flexible array member.
1337 if (Field->getType()->isIncompleteArrayType()) {
1338 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001339 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001340 // We can't designate an object within the flexible array
1341 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001342 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001343 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001344 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001345 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001346 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001347 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001348 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001349 << *Field;
1350 Invalid = true;
1351 }
1352
1353 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1354 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001355 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001356 diag::err_flexible_array_init_needs_braces)
1357 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001358 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001359 << *Field;
1360 Invalid = true;
1361 }
1362
1363 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001364 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001365 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001366 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001367 diag::err_flexible_array_init_nonempty)
1368 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001369 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001370 << *Field;
1371 Invalid = true;
1372 }
1373
1374 if (Invalid) {
1375 ++Index;
1376 return true;
1377 }
1378
1379 // Initialize the array.
1380 bool prevHadError = hadError;
1381 unsigned newStructuredIndex = FieldIndex;
1382 unsigned OldIndex = Index;
1383 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001384 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001385 StructuredList, newStructuredIndex);
1386 IList->setInit(OldIndex, DIE);
1387 if (hadError && !prevHadError) {
1388 ++Field;
1389 ++FieldIndex;
1390 if (NextField)
1391 *NextField = Field;
1392 StructuredIndex = FieldIndex;
1393 return true;
1394 }
1395 } else {
1396 // Recurse to check later designated subobjects.
1397 QualType FieldType = (*Field)->getType();
1398 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001399 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1400 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001401 true, false))
1402 return true;
1403 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001404
1405 // Find the position of the next field to be initialized in this
1406 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001407 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001408 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001409
1410 // If this the first designator, our caller will continue checking
1411 // the rest of this struct/class/union subobject.
1412 if (IsFirstDesignator) {
1413 if (NextField)
1414 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001415 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001416 return false;
1417 }
1418
Douglas Gregor34e79462009-01-28 23:36:17 +00001419 if (!FinishSubobjectInit)
1420 return false;
1421
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001422 // We've already initialized something in the union; we're done.
1423 if (RT->getDecl()->isUnion())
1424 return hadError;
1425
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001426 // Check the remaining fields within this class/struct/union subobject.
1427 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001428 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1429 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001430 return hadError && !prevHadError;
1431 }
1432
1433 // C99 6.7.8p6:
1434 //
1435 // If a designator has the form
1436 //
1437 // [ constant-expression ]
1438 //
1439 // then the current object (defined below) shall have array
1440 // type and the expression shall be an integer constant
1441 // expression. If the array is of unknown size, any
1442 // nonnegative value is valid.
1443 //
1444 // Additionally, cope with the GNU extension that permits
1445 // designators of the form
1446 //
1447 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001448 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001449 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001450 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001451 << CurrentObjectType;
1452 ++Index;
1453 return true;
1454 }
1455
1456 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001457 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1458 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001459 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001460 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001461 DesignatedEndIndex = DesignatedStartIndex;
1462 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001463 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001464
Mike Stump1eb44332009-09-09 15:08:12 +00001465
1466 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001467 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001468 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001469 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001470 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001471
Chris Lattner3bf68932009-04-25 21:59:05 +00001472 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001473 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001474 }
1475
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001476 if (isa<ConstantArrayType>(AT)) {
1477 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001478 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1479 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1480 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1481 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1482 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001483 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001484 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001485 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001486 << IndexExpr->getSourceRange();
1487 ++Index;
1488 return true;
1489 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001490 } else {
1491 // Make sure the bit-widths and signedness match.
1492 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1493 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001494 else if (DesignatedStartIndex.getBitWidth() <
1495 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001496 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1497 DesignatedStartIndex.setIsUnsigned(true);
1498 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001499 }
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Douglas Gregor4c678342009-01-28 21:54:33 +00001501 // Make sure that our non-designated initializer list has space
1502 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001503 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001504 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001505 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001506
Douglas Gregor34e79462009-01-28 23:36:17 +00001507 // Repeatedly perform subobject initializations in the range
1508 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001509
Douglas Gregor34e79462009-01-28 23:36:17 +00001510 // Move to the next designator
1511 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1512 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001513 while (DesignatedStartIndex <= DesignatedEndIndex) {
1514 // Recurse to check later designated subobjects.
1515 QualType ElementType = AT->getElementType();
1516 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001517 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1518 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001519 (DesignatedStartIndex == DesignatedEndIndex),
1520 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001521 return true;
1522
1523 // Move to the next index in the array that we'll be initializing.
1524 ++DesignatedStartIndex;
1525 ElementIndex = DesignatedStartIndex.getZExtValue();
1526 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527
1528 // If this the first designator, our caller will continue checking
1529 // the rest of this array subobject.
1530 if (IsFirstDesignator) {
1531 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001532 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001533 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001534 return false;
1535 }
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Douglas Gregor34e79462009-01-28 23:36:17 +00001537 if (!FinishSubobjectInit)
1538 return false;
1539
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001540 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001541 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001542 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001543 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001544 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001545}
1546
Douglas Gregor4c678342009-01-28 21:54:33 +00001547// Get the structured initializer list for a subobject of type
1548// @p CurrentObjectType.
1549InitListExpr *
1550InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1551 QualType CurrentObjectType,
1552 InitListExpr *StructuredList,
1553 unsigned StructuredIndex,
1554 SourceRange InitRange) {
1555 Expr *ExistingInit = 0;
1556 if (!StructuredList)
1557 ExistingInit = SyntacticToSemantic[IList];
1558 else if (StructuredIndex < StructuredList->getNumInits())
1559 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Douglas Gregor4c678342009-01-28 21:54:33 +00001561 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1562 return Result;
1563
1564 if (ExistingInit) {
1565 // We are creating an initializer list that initializes the
1566 // subobjects of the current object, but there was already an
1567 // initialization that completely initialized the current
1568 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001569 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001570 // struct X { int a, b; };
1571 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001572 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001573 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1574 // designated initializer re-initializes the whole
1575 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001576 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001577 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001578 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001579 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001580 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001581 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001582 << ExistingInit->getSourceRange();
1583 }
1584
Mike Stump1eb44332009-09-09 15:08:12 +00001585 InitListExpr *Result
1586 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001587 InitRange.getEnd());
1588
Douglas Gregor4c678342009-01-28 21:54:33 +00001589 Result->setType(CurrentObjectType);
1590
Douglas Gregorfa219202009-03-20 23:58:33 +00001591 // Pre-allocate storage for the structured initializer list.
1592 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001593 unsigned NumInits = 0;
1594 if (!StructuredList)
1595 NumInits = IList->getNumInits();
1596 else if (Index < IList->getNumInits()) {
1597 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1598 NumInits = SubList->getNumInits();
1599 }
1600
Mike Stump1eb44332009-09-09 15:08:12 +00001601 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001602 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1603 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1604 NumElements = CAType->getSize().getZExtValue();
1605 // Simple heuristic so that we don't allocate a very large
1606 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001607 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001608 NumElements = 0;
1609 }
John McCall183700f2009-09-21 23:43:11 +00001610 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001611 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001612 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001613 RecordDecl *RDecl = RType->getDecl();
1614 if (RDecl->isUnion())
1615 NumElements = 1;
1616 else
Mike Stump1eb44332009-09-09 15:08:12 +00001617 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001618 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001619 }
1620
Douglas Gregor08457732009-03-21 18:13:52 +00001621 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001622 NumElements = IList->getNumInits();
1623
1624 Result->reserveInits(NumElements);
1625
Douglas Gregor4c678342009-01-28 21:54:33 +00001626 // Link this new initializer list into the structured initializer
1627 // lists.
1628 if (StructuredList)
1629 StructuredList->updateInit(StructuredIndex, Result);
1630 else {
1631 Result->setSyntacticForm(IList);
1632 SyntacticToSemantic[IList] = Result;
1633 }
1634
1635 return Result;
1636}
1637
1638/// Update the initializer at index @p StructuredIndex within the
1639/// structured initializer list to the value @p expr.
1640void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1641 unsigned &StructuredIndex,
1642 Expr *expr) {
1643 // No structured initializer list to update
1644 if (!StructuredList)
1645 return;
1646
1647 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1648 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001649 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001650 diag::warn_initializer_overrides)
1651 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001652 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001653 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001654 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001655 << PrevInit->getSourceRange();
1656 }
Mike Stump1eb44332009-09-09 15:08:12 +00001657
Douglas Gregor4c678342009-01-28 21:54:33 +00001658 ++StructuredIndex;
1659}
1660
Douglas Gregor05c13a32009-01-22 00:58:24 +00001661/// Check that the given Index expression is a valid array designator
1662/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001663/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001664/// and produces a reasonable diagnostic if there is a
1665/// failure. Returns true if there was an error, false otherwise. If
1666/// everything went okay, Value will receive the value of the constant
1667/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001668static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001669CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001670 SourceLocation Loc = Index->getSourceRange().getBegin();
1671
1672 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001673 if (S.VerifyIntegerConstantExpression(Index, &Value))
1674 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001675
Chris Lattner3bf68932009-04-25 21:59:05 +00001676 if (Value.isSigned() && Value.isNegative())
1677 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001678 << Value.toString(10) << Index->getSourceRange();
1679
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001680 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001681 return false;
1682}
1683
1684Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1685 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001686 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001687 OwningExprResult Init) {
1688 typedef DesignatedInitExpr::Designator ASTDesignator;
1689
1690 bool Invalid = false;
1691 llvm::SmallVector<ASTDesignator, 32> Designators;
1692 llvm::SmallVector<Expr *, 32> InitExpressions;
1693
1694 // Build designators and check array designator expressions.
1695 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1696 const Designator &D = Desig.getDesignator(Idx);
1697 switch (D.getKind()) {
1698 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001699 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001700 D.getFieldLoc()));
1701 break;
1702
1703 case Designator::ArrayDesignator: {
1704 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1705 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001706 if (!Index->isTypeDependent() &&
1707 !Index->isValueDependent() &&
1708 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001709 Invalid = true;
1710 else {
1711 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001712 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001713 D.getRBracketLoc()));
1714 InitExpressions.push_back(Index);
1715 }
1716 break;
1717 }
1718
1719 case Designator::ArrayRangeDesignator: {
1720 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1721 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1722 llvm::APSInt StartValue;
1723 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001724 bool StartDependent = StartIndex->isTypeDependent() ||
1725 StartIndex->isValueDependent();
1726 bool EndDependent = EndIndex->isTypeDependent() ||
1727 EndIndex->isValueDependent();
1728 if ((!StartDependent &&
1729 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1730 (!EndDependent &&
1731 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001732 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001733 else {
1734 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001735 if (StartDependent || EndDependent) {
1736 // Nothing to compute.
1737 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001738 EndValue.extend(StartValue.getBitWidth());
1739 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1740 StartValue.extend(EndValue.getBitWidth());
1741
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001742 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001743 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001744 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001745 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1746 Invalid = true;
1747 } else {
1748 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001749 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001750 D.getEllipsisLoc(),
1751 D.getRBracketLoc()));
1752 InitExpressions.push_back(StartIndex);
1753 InitExpressions.push_back(EndIndex);
1754 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001755 }
1756 break;
1757 }
1758 }
1759 }
1760
1761 if (Invalid || Init.isInvalid())
1762 return ExprError();
1763
1764 // Clear out the expressions within the designation.
1765 Desig.ClearExprs(*this);
1766
1767 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001768 = DesignatedInitExpr::Create(Context,
1769 Designators.data(), Designators.size(),
1770 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001771 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001772 return Owned(DIE);
1773}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001774
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001775bool Sema::CheckInitList(const InitializedEntity &Entity,
1776 InitListExpr *&InitList, QualType &DeclType) {
1777 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001778 if (!CheckInitList.HadError())
1779 InitList = CheckInitList.getFullyStructuredList();
1780
1781 return CheckInitList.HadError();
1782}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001783
Douglas Gregor20093b42009-12-09 23:02:17 +00001784//===----------------------------------------------------------------------===//
1785// Initialization entity
1786//===----------------------------------------------------------------------===//
1787
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001788InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1789 const InitializedEntity &Parent)
1790 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1791{
Douglas Gregord6542d82009-12-22 15:35:07 +00001792 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType()))
1793 Type = AT->getElementType();
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001794 else
Douglas Gregord6542d82009-12-22 15:35:07 +00001795 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001796}
1797
1798InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1799 CXXBaseSpecifier *Base)
1800{
1801 InitializedEntity Result;
1802 Result.Kind = EK_Base;
1803 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001804 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001805 return Result;
1806}
1807
Douglas Gregor99a2e602009-12-16 01:38:02 +00001808DeclarationName InitializedEntity::getName() const {
1809 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001810 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001811 if (!VariableOrMember)
1812 return DeclarationName();
1813 // Fall through
1814
1815 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001816 case EK_Member:
1817 return VariableOrMember->getDeclName();
1818
1819 case EK_Result:
1820 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001821 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001822 case EK_Temporary:
1823 case EK_Base:
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001824 case EK_ArrayOrVectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001825 return DeclarationName();
1826 }
1827
1828 // Silence GCC warning
1829 return DeclarationName();
1830}
1831
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001832DeclaratorDecl *InitializedEntity::getDecl() const {
1833 switch (getKind()) {
1834 case EK_Variable:
1835 case EK_Parameter:
1836 case EK_Member:
1837 return VariableOrMember;
1838
1839 case EK_Result:
1840 case EK_Exception:
1841 case EK_New:
1842 case EK_Temporary:
1843 case EK_Base:
1844 case EK_ArrayOrVectorElement:
1845 return 0;
1846 }
1847
1848 // Silence GCC warning
1849 return 0;
1850}
1851
Douglas Gregor20093b42009-12-09 23:02:17 +00001852//===----------------------------------------------------------------------===//
1853// Initialization sequence
1854//===----------------------------------------------------------------------===//
1855
1856void InitializationSequence::Step::Destroy() {
1857 switch (Kind) {
1858 case SK_ResolveAddressOfOverloadedFunction:
1859 case SK_CastDerivedToBaseRValue:
1860 case SK_CastDerivedToBaseLValue:
1861 case SK_BindReference:
1862 case SK_BindReferenceToTemporary:
1863 case SK_UserConversion:
1864 case SK_QualificationConversionRValue:
1865 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001866 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001867 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001868 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001869 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001870 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001871 break;
1872
1873 case SK_ConversionSequence:
1874 delete ICS;
1875 }
1876}
1877
1878void InitializationSequence::AddAddressOverloadResolutionStep(
1879 FunctionDecl *Function) {
1880 Step S;
1881 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1882 S.Type = Function->getType();
1883 S.Function = Function;
1884 Steps.push_back(S);
1885}
1886
1887void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1888 bool IsLValue) {
1889 Step S;
1890 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1891 S.Type = BaseType;
1892 Steps.push_back(S);
1893}
1894
1895void InitializationSequence::AddReferenceBindingStep(QualType T,
1896 bool BindingTemporary) {
1897 Step S;
1898 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1899 S.Type = T;
1900 Steps.push_back(S);
1901}
1902
Eli Friedman03981012009-12-11 02:42:07 +00001903void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1904 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001905 Step S;
1906 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00001907 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00001908 S.Function = Function;
1909 Steps.push_back(S);
1910}
1911
1912void InitializationSequence::AddQualificationConversionStep(QualType Ty,
1913 bool IsLValue) {
1914 Step S;
1915 S.Kind = IsLValue? SK_QualificationConversionLValue
1916 : SK_QualificationConversionRValue;
1917 S.Type = Ty;
1918 Steps.push_back(S);
1919}
1920
1921void InitializationSequence::AddConversionSequenceStep(
1922 const ImplicitConversionSequence &ICS,
1923 QualType T) {
1924 Step S;
1925 S.Kind = SK_ConversionSequence;
1926 S.Type = T;
1927 S.ICS = new ImplicitConversionSequence(ICS);
1928 Steps.push_back(S);
1929}
1930
Douglas Gregord87b61f2009-12-10 17:56:55 +00001931void InitializationSequence::AddListInitializationStep(QualType T) {
1932 Step S;
1933 S.Kind = SK_ListInitialization;
1934 S.Type = T;
1935 Steps.push_back(S);
1936}
1937
Douglas Gregor51c56d62009-12-14 20:49:26 +00001938void
1939InitializationSequence::AddConstructorInitializationStep(
1940 CXXConstructorDecl *Constructor,
1941 QualType T) {
1942 Step S;
1943 S.Kind = SK_ConstructorInitialization;
1944 S.Type = T;
1945 S.Function = Constructor;
1946 Steps.push_back(S);
1947}
1948
Douglas Gregor71d17402009-12-15 00:01:57 +00001949void InitializationSequence::AddZeroInitializationStep(QualType T) {
1950 Step S;
1951 S.Kind = SK_ZeroInitialization;
1952 S.Type = T;
1953 Steps.push_back(S);
1954}
1955
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001956void InitializationSequence::AddCAssignmentStep(QualType T) {
1957 Step S;
1958 S.Kind = SK_CAssignment;
1959 S.Type = T;
1960 Steps.push_back(S);
1961}
1962
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001963void InitializationSequence::AddStringInitStep(QualType T) {
1964 Step S;
1965 S.Kind = SK_StringInit;
1966 S.Type = T;
1967 Steps.push_back(S);
1968}
1969
Douglas Gregor20093b42009-12-09 23:02:17 +00001970void InitializationSequence::SetOverloadFailure(FailureKind Failure,
1971 OverloadingResult Result) {
1972 SequenceKind = FailedSequence;
1973 this->Failure = Failure;
1974 this->FailedOverloadResult = Result;
1975}
1976
1977//===----------------------------------------------------------------------===//
1978// Attempt initialization
1979//===----------------------------------------------------------------------===//
1980
1981/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00001982static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00001983 const InitializedEntity &Entity,
1984 const InitializationKind &Kind,
1985 InitListExpr *InitList,
1986 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00001987 // FIXME: We only perform rudimentary checking of list
1988 // initializations at this point, then assume that any list
1989 // initialization of an array, aggregate, or scalar will be
1990 // well-formed. We we actually "perform" list initialization, we'll
1991 // do all of the necessary checking. C++0x initializer lists will
1992 // force us to perform more checking here.
1993 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
1994
Douglas Gregord6542d82009-12-22 15:35:07 +00001995 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00001996
1997 // C++ [dcl.init]p13:
1998 // If T is a scalar type, then a declaration of the form
1999 //
2000 // T x = { a };
2001 //
2002 // is equivalent to
2003 //
2004 // T x = a;
2005 if (DestType->isScalarType()) {
2006 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2007 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2008 return;
2009 }
2010
2011 // Assume scalar initialization from a single value works.
2012 } else if (DestType->isAggregateType()) {
2013 // Assume aggregate initialization works.
2014 } else if (DestType->isVectorType()) {
2015 // Assume vector initialization works.
2016 } else if (DestType->isReferenceType()) {
2017 // FIXME: C++0x defines behavior for this.
2018 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2019 return;
2020 } else if (DestType->isRecordType()) {
2021 // FIXME: C++0x defines behavior for this
2022 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2023 }
2024
2025 // Add a general "list initialization" step.
2026 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002027}
2028
2029/// \brief Try a reference initialization that involves calling a conversion
2030/// function.
2031///
2032/// FIXME: look intos DRs 656, 896
2033static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2034 const InitializedEntity &Entity,
2035 const InitializationKind &Kind,
2036 Expr *Initializer,
2037 bool AllowRValues,
2038 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002039 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002040 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2041 QualType T1 = cv1T1.getUnqualifiedType();
2042 QualType cv2T2 = Initializer->getType();
2043 QualType T2 = cv2T2.getUnqualifiedType();
2044
2045 bool DerivedToBase;
2046 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2047 T1, T2, DerivedToBase) &&
2048 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002049 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002050
2051 // Build the candidate set directly in the initialization sequence
2052 // structure, so that it will persist if we fail.
2053 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2054 CandidateSet.clear();
2055
2056 // Determine whether we are allowed to call explicit constructors or
2057 // explicit conversion operators.
2058 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2059
2060 const RecordType *T1RecordType = 0;
2061 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2062 // The type we're converting to is a class type. Enumerate its constructors
2063 // to see if there is a suitable conversion.
2064 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2065
2066 DeclarationName ConstructorName
2067 = S.Context.DeclarationNames.getCXXConstructorName(
2068 S.Context.getCanonicalType(T1).getUnqualifiedType());
2069 DeclContext::lookup_iterator Con, ConEnd;
2070 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2071 Con != ConEnd; ++Con) {
2072 // Find the constructor (which may be a template).
2073 CXXConstructorDecl *Constructor = 0;
2074 FunctionTemplateDecl *ConstructorTmpl
2075 = dyn_cast<FunctionTemplateDecl>(*Con);
2076 if (ConstructorTmpl)
2077 Constructor = cast<CXXConstructorDecl>(
2078 ConstructorTmpl->getTemplatedDecl());
2079 else
2080 Constructor = cast<CXXConstructorDecl>(*Con);
2081
2082 if (!Constructor->isInvalidDecl() &&
2083 Constructor->isConvertingConstructor(AllowExplicit)) {
2084 if (ConstructorTmpl)
2085 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2086 &Initializer, 1, CandidateSet);
2087 else
2088 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2089 }
2090 }
2091 }
2092
2093 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2094 // The type we're converting from is a class type, enumerate its conversion
2095 // functions.
2096 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2097
2098 // Determine the type we are converting to. If we are allowed to
2099 // convert to an rvalue, take the type that the destination type
2100 // refers to.
2101 QualType ToType = AllowRValues? cv1T1 : DestType;
2102
2103 const UnresolvedSet *Conversions
2104 = T2RecordDecl->getVisibleConversionFunctions();
2105 for (UnresolvedSet::iterator I = Conversions->begin(),
2106 E = Conversions->end();
2107 I != E; ++I) {
2108 NamedDecl *D = *I;
2109 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2110 if (isa<UsingShadowDecl>(D))
2111 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2112
2113 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2114 CXXConversionDecl *Conv;
2115 if (ConvTemplate)
2116 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2117 else
2118 Conv = cast<CXXConversionDecl>(*I);
2119
2120 // If the conversion function doesn't return a reference type,
2121 // it can't be considered for this conversion unless we're allowed to
2122 // consider rvalues.
2123 // FIXME: Do we need to make sure that we only consider conversion
2124 // candidates with reference-compatible results? That might be needed to
2125 // break recursion.
2126 if ((AllowExplicit || !Conv->isExplicit()) &&
2127 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2128 if (ConvTemplate)
2129 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2130 ToType, CandidateSet);
2131 else
2132 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2133 CandidateSet);
2134 }
2135 }
2136 }
2137
2138 SourceLocation DeclLoc = Initializer->getLocStart();
2139
2140 // Perform overload resolution. If it fails, return the failed result.
2141 OverloadCandidateSet::iterator Best;
2142 if (OverloadingResult Result
2143 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2144 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002145
Douglas Gregor20093b42009-12-09 23:02:17 +00002146 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002147
2148 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002149 if (isa<CXXConversionDecl>(Function))
2150 T2 = Function->getResultType();
2151 else
2152 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002153
2154 // Add the user-defined conversion step.
2155 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2156
2157 // Determine whether we need to perform derived-to-base or
2158 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002159 bool NewDerivedToBase = false;
2160 Sema::ReferenceCompareResult NewRefRelationship
2161 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2162 NewDerivedToBase);
2163 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2164 "Overload resolution picked a bad conversion function");
2165 (void)NewRefRelationship;
2166 if (NewDerivedToBase)
2167 Sequence.AddDerivedToBaseCastStep(
2168 S.Context.getQualifiedType(T1,
2169 T2.getNonReferenceType().getQualifiers()),
2170 /*isLValue=*/true);
2171
2172 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2173 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2174
2175 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2176 return OR_Success;
2177}
2178
2179/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2180static void TryReferenceInitialization(Sema &S,
2181 const InitializedEntity &Entity,
2182 const InitializationKind &Kind,
2183 Expr *Initializer,
2184 InitializationSequence &Sequence) {
2185 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2186
Douglas Gregord6542d82009-12-22 15:35:07 +00002187 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002188 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2189 QualType T1 = cv1T1.getUnqualifiedType();
2190 QualType cv2T2 = Initializer->getType();
2191 QualType T2 = cv2T2.getUnqualifiedType();
2192 SourceLocation DeclLoc = Initializer->getLocStart();
2193
2194 // If the initializer is the address of an overloaded function, try
2195 // to resolve the overloaded function. If all goes well, T2 is the
2196 // type of the resulting function.
2197 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2198 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2199 T1,
2200 false);
2201 if (!Fn) {
2202 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2203 return;
2204 }
2205
2206 Sequence.AddAddressOverloadResolutionStep(Fn);
2207 cv2T2 = Fn->getType();
2208 T2 = cv2T2.getUnqualifiedType();
2209 }
2210
2211 // FIXME: Rvalue references
2212 bool ForceRValue = false;
2213
2214 // Compute some basic properties of the types and the initializer.
2215 bool isLValueRef = DestType->isLValueReferenceType();
2216 bool isRValueRef = !isLValueRef;
2217 bool DerivedToBase = false;
2218 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2219 Initializer->isLvalue(S.Context);
2220 Sema::ReferenceCompareResult RefRelationship
2221 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2222
2223 // C++0x [dcl.init.ref]p5:
2224 // A reference to type "cv1 T1" is initialized by an expression of type
2225 // "cv2 T2" as follows:
2226 //
2227 // - If the reference is an lvalue reference and the initializer
2228 // expression
2229 OverloadingResult ConvOvlResult = OR_Success;
2230 if (isLValueRef) {
2231 if (InitLvalue == Expr::LV_Valid &&
2232 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2233 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2234 // reference-compatible with "cv2 T2," or
2235 //
2236 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2237 // bit-field when we're determining whether the reference initialization
2238 // can occur. This property will be checked by PerformInitialization.
2239 if (DerivedToBase)
2240 Sequence.AddDerivedToBaseCastStep(
2241 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2242 /*isLValue=*/true);
2243 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2244 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2245 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2246 return;
2247 }
2248
2249 // - has a class type (i.e., T2 is a class type), where T1 is not
2250 // reference-related to T2, and can be implicitly converted to an
2251 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2252 // with "cv3 T3" (this conversion is selected by enumerating the
2253 // applicable conversion functions (13.3.1.6) and choosing the best
2254 // one through overload resolution (13.3)),
2255 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2256 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2257 Initializer,
2258 /*AllowRValues=*/false,
2259 Sequence);
2260 if (ConvOvlResult == OR_Success)
2261 return;
2262 }
2263 }
2264
2265 // - Otherwise, the reference shall be an lvalue reference to a
2266 // non-volatile const type (i.e., cv1 shall be const), or the reference
2267 // shall be an rvalue reference and the initializer expression shall
2268 // be an rvalue.
2269 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2270 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2271 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2272 Sequence.SetOverloadFailure(
2273 InitializationSequence::FK_ReferenceInitOverloadFailed,
2274 ConvOvlResult);
2275 else if (isLValueRef)
2276 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2277 ? (RefRelationship == Sema::Ref_Related
2278 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2279 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2280 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2281 else
2282 Sequence.SetFailed(
2283 InitializationSequence::FK_RValueReferenceBindingToLValue);
2284
2285 return;
2286 }
2287
2288 // - If T1 and T2 are class types and
2289 if (T1->isRecordType() && T2->isRecordType()) {
2290 // - the initializer expression is an rvalue and "cv1 T1" is
2291 // reference-compatible with "cv2 T2", or
2292 if (InitLvalue != Expr::LV_Valid &&
2293 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2294 if (DerivedToBase)
2295 Sequence.AddDerivedToBaseCastStep(
2296 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2297 /*isLValue=*/false);
2298 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2299 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2300 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2301 return;
2302 }
2303
2304 // - T1 is not reference-related to T2 and the initializer expression
2305 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2306 // conversion is selected by enumerating the applicable conversion
2307 // functions (13.3.1.6) and choosing the best one through overload
2308 // resolution (13.3)),
2309 if (RefRelationship == Sema::Ref_Incompatible) {
2310 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2311 Kind, Initializer,
2312 /*AllowRValues=*/true,
2313 Sequence);
2314 if (ConvOvlResult)
2315 Sequence.SetOverloadFailure(
2316 InitializationSequence::FK_ReferenceInitOverloadFailed,
2317 ConvOvlResult);
2318
2319 return;
2320 }
2321
2322 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2323 return;
2324 }
2325
2326 // - If the initializer expression is an rvalue, with T2 an array type,
2327 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2328 // is bound to the object represented by the rvalue (see 3.10).
2329 // FIXME: How can an array type be reference-compatible with anything?
2330 // Don't we mean the element types of T1 and T2?
2331
2332 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2333 // from the initializer expression using the rules for a non-reference
2334 // copy initialization (8.5). The reference is then bound to the
2335 // temporary. [...]
2336 // Determine whether we are allowed to call explicit constructors or
2337 // explicit conversion operators.
2338 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2339 ImplicitConversionSequence ICS
2340 = S.TryImplicitConversion(Initializer, cv1T1,
2341 /*SuppressUserConversions=*/false, AllowExplicit,
2342 /*ForceRValue=*/false,
2343 /*FIXME:InOverloadResolution=*/false,
2344 /*UserCast=*/Kind.isExplicitCast());
2345
2346 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2347 // FIXME: Use the conversion function set stored in ICS to turn
2348 // this into an overloading ambiguity diagnostic. However, we need
2349 // to keep that set as an OverloadCandidateSet rather than as some
2350 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002351 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2352 Sequence.SetOverloadFailure(
2353 InitializationSequence::FK_ReferenceInitOverloadFailed,
2354 ConvOvlResult);
2355 else
2356 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002357 return;
2358 }
2359
2360 // [...] If T1 is reference-related to T2, cv1 must be the
2361 // same cv-qualification as, or greater cv-qualification
2362 // than, cv2; otherwise, the program is ill-formed.
2363 if (RefRelationship == Sema::Ref_Related &&
2364 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2365 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2366 return;
2367 }
2368
2369 // Perform the actual conversion.
2370 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2371 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2372 return;
2373}
2374
2375/// \brief Attempt character array initialization from a string literal
2376/// (C++ [dcl.init.string], C99 6.7.8).
2377static void TryStringLiteralInitialization(Sema &S,
2378 const InitializedEntity &Entity,
2379 const InitializationKind &Kind,
2380 Expr *Initializer,
2381 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002382 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002383 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002384}
2385
Douglas Gregor20093b42009-12-09 23:02:17 +00002386/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2387/// enumerates the constructors of the initialized entity and performs overload
2388/// resolution to select the best.
2389static void TryConstructorInitialization(Sema &S,
2390 const InitializedEntity &Entity,
2391 const InitializationKind &Kind,
2392 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002393 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002394 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002395 if (Kind.getKind() == InitializationKind::IK_Copy)
2396 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2397 else
2398 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002399
2400 // Build the candidate set directly in the initialization sequence
2401 // structure, so that it will persist if we fail.
2402 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2403 CandidateSet.clear();
2404
2405 // Determine whether we are allowed to call explicit constructors or
2406 // explicit conversion operators.
2407 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2408 Kind.getKind() == InitializationKind::IK_Value ||
2409 Kind.getKind() == InitializationKind::IK_Default);
2410
2411 // The type we're converting to is a class type. Enumerate its constructors
2412 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002413 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2414 assert(DestRecordType && "Constructor initialization requires record type");
2415 CXXRecordDecl *DestRecordDecl
2416 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2417
2418 DeclarationName ConstructorName
2419 = S.Context.DeclarationNames.getCXXConstructorName(
2420 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2421 DeclContext::lookup_iterator Con, ConEnd;
2422 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2423 Con != ConEnd; ++Con) {
2424 // Find the constructor (which may be a template).
2425 CXXConstructorDecl *Constructor = 0;
2426 FunctionTemplateDecl *ConstructorTmpl
2427 = dyn_cast<FunctionTemplateDecl>(*Con);
2428 if (ConstructorTmpl)
2429 Constructor = cast<CXXConstructorDecl>(
2430 ConstructorTmpl->getTemplatedDecl());
2431 else
2432 Constructor = cast<CXXConstructorDecl>(*Con);
2433
2434 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002435 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002436 if (ConstructorTmpl)
2437 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2438 Args, NumArgs, CandidateSet);
2439 else
2440 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2441 }
2442 }
2443
2444 SourceLocation DeclLoc = Kind.getLocation();
2445
2446 // Perform overload resolution. If it fails, return the failed result.
2447 OverloadCandidateSet::iterator Best;
2448 if (OverloadingResult Result
2449 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2450 Sequence.SetOverloadFailure(
2451 InitializationSequence::FK_ConstructorOverloadFailed,
2452 Result);
2453 return;
2454 }
2455
2456 // Add the constructor initialization step. Any cv-qualification conversion is
2457 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002458 if (Kind.getKind() == InitializationKind::IK_Copy) {
2459 Sequence.AddUserConversionStep(Best->Function, DestType);
2460 } else {
2461 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002462 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002463 DestType);
2464 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002465}
2466
Douglas Gregor71d17402009-12-15 00:01:57 +00002467/// \brief Attempt value initialization (C++ [dcl.init]p7).
2468static void TryValueInitialization(Sema &S,
2469 const InitializedEntity &Entity,
2470 const InitializationKind &Kind,
2471 InitializationSequence &Sequence) {
2472 // C++ [dcl.init]p5:
2473 //
2474 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002475 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002476
2477 // -- if T is an array type, then each element is value-initialized;
2478 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2479 T = AT->getElementType();
2480
2481 if (const RecordType *RT = T->getAs<RecordType>()) {
2482 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2483 // -- if T is a class type (clause 9) with a user-declared
2484 // constructor (12.1), then the default constructor for T is
2485 // called (and the initialization is ill-formed if T has no
2486 // accessible default constructor);
2487 //
2488 // FIXME: we really want to refer to a single subobject of the array,
2489 // but Entity doesn't have a way to capture that (yet).
2490 if (ClassDecl->hasUserDeclaredConstructor())
2491 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2492
Douglas Gregor16006c92009-12-16 18:50:27 +00002493 // -- if T is a (possibly cv-qualified) non-union class type
2494 // without a user-provided constructor, then the object is
2495 // zero-initialized and, if T’s implicitly-declared default
2496 // constructor is non-trivial, that constructor is called.
2497 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2498 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2499 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002500 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002501 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2502 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002503 }
2504 }
2505
Douglas Gregord6542d82009-12-22 15:35:07 +00002506 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002507 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2508}
2509
Douglas Gregor99a2e602009-12-16 01:38:02 +00002510/// \brief Attempt default initialization (C++ [dcl.init]p6).
2511static void TryDefaultInitialization(Sema &S,
2512 const InitializedEntity &Entity,
2513 const InitializationKind &Kind,
2514 InitializationSequence &Sequence) {
2515 assert(Kind.getKind() == InitializationKind::IK_Default);
2516
2517 // C++ [dcl.init]p6:
2518 // To default-initialize an object of type T means:
2519 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002520 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002521 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2522 DestType = Array->getElementType();
2523
2524 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2525 // constructor for T is called (and the initialization is ill-formed if
2526 // T has no accessible default constructor);
2527 if (DestType->isRecordType()) {
2528 // FIXME: If a program calls for the default initialization of an object of
2529 // a const-qualified type T, T shall be a class type with a user-provided
2530 // default constructor.
2531 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2532 Sequence);
2533 }
2534
2535 // - otherwise, no initialization is performed.
2536 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2537
2538 // If a program calls for the default initialization of an object of
2539 // a const-qualified type T, T shall be a class type with a user-provided
2540 // default constructor.
2541 if (DestType.isConstQualified())
2542 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2543}
2544
Douglas Gregor20093b42009-12-09 23:02:17 +00002545/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2546/// which enumerates all conversion functions and performs overload resolution
2547/// to select the best.
2548static void TryUserDefinedConversion(Sema &S,
2549 const InitializedEntity &Entity,
2550 const InitializationKind &Kind,
2551 Expr *Initializer,
2552 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002553 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2554
Douglas Gregord6542d82009-12-22 15:35:07 +00002555 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002556 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2557 QualType SourceType = Initializer->getType();
2558 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2559 "Must have a class type to perform a user-defined conversion");
2560
2561 // Build the candidate set directly in the initialization sequence
2562 // structure, so that it will persist if we fail.
2563 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2564 CandidateSet.clear();
2565
2566 // Determine whether we are allowed to call explicit constructors or
2567 // explicit conversion operators.
2568 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2569
2570 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2571 // The type we're converting to is a class type. Enumerate its constructors
2572 // to see if there is a suitable conversion.
2573 CXXRecordDecl *DestRecordDecl
2574 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2575
2576 DeclarationName ConstructorName
2577 = S.Context.DeclarationNames.getCXXConstructorName(
2578 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2579 DeclContext::lookup_iterator Con, ConEnd;
2580 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2581 Con != ConEnd; ++Con) {
2582 // Find the constructor (which may be a template).
2583 CXXConstructorDecl *Constructor = 0;
2584 FunctionTemplateDecl *ConstructorTmpl
2585 = dyn_cast<FunctionTemplateDecl>(*Con);
2586 if (ConstructorTmpl)
2587 Constructor = cast<CXXConstructorDecl>(
2588 ConstructorTmpl->getTemplatedDecl());
2589 else
2590 Constructor = cast<CXXConstructorDecl>(*Con);
2591
2592 if (!Constructor->isInvalidDecl() &&
2593 Constructor->isConvertingConstructor(AllowExplicit)) {
2594 if (ConstructorTmpl)
2595 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2596 &Initializer, 1, CandidateSet);
2597 else
2598 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2599 }
2600 }
2601 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002602
2603 SourceLocation DeclLoc = Initializer->getLocStart();
2604
Douglas Gregor4a520a22009-12-14 17:27:33 +00002605 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2606 // The type we're converting from is a class type, enumerate its conversion
2607 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002608
Eli Friedman33c2da92009-12-20 22:12:03 +00002609 // We can only enumerate the conversion functions for a complete type; if
2610 // the type isn't complete, simply skip this step.
2611 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2612 CXXRecordDecl *SourceRecordDecl
2613 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002614
Eli Friedman33c2da92009-12-20 22:12:03 +00002615 const UnresolvedSet *Conversions
2616 = SourceRecordDecl->getVisibleConversionFunctions();
2617 for (UnresolvedSet::iterator I = Conversions->begin(),
2618 E = Conversions->end();
2619 I != E; ++I) {
2620 NamedDecl *D = *I;
2621 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2622 if (isa<UsingShadowDecl>(D))
2623 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2624
2625 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2626 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002627 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002628 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002629 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002630 Conv = cast<CXXConversionDecl>(*I);
2631
2632 if (AllowExplicit || !Conv->isExplicit()) {
2633 if (ConvTemplate)
2634 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2635 Initializer, DestType,
2636 CandidateSet);
2637 else
2638 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2639 CandidateSet);
2640 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002641 }
2642 }
2643 }
2644
Douglas Gregor4a520a22009-12-14 17:27:33 +00002645 // Perform overload resolution. If it fails, return the failed result.
2646 OverloadCandidateSet::iterator Best;
2647 if (OverloadingResult Result
2648 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2649 Sequence.SetOverloadFailure(
2650 InitializationSequence::FK_UserConversionOverloadFailed,
2651 Result);
2652 return;
2653 }
2654
2655 FunctionDecl *Function = Best->Function;
2656
2657 if (isa<CXXConstructorDecl>(Function)) {
2658 // Add the user-defined conversion step. Any cv-qualification conversion is
2659 // subsumed by the initialization.
2660 Sequence.AddUserConversionStep(Function, DestType);
2661 return;
2662 }
2663
2664 // Add the user-defined conversion step that calls the conversion function.
2665 QualType ConvType = Function->getResultType().getNonReferenceType();
2666 Sequence.AddUserConversionStep(Function, ConvType);
2667
2668 // If the conversion following the call to the conversion function is
2669 // interesting, add it as a separate step.
2670 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2671 Best->FinalConversion.Third) {
2672 ImplicitConversionSequence ICS;
2673 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2674 ICS.Standard = Best->FinalConversion;
2675 Sequence.AddConversionSequenceStep(ICS, DestType);
2676 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002677}
2678
2679/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2680/// non-class type to another.
2681static void TryImplicitConversion(Sema &S,
2682 const InitializedEntity &Entity,
2683 const InitializationKind &Kind,
2684 Expr *Initializer,
2685 InitializationSequence &Sequence) {
2686 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002687 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002688 /*SuppressUserConversions=*/true,
2689 /*AllowExplicit=*/false,
2690 /*ForceRValue=*/false,
2691 /*FIXME:InOverloadResolution=*/false,
2692 /*UserCast=*/Kind.isExplicitCast());
2693
2694 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2695 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2696 return;
2697 }
2698
Douglas Gregord6542d82009-12-22 15:35:07 +00002699 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002700}
2701
2702InitializationSequence::InitializationSequence(Sema &S,
2703 const InitializedEntity &Entity,
2704 const InitializationKind &Kind,
2705 Expr **Args,
2706 unsigned NumArgs) {
2707 ASTContext &Context = S.Context;
2708
2709 // C++0x [dcl.init]p16:
2710 // The semantics of initializers are as follows. The destination type is
2711 // the type of the object or reference being initialized and the source
2712 // type is the type of the initializer expression. The source type is not
2713 // defined when the initializer is a braced-init-list or when it is a
2714 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002715 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002716
2717 if (DestType->isDependentType() ||
2718 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2719 SequenceKind = DependentSequence;
2720 return;
2721 }
2722
2723 QualType SourceType;
2724 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002725 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002726 Initializer = Args[0];
2727 if (!isa<InitListExpr>(Initializer))
2728 SourceType = Initializer->getType();
2729 }
2730
2731 // - If the initializer is a braced-init-list, the object is
2732 // list-initialized (8.5.4).
2733 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2734 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002735 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002736 }
2737
2738 // - If the destination type is a reference type, see 8.5.3.
2739 if (DestType->isReferenceType()) {
2740 // C++0x [dcl.init.ref]p1:
2741 // A variable declared to be a T& or T&&, that is, "reference to type T"
2742 // (8.3.2), shall be initialized by an object, or function, of type T or
2743 // by an object that can be converted into a T.
2744 // (Therefore, multiple arguments are not permitted.)
2745 if (NumArgs != 1)
2746 SetFailed(FK_TooManyInitsForReference);
2747 else
2748 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2749 return;
2750 }
2751
2752 // - If the destination type is an array of characters, an array of
2753 // char16_t, an array of char32_t, or an array of wchar_t, and the
2754 // initializer is a string literal, see 8.5.2.
2755 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2756 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2757 return;
2758 }
2759
2760 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002761 if (Kind.getKind() == InitializationKind::IK_Value ||
2762 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002763 TryValueInitialization(S, Entity, Kind, *this);
2764 return;
2765 }
2766
Douglas Gregor99a2e602009-12-16 01:38:02 +00002767 // Handle default initialization.
2768 if (Kind.getKind() == InitializationKind::IK_Default){
2769 TryDefaultInitialization(S, Entity, Kind, *this);
2770 return;
2771 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002772
Douglas Gregor20093b42009-12-09 23:02:17 +00002773 // - Otherwise, if the destination type is an array, the program is
2774 // ill-formed.
2775 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2776 if (AT->getElementType()->isAnyCharacterType())
2777 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2778 else
2779 SetFailed(FK_ArrayNeedsInitList);
2780
2781 return;
2782 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002783
2784 // Handle initialization in C
2785 if (!S.getLangOptions().CPlusPlus) {
2786 setSequenceKind(CAssignment);
2787 AddCAssignmentStep(DestType);
2788 return;
2789 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002790
2791 // - If the destination type is a (possibly cv-qualified) class type:
2792 if (DestType->isRecordType()) {
2793 // - If the initialization is direct-initialization, or if it is
2794 // copy-initialization where the cv-unqualified version of the
2795 // source type is the same class as, or a derived class of, the
2796 // class of the destination, constructors are considered. [...]
2797 if (Kind.getKind() == InitializationKind::IK_Direct ||
2798 (Kind.getKind() == InitializationKind::IK_Copy &&
2799 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2800 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002801 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00002802 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002803 // - Otherwise (i.e., for the remaining copy-initialization cases),
2804 // user-defined conversion sequences that can convert from the source
2805 // type to the destination type or (when a conversion function is
2806 // used) to a derived class thereof are enumerated as described in
2807 // 13.3.1.4, and the best one is chosen through overload resolution
2808 // (13.3).
2809 else
2810 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2811 return;
2812 }
2813
Douglas Gregor99a2e602009-12-16 01:38:02 +00002814 if (NumArgs > 1) {
2815 SetFailed(FK_TooManyInitsForScalar);
2816 return;
2817 }
2818 assert(NumArgs == 1 && "Zero-argument case handled above");
2819
Douglas Gregor20093b42009-12-09 23:02:17 +00002820 // - Otherwise, if the source type is a (possibly cv-qualified) class
2821 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002822 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002823 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2824 return;
2825 }
2826
2827 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002828 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002829 // conversions (Clause 4) will be used, if necessary, to convert the
2830 // initializer expression to the cv-unqualified version of the
2831 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002832 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002833 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2834}
2835
2836InitializationSequence::~InitializationSequence() {
2837 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2838 StepEnd = Steps.end();
2839 Step != StepEnd; ++Step)
2840 Step->Destroy();
2841}
2842
2843//===----------------------------------------------------------------------===//
2844// Perform initialization
2845//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002846static Sema::AssignmentAction
2847getAssignmentAction(const InitializedEntity &Entity) {
2848 switch(Entity.getKind()) {
2849 case InitializedEntity::EK_Variable:
2850 case InitializedEntity::EK_New:
2851 return Sema::AA_Initializing;
2852
2853 case InitializedEntity::EK_Parameter:
2854 // FIXME: Can we tell when we're sending vs. passing?
2855 return Sema::AA_Passing;
2856
2857 case InitializedEntity::EK_Result:
2858 return Sema::AA_Returning;
2859
2860 case InitializedEntity::EK_Exception:
2861 case InitializedEntity::EK_Base:
2862 llvm_unreachable("No assignment action for C++-specific initialization");
2863 break;
2864
2865 case InitializedEntity::EK_Temporary:
2866 // FIXME: Can we tell apart casting vs. converting?
2867 return Sema::AA_Casting;
2868
2869 case InitializedEntity::EK_Member:
2870 case InitializedEntity::EK_ArrayOrVectorElement:
2871 return Sema::AA_Initializing;
2872 }
2873
2874 return Sema::AA_Converting;
2875}
2876
2877static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2878 bool IsCopy) {
2879 switch (Entity.getKind()) {
2880 case InitializedEntity::EK_Result:
2881 case InitializedEntity::EK_Exception:
2882 return !IsCopy;
2883
2884 case InitializedEntity::EK_New:
2885 case InitializedEntity::EK_Variable:
2886 case InitializedEntity::EK_Base:
2887 case InitializedEntity::EK_Member:
2888 case InitializedEntity::EK_ArrayOrVectorElement:
2889 return false;
2890
2891 case InitializedEntity::EK_Parameter:
2892 case InitializedEntity::EK_Temporary:
2893 return true;
2894 }
2895
2896 llvm_unreachable("missed an InitializedEntity kind?");
2897}
2898
2899/// \brief If we need to perform an additional copy of the initialized object
2900/// for this kind of entity (e.g., the result of a function or an object being
2901/// thrown), make the copy.
2902static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
2903 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002904 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002905 Sema::OwningExprResult CurInit) {
2906 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002907
2908 switch (Entity.getKind()) {
2909 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00002910 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002911 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002912 Loc = Entity.getReturnLoc();
2913 break;
2914
2915 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002916 Loc = Entity.getThrowLoc();
2917 break;
2918
2919 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00002920 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002921 Kind.getKind() != InitializationKind::IK_Copy)
2922 return move(CurInit);
2923 Loc = Entity.getDecl()->getLocation();
2924 break;
2925
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002926 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002927 // FIXME: Do we need this initialization for a parameter?
2928 return move(CurInit);
2929
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002930 case InitializedEntity::EK_New:
2931 case InitializedEntity::EK_Temporary:
2932 case InitializedEntity::EK_Base:
2933 case InitializedEntity::EK_Member:
2934 case InitializedEntity::EK_ArrayOrVectorElement:
2935 // We don't need to copy for any of these initialized entities.
2936 return move(CurInit);
2937 }
2938
2939 Expr *CurInitExpr = (Expr *)CurInit.get();
2940 CXXRecordDecl *Class = 0;
2941 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
2942 Class = cast<CXXRecordDecl>(Record->getDecl());
2943 if (!Class)
2944 return move(CurInit);
2945
2946 // Perform overload resolution using the class's copy constructors.
2947 DeclarationName ConstructorName
2948 = S.Context.DeclarationNames.getCXXConstructorName(
2949 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
2950 DeclContext::lookup_iterator Con, ConEnd;
2951 OverloadCandidateSet CandidateSet;
2952 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
2953 Con != ConEnd; ++Con) {
2954 // Find the constructor (which may be a template).
2955 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
2956 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00002957 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002958 continue;
2959
2960 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
2961 }
2962
2963 OverloadCandidateSet::iterator Best;
2964 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
2965 case OR_Success:
2966 break;
2967
2968 case OR_No_Viable_Function:
2969 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002970 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002971 << CurInitExpr->getSourceRange();
2972 S.PrintOverloadCandidates(CandidateSet, false);
2973 return S.ExprError();
2974
2975 case OR_Ambiguous:
2976 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002977 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002978 << CurInitExpr->getSourceRange();
2979 S.PrintOverloadCandidates(CandidateSet, true);
2980 return S.ExprError();
2981
2982 case OR_Deleted:
2983 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002984 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002985 << CurInitExpr->getSourceRange();
2986 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
2987 << Best->Function->isDeleted();
2988 return S.ExprError();
2989 }
2990
2991 CurInit.release();
2992 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
2993 cast<CXXConstructorDecl>(Best->Function),
2994 /*Elidable=*/true,
2995 Sema::MultiExprArg(S,
2996 (void**)&CurInitExpr, 1));
2997}
Douglas Gregor20093b42009-12-09 23:02:17 +00002998
2999Action::OwningExprResult
3000InitializationSequence::Perform(Sema &S,
3001 const InitializedEntity &Entity,
3002 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003003 Action::MultiExprArg Args,
3004 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003005 if (SequenceKind == FailedSequence) {
3006 unsigned NumArgs = Args.size();
3007 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3008 return S.ExprError();
3009 }
3010
3011 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003012 // If the declaration is a non-dependent, incomplete array type
3013 // that has an initializer, then its type will be completed once
3014 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003015 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003016 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003017 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003018 if (const IncompleteArrayType *ArrayT
3019 = S.Context.getAsIncompleteArrayType(DeclType)) {
3020 // FIXME: We don't currently have the ability to accurately
3021 // compute the length of an initializer list without
3022 // performing full type-checking of the initializer list
3023 // (since we have to determine where braces are implicitly
3024 // introduced and such). So, we fall back to making the array
3025 // type a dependently-sized array type with no specified
3026 // bound.
3027 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3028 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003029
Douglas Gregord87b61f2009-12-10 17:56:55 +00003030 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003031 if (DeclaratorDecl *DD = Entity.getDecl()) {
3032 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3033 TypeLoc TL = TInfo->getTypeLoc();
3034 if (IncompleteArrayTypeLoc *ArrayLoc
3035 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3036 Brackets = ArrayLoc->getBracketsRange();
3037 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003038 }
3039
3040 *ResultType
3041 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3042 /*NumElts=*/0,
3043 ArrayT->getSizeModifier(),
3044 ArrayT->getIndexTypeCVRQualifiers(),
3045 Brackets);
3046 }
3047
3048 }
3049 }
3050
Eli Friedman08544622009-12-22 02:35:53 +00003051 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003052 return Sema::OwningExprResult(S, Args.release()[0]);
3053
3054 unsigned NumArgs = Args.size();
3055 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3056 SourceLocation(),
3057 (Expr **)Args.release(),
3058 NumArgs,
3059 SourceLocation()));
3060 }
3061
Douglas Gregor99a2e602009-12-16 01:38:02 +00003062 if (SequenceKind == NoInitialization)
3063 return S.Owned((Expr *)0);
3064
Douglas Gregord6542d82009-12-22 15:35:07 +00003065 QualType DestType = Entity.getType().getNonReferenceType();
3066 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003067 // the same as Entity.getDecl()->getType() in cases involving type merging,
3068 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003069 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003070 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003071 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003072
Douglas Gregor99a2e602009-12-16 01:38:02 +00003073 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3074
3075 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3076
3077 // For initialization steps that start with a single initializer,
3078 // grab the only argument out the Args and place it into the "current"
3079 // initializer.
3080 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003081 case SK_ResolveAddressOfOverloadedFunction:
3082 case SK_CastDerivedToBaseRValue:
3083 case SK_CastDerivedToBaseLValue:
3084 case SK_BindReference:
3085 case SK_BindReferenceToTemporary:
3086 case SK_UserConversion:
3087 case SK_QualificationConversionLValue:
3088 case SK_QualificationConversionRValue:
3089 case SK_ConversionSequence:
3090 case SK_ListInitialization:
3091 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003092 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003093 assert(Args.size() == 1);
3094 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3095 if (CurInit.isInvalid())
3096 return S.ExprError();
3097 break;
3098
3099 case SK_ConstructorInitialization:
3100 case SK_ZeroInitialization:
3101 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003102 }
3103
3104 // Walk through the computed steps for the initialization sequence,
3105 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003106 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003107 for (step_iterator Step = step_begin(), StepEnd = step_end();
3108 Step != StepEnd; ++Step) {
3109 if (CurInit.isInvalid())
3110 return S.ExprError();
3111
3112 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003113 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003114
3115 switch (Step->Kind) {
3116 case SK_ResolveAddressOfOverloadedFunction:
3117 // Overload resolution determined which function invoke; update the
3118 // initializer to reflect that choice.
3119 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3120 break;
3121
3122 case SK_CastDerivedToBaseRValue:
3123 case SK_CastDerivedToBaseLValue: {
3124 // We have a derived-to-base cast that produces either an rvalue or an
3125 // lvalue. Perform that cast.
3126
3127 // Casts to inaccessible base classes are allowed with C-style casts.
3128 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3129 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3130 CurInitExpr->getLocStart(),
3131 CurInitExpr->getSourceRange(),
3132 IgnoreBaseAccess))
3133 return S.ExprError();
3134
3135 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3136 CastExpr::CK_DerivedToBase,
3137 (Expr*)CurInit.release(),
3138 Step->Kind == SK_CastDerivedToBaseLValue));
3139 break;
3140 }
3141
3142 case SK_BindReference:
3143 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3144 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3145 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003146 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003147 << BitField->getDeclName()
3148 << CurInitExpr->getSourceRange();
3149 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3150 return S.ExprError();
3151 }
3152
3153 // Reference binding does not have any corresponding ASTs.
3154
3155 // Check exception specifications
3156 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3157 return S.ExprError();
3158 break;
3159
3160 case SK_BindReferenceToTemporary:
3161 // Check exception specifications
3162 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3163 return S.ExprError();
3164
3165 // FIXME: At present, we have no AST to describe when we need to make a
3166 // temporary to bind a reference to. We should.
3167 break;
3168
3169 case SK_UserConversion: {
3170 // We have a user-defined conversion that invokes either a constructor
3171 // or a conversion function.
3172 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003173 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003174 if (CXXConstructorDecl *Constructor
3175 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3176 // Build a call to the selected constructor.
3177 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3178 SourceLocation Loc = CurInitExpr->getLocStart();
3179 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3180
3181 // Determine the arguments required to actually perform the constructor
3182 // call.
3183 if (S.CompleteConstructorCall(Constructor,
3184 Sema::MultiExprArg(S,
3185 (void **)&CurInitExpr,
3186 1),
3187 Loc, ConstructorArgs))
3188 return S.ExprError();
3189
3190 // Build the an expression that constructs a temporary.
3191 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3192 move_arg(ConstructorArgs));
3193 if (CurInit.isInvalid())
3194 return S.ExprError();
3195
3196 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003197 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3198 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3199 S.IsDerivedFrom(SourceType, Class))
3200 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003201 } else {
3202 // Build a call to the conversion function.
3203 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003204
Douglas Gregor20093b42009-12-09 23:02:17 +00003205 // FIXME: Should we move this initialization into a separate
3206 // derived-to-base conversion? I believe the answer is "no", because
3207 // we don't want to turn off access control here for c-style casts.
3208 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3209 return S.ExprError();
3210
3211 // Do a little dance to make sure that CurInit has the proper
3212 // pointer.
3213 CurInit.release();
3214
3215 // Build the actual call to the conversion function.
3216 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3217 if (CurInit.isInvalid() || !CurInit.get())
3218 return S.ExprError();
3219
3220 CastKind = CastExpr::CK_UserDefinedConversion;
3221 }
3222
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003223 if (shouldBindAsTemporary(Entity, IsCopy))
3224 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3225
Douglas Gregor20093b42009-12-09 23:02:17 +00003226 CurInitExpr = CurInit.takeAs<Expr>();
3227 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3228 CastKind,
3229 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003230 false));
3231
3232 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003233 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003234 break;
3235 }
3236
3237 case SK_QualificationConversionLValue:
3238 case SK_QualificationConversionRValue:
3239 // Perform a qualification conversion; these can never go wrong.
3240 S.ImpCastExprToType(CurInitExpr, Step->Type,
3241 CastExpr::CK_NoOp,
3242 Step->Kind == SK_QualificationConversionLValue);
3243 CurInit.release();
3244 CurInit = S.Owned(CurInitExpr);
3245 break;
3246
3247 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003248 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003249 false, false, *Step->ICS))
3250 return S.ExprError();
3251
3252 CurInit.release();
3253 CurInit = S.Owned(CurInitExpr);
3254 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003255
3256 case SK_ListInitialization: {
3257 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3258 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003259 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003260 return S.ExprError();
3261
3262 CurInit.release();
3263 CurInit = S.Owned(InitList);
3264 break;
3265 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003266
3267 case SK_ConstructorInitialization: {
3268 CXXConstructorDecl *Constructor
3269 = cast<CXXConstructorDecl>(Step->Function);
3270
3271 // Build a call to the selected constructor.
3272 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3273 SourceLocation Loc = Kind.getLocation();
3274
3275 // Determine the arguments required to actually perform the constructor
3276 // call.
3277 if (S.CompleteConstructorCall(Constructor, move(Args),
3278 Loc, ConstructorArgs))
3279 return S.ExprError();
3280
3281 // Build the an expression that constructs a temporary.
Douglas Gregord6542d82009-12-22 15:35:07 +00003282 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor745880f2009-12-20 22:01:25 +00003283 Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003284 move_arg(ConstructorArgs),
3285 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003286 if (CurInit.isInvalid())
3287 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003288
3289 bool Elidable
3290 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3291 if (shouldBindAsTemporary(Entity, Elidable))
3292 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3293
3294 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003295 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003296 break;
3297 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003298
3299 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003300 step_iterator NextStep = Step;
3301 ++NextStep;
3302 if (NextStep != StepEnd &&
3303 NextStep->Kind == SK_ConstructorInitialization) {
3304 // The need for zero-initialization is recorded directly into
3305 // the call to the object's constructor within the next step.
3306 ConstructorInitRequiresZeroInit = true;
3307 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3308 S.getLangOptions().CPlusPlus &&
3309 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003310 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3311 Kind.getRange().getBegin(),
3312 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003313 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003314 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003315 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003316 break;
3317 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003318
3319 case SK_CAssignment: {
3320 QualType SourceType = CurInitExpr->getType();
3321 Sema::AssignConvertType ConvTy =
3322 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003323
3324 // If this is a call, allow conversion to a transparent union.
3325 if (ConvTy != Sema::Compatible &&
3326 Entity.getKind() == InitializedEntity::EK_Parameter &&
3327 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3328 == Sema::Compatible)
3329 ConvTy = Sema::Compatible;
3330
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003331 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3332 Step->Type, SourceType,
3333 CurInitExpr, getAssignmentAction(Entity)))
3334 return S.ExprError();
3335
3336 CurInit.release();
3337 CurInit = S.Owned(CurInitExpr);
3338 break;
3339 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003340
3341 case SK_StringInit: {
3342 QualType Ty = Step->Type;
3343 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3344 break;
3345 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003346 }
3347 }
3348
3349 return move(CurInit);
3350}
3351
3352//===----------------------------------------------------------------------===//
3353// Diagnose initialization failures
3354//===----------------------------------------------------------------------===//
3355bool InitializationSequence::Diagnose(Sema &S,
3356 const InitializedEntity &Entity,
3357 const InitializationKind &Kind,
3358 Expr **Args, unsigned NumArgs) {
3359 if (SequenceKind != FailedSequence)
3360 return false;
3361
Douglas Gregord6542d82009-12-22 15:35:07 +00003362 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003363 switch (Failure) {
3364 case FK_TooManyInitsForReference:
3365 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3366 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3367 break;
3368
3369 case FK_ArrayNeedsInitList:
3370 case FK_ArrayNeedsInitListOrStringLiteral:
3371 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3372 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3373 break;
3374
3375 case FK_AddressOfOverloadFailed:
3376 S.ResolveAddressOfOverloadedFunction(Args[0],
3377 DestType.getNonReferenceType(),
3378 true);
3379 break;
3380
3381 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003382 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 switch (FailedOverloadResult) {
3384 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003385 if (Failure == FK_UserConversionOverloadFailed)
3386 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3387 << Args[0]->getType() << DestType
3388 << Args[0]->getSourceRange();
3389 else
3390 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3391 << DestType << Args[0]->getType()
3392 << Args[0]->getSourceRange();
3393
Douglas Gregor20093b42009-12-09 23:02:17 +00003394 S.PrintOverloadCandidates(FailedCandidateSet, true);
3395 break;
3396
3397 case OR_No_Viable_Function:
3398 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3399 << Args[0]->getType() << DestType.getNonReferenceType()
3400 << Args[0]->getSourceRange();
3401 S.PrintOverloadCandidates(FailedCandidateSet, false);
3402 break;
3403
3404 case OR_Deleted: {
3405 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3406 << Args[0]->getType() << DestType.getNonReferenceType()
3407 << Args[0]->getSourceRange();
3408 OverloadCandidateSet::iterator Best;
3409 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3410 Kind.getLocation(),
3411 Best);
3412 if (Ovl == OR_Deleted) {
3413 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3414 << Best->Function->isDeleted();
3415 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003416 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003417 }
3418 break;
3419 }
3420
3421 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003422 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003423 break;
3424 }
3425 break;
3426
3427 case FK_NonConstLValueReferenceBindingToTemporary:
3428 case FK_NonConstLValueReferenceBindingToUnrelated:
3429 S.Diag(Kind.getLocation(),
3430 Failure == FK_NonConstLValueReferenceBindingToTemporary
3431 ? diag::err_lvalue_reference_bind_to_temporary
3432 : diag::err_lvalue_reference_bind_to_unrelated)
3433 << DestType.getNonReferenceType()
3434 << Args[0]->getType()
3435 << Args[0]->getSourceRange();
3436 break;
3437
3438 case FK_RValueReferenceBindingToLValue:
3439 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3440 << Args[0]->getSourceRange();
3441 break;
3442
3443 case FK_ReferenceInitDropsQualifiers:
3444 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3445 << DestType.getNonReferenceType()
3446 << Args[0]->getType()
3447 << Args[0]->getSourceRange();
3448 break;
3449
3450 case FK_ReferenceInitFailed:
3451 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3452 << DestType.getNonReferenceType()
3453 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3454 << Args[0]->getType()
3455 << Args[0]->getSourceRange();
3456 break;
3457
3458 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003459 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3460 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003461 << DestType
3462 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3463 << Args[0]->getType()
3464 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003465 break;
3466
3467 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003468 SourceRange R;
3469
3470 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3471 R = SourceRange(InitList->getInit(1)->getLocStart(),
3472 InitList->getLocEnd());
3473 else
3474 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003475
3476 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003477 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003478 break;
3479 }
3480
3481 case FK_ReferenceBindingToInitList:
3482 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3483 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3484 break;
3485
3486 case FK_InitListBadDestinationType:
3487 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3488 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3489 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003490
3491 case FK_ConstructorOverloadFailed: {
3492 SourceRange ArgsRange;
3493 if (NumArgs)
3494 ArgsRange = SourceRange(Args[0]->getLocStart(),
3495 Args[NumArgs - 1]->getLocEnd());
3496
3497 // FIXME: Using "DestType" for the entity we're printing is probably
3498 // bad.
3499 switch (FailedOverloadResult) {
3500 case OR_Ambiguous:
3501 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3502 << DestType << ArgsRange;
3503 S.PrintOverloadCandidates(FailedCandidateSet, true);
3504 break;
3505
3506 case OR_No_Viable_Function:
3507 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3508 << DestType << ArgsRange;
3509 S.PrintOverloadCandidates(FailedCandidateSet, false);
3510 break;
3511
3512 case OR_Deleted: {
3513 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3514 << true << DestType << ArgsRange;
3515 OverloadCandidateSet::iterator Best;
3516 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3517 Kind.getLocation(),
3518 Best);
3519 if (Ovl == OR_Deleted) {
3520 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3521 << Best->Function->isDeleted();
3522 } else {
3523 llvm_unreachable("Inconsistent overload resolution?");
3524 }
3525 break;
3526 }
3527
3528 case OR_Success:
3529 llvm_unreachable("Conversion did not fail!");
3530 break;
3531 }
3532 break;
3533 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003534
3535 case FK_DefaultInitOfConst:
3536 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3537 << DestType;
3538 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003539 }
3540
3541 return true;
3542}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003543
3544//===----------------------------------------------------------------------===//
3545// Initialization helper functions
3546//===----------------------------------------------------------------------===//
3547Sema::OwningExprResult
3548Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3549 SourceLocation EqualLoc,
3550 OwningExprResult Init) {
3551 if (Init.isInvalid())
3552 return ExprError();
3553
3554 Expr *InitE = (Expr *)Init.get();
3555 assert(InitE && "No initialization expression?");
3556
3557 if (EqualLoc.isInvalid())
3558 EqualLoc = InitE->getLocStart();
3559
3560 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3561 EqualLoc);
3562 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3563 Init.release();
3564 return Seq.Perform(*this, Entity, Kind,
3565 MultiExprArg(*this, (void**)&InitE, 1));
3566}