blob: 3ff2588356589460dc217df19568cd1b1e21d4d0 [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 Gregor20093b42009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000025#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000026using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000027
Chris Lattnerdd8e0062009-02-24 22:27:37 +000028//===----------------------------------------------------------------------===//
29// Sema Initialization Checking
30//===----------------------------------------------------------------------===//
31
Chris Lattner79e079d2009-02-24 23:10:27 +000032static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000033 const ArrayType *AT = Context.getAsArrayType(DeclType);
34 if (!AT) return 0;
35
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000051 // char array can be initialized with a narrow string.
52 // Only allow char x[] = "foo"; not char x[] = L"foo";
53 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000054 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000055
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
57 // correction from DR343): "An array with element type compatible with a
58 // qualified or unqualified version of wchar_t may be initialized by a wide
59 // string literal, optionally enclosed in braces."
60 if (Context.typesAreCompatible(Context.getWCharType(),
61 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000062 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnerdd8e0062009-02-24 22:27:37 +000064 return 0;
65}
66
Mike Stump1eb44332009-09-09 15:08:12 +000067static bool CheckSingleInitializer(Expr *&Init, QualType DeclType,
Chris Lattner95e8d652009-02-24 22:46:58 +000068 bool DirectInit, Sema &S) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000069 // Get the type before calling CheckSingleAssignmentConstraints(), since
70 // it can promote the expression.
Mike Stump1eb44332009-09-09 15:08:12 +000071 QualType InitType = Init->getType();
72
Chris Lattner95e8d652009-02-24 22:46:58 +000073 if (S.getLangOptions().CPlusPlus) {
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074 // FIXME: I dislike this error message. A lot.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000075 if (S.PerformImplicitConversion(Init, DeclType,
Douglas Gregor68647482009-12-16 03:45:30 +000076 Sema::AA_Initializing, DirectInit)) {
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000077 ImplicitConversionSequence ICS;
78 OverloadCandidateSet CandidateSet;
79 if (S.IsUserDefinedConversion(Init, DeclType, ICS.UserDefined,
80 CandidateSet,
Douglas Gregor20093b42009-12-09 23:02:17 +000081 true, false, false) != OR_Ambiguous)
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000082 return S.Diag(Init->getSourceRange().getBegin(),
83 diag::err_typecheck_convert_incompatible)
Douglas Gregor68647482009-12-16 03:45:30 +000084 << DeclType << Init->getType() << Sema::AA_Initializing
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +000085 << Init->getSourceRange();
86 S.Diag(Init->getSourceRange().getBegin(),
87 diag::err_typecheck_convert_ambiguous)
88 << DeclType << Init->getType() << Init->getSourceRange();
89 S.PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
90 return true;
91 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 return false;
93 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Chris Lattner95e8d652009-02-24 22:46:58 +000095 Sema::AssignConvertType ConvTy =
96 S.CheckSingleAssignmentConstraints(DeclType, Init);
97 return S.DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
Douglas Gregor68647482009-12-16 03:45:30 +000098 InitType, Init, Sema::AA_Initializing);
Chris Lattnerdd8e0062009-02-24 22:27:37 +000099}
100
Chris Lattner79e079d2009-02-24 23:10:27 +0000101static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
102 // Get the length of the string as parsed.
103 uint64_t StrLength =
104 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
105
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Chris Lattner79e079d2009-02-24 23:10:27 +0000107 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000108 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000109 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000110 // being initialized to a string literal.
111 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000112 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000113 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000114 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
115 ConstVal,
116 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000117 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Eli Friedman8718a6a2009-05-29 18:22:49 +0000120 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Eli Friedman8718a6a2009-05-29 18:22:49 +0000122 // C99 6.7.8p14. We have an array of character type with known size. However,
123 // the size may be smaller or larger than the string we are initializing.
124 // FIXME: Avoid truncation for 64-bit length strings.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
137bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
Douglas Gregor99a2e602009-12-16 01:38:02 +0000138 const InitializedEntity &Entity,
139 const InitializationKind &Kind) {
140 SourceLocation InitLoc = Kind.getLocation();
141 DeclarationName InitEntity = Entity.getName();
142 bool DirectInit = (Kind.getKind() == InitializationKind::IK_Direct);
143
Mike Stump1eb44332009-09-09 15:08:12 +0000144 if (DeclType->isDependentType() ||
Douglas Gregorcb78d882009-11-19 18:03:26 +0000145 Init->isTypeDependent() || Init->isValueDependent()) {
146 // We have either a dependent type or a type- or value-dependent
147 // initializer, so we don't perform any additional checking at
148 // this point.
149
150 // If the declaration is a non-dependent, incomplete array type
151 // that has an initializer, then its type will be completed once
Douglas Gregor73460a32009-11-19 23:25:22 +0000152 // the initializer is instantiated.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000153 if (!DeclType->isDependentType()) {
154 if (const IncompleteArrayType *ArrayT
155 = Context.getAsIncompleteArrayType(DeclType)) {
Douglas Gregor73460a32009-11-19 23:25:22 +0000156 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
157 if (!ILE->isTypeDependent()) {
158 // Compute the constant array type from the length of the
159 // initializer list.
160 // FIXME: This will be wrong if there are designated
161 // initializations. Good thing they don't exist in C++!
162 llvm::APInt NumElements(Context.getTypeSize(Context.getSizeType()),
163 ILE->getNumInits());
164 llvm::APInt Zero(Context.getTypeSize(Context.getSizeType()), 0);
165 if (NumElements == Zero) {
166 // Sizing an array implicitly to zero is not allowed by ISO C,
167 // but is supported by GNU.
168 Diag(ILE->getLocStart(), diag::ext_typecheck_zero_array_size);
169 }
170
171 DeclType = Context.getConstantArrayType(ArrayT->getElementType(),
172 NumElements,
173 ArrayT->getSizeModifier(),
174 ArrayT->getIndexTypeCVRQualifiers());
175 return false;
176 }
177 }
178
179 // Make the array type-dependent by making it dependently-sized.
Douglas Gregorcb78d882009-11-19 18:03:26 +0000180 DeclType = Context.getDependentSizedArrayType(ArrayT->getElementType(),
181 /*NumElts=*/0,
182 ArrayT->getSizeModifier(),
183 ArrayT->getIndexTypeCVRQualifiers(),
184 SourceRange());
185 }
186 }
187
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000188 return false;
Douglas Gregorcb78d882009-11-19 18:03:26 +0000189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000191 // C++ [dcl.init.ref]p1:
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000192 // A variable declared to be a T& or T&&, that is "reference to type T"
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000193 // (8.3.2), shall be initialized by an object, or function, of
194 // type T or by an object that can be converted into a T.
Douglas Gregor52bb5d22009-12-16 16:54:16 +0000195 if (DeclType->isReferenceType()) {
196 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
197 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind,
198 MultiExprArg(*this, (void**)&Init, 1),
199 &DeclType);
200 if (CurInit.isInvalid())
201 return true;
202
203 Init = CurInit.takeAs<Expr>();
204 return false;
205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000207 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
208 // of unknown size ("[]") or an object type that is not a variable array type.
209 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
210 return Diag(InitLoc, diag::err_variable_object_no_init)
211 << VAT->getSizeExpr()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000213 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
214 if (!InitList) {
215 // FIXME: Handle wide strings
Chris Lattner79e079d2009-02-24 23:10:27 +0000216 if (Expr *Str = IsStringInit(Init, DeclType, Context)) {
217 CheckStringInit(Str, DeclType, *this);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000218 return false;
219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000221 // C++ [dcl.init]p14:
222 // -- If the destination type is a (possibly cv-qualified) class
223 // type:
224 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
Douglas Gregor7abfbdb2009-12-19 03:01:41 +0000225 InitializationSequence InitSeq(*this, Entity, Kind, &Init, 1);
226 OwningExprResult CurInit = InitSeq.Perform(*this, Entity, Kind,
227 MultiExprArg(*this, (void**)&Init, 1),
228 &DeclType);
229 if (CurInit.isInvalid())
230 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Douglas Gregor7abfbdb2009-12-19 03:01:41 +0000232 Init = CurInit.takeAs<Expr>();
233 return false;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000234 }
Mike Stump1eb44332009-09-09 15:08:12 +0000235
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000236 // C99 6.7.8p16.
237 if (DeclType->isArrayType())
238 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
Chris Lattnerb78d8332009-06-26 04:45:06 +0000239 << Init->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattner95e8d652009-02-24 22:46:58 +0000241 return CheckSingleInitializer(Init, DeclType, DirectInit, *this);
Mike Stump1eb44332009-09-09 15:08:12 +0000242 }
243
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000244 bool hadError = CheckInitList(Entity, InitList, DeclType);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000245 Init = InitList;
246 return hadError;
247}
248
249//===----------------------------------------------------------------------===//
250// Semantic checking for initializer lists.
251//===----------------------------------------------------------------------===//
252
Douglas Gregor9e80f722009-01-29 01:05:33 +0000253/// @brief Semantic checking for initializer lists.
254///
255/// The InitListChecker class contains a set of routines that each
256/// handle the initialization of a certain kind of entity, e.g.,
257/// arrays, vectors, struct/union types, scalars, etc. The
258/// InitListChecker itself performs a recursive walk of the subobject
259/// structure of the type to be initialized, while stepping through
260/// the initializer list one element at a time. The IList and Index
261/// parameters to each of the Check* routines contain the active
262/// (syntactic) initializer list and the index into that initializer
263/// list that represents the current initializer. Each routine is
264/// responsible for moving that Index forward as it consumes elements.
265///
266/// Each Check* routine also has a StructuredList/StructuredIndex
267/// arguments, which contains the current the "structured" (semantic)
268/// initializer list and the index into that initializer list where we
269/// are copying initializers as we map them over to the semantic
270/// list. Once we have completed our recursive walk of the subobject
271/// structure, we will have constructed a full semantic initializer
272/// list.
273///
274/// C99 designators cause changes in the initializer list traversal,
275/// because they make the initialization "jump" into a specific
276/// subobject and then continue the initialization from that
277/// point. CheckDesignatedInitializer() recursively steps into the
278/// designated subobject and manages backing out the recursion to
279/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000280namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000281class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000282 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000283 bool hadError;
284 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
285 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000286
287 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000288 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000289 unsigned &StructuredIndex,
290 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000291 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000292 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000293 unsigned &StructuredIndex,
294 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000295 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
296 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000297 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000298 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000299 unsigned &StructuredIndex,
300 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000301 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000302 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000303 InitListExpr *StructuredList,
304 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000305 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000306 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000307 InitListExpr *StructuredList,
308 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000309 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000310 unsigned &Index,
311 InitListExpr *StructuredList,
312 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000313 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000314 InitListExpr *StructuredList,
315 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000316 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
317 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000318 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000319 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000320 unsigned &StructuredIndex,
321 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000322 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
323 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000324 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000325 InitListExpr *StructuredList,
326 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000327 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000328 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000329 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000330 RecordDecl::field_iterator *NextField,
331 llvm::APSInt *NextElementIndex,
332 unsigned &Index,
333 InitListExpr *StructuredList,
334 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000335 bool FinishSubobjectInit,
336 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000337 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
338 QualType CurrentObjectType,
339 InitListExpr *StructuredList,
340 unsigned StructuredIndex,
341 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000342 void UpdateStructuredListElement(InitListExpr *StructuredList,
343 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000344 Expr *expr);
345 int numArrayElements(QualType DeclType);
346 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000347
Douglas Gregord6d37de2009-12-22 00:05:34 +0000348 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
349 const InitializedEntity &ParentEntity,
350 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000351 void FillInValueInitializations(const InitializedEntity &Entity,
352 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000353public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000354 InitListChecker(Sema &S, const InitializedEntity &Entity,
355 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000356 bool HadError() { return hadError; }
357
358 // @brief Retrieves the fully-structured initializer list used for
359 // semantic analysis and code generation.
360 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
361};
Chris Lattner8b419b92009-02-24 22:48:58 +0000362} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000363
Douglas Gregord6d37de2009-12-22 00:05:34 +0000364void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
365 const InitializedEntity &ParentEntity,
366 InitListExpr *ILE,
367 bool &RequiresSecondPass) {
368 SourceLocation Loc = ILE->getSourceRange().getBegin();
369 unsigned NumInits = ILE->getNumInits();
370 InitializedEntity MemberEntity
371 = InitializedEntity::InitializeMember(Field, &ParentEntity);
372 if (Init >= NumInits || !ILE->getInit(Init)) {
373 // FIXME: We probably don't need to handle references
374 // specially here, since value-initialization of references is
375 // handled in InitializationSequence.
376 if (Field->getType()->isReferenceType()) {
377 // C++ [dcl.init.aggr]p9:
378 // If an incomplete or empty initializer-list leaves a
379 // member of reference type uninitialized, the program is
380 // ill-formed.
381 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
382 << Field->getType()
383 << ILE->getSyntacticForm()->getSourceRange();
384 SemaRef.Diag(Field->getLocation(),
385 diag::note_uninit_reference_member);
386 hadError = true;
387 return;
388 }
389
390 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
391 true);
392 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
393 if (!InitSeq) {
394 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
395 hadError = true;
396 return;
397 }
398
399 Sema::OwningExprResult MemberInit
400 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
401 Sema::MultiExprArg(SemaRef, 0, 0));
402 if (MemberInit.isInvalid()) {
403 hadError = true;
404 return;
405 }
406
407 if (hadError) {
408 // Do nothing
409 } else if (Init < NumInits) {
410 ILE->setInit(Init, MemberInit.takeAs<Expr>());
411 } else if (InitSeq.getKind()
412 == InitializationSequence::ConstructorInitialization) {
413 // Value-initialization requires a constructor call, so
414 // extend the initializer list to include the constructor
415 // call and make a note that we'll need to take another pass
416 // through the initializer list.
417 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
418 RequiresSecondPass = true;
419 }
420 } else if (InitListExpr *InnerILE
421 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
422 FillInValueInitializations(MemberEntity, InnerILE,
423 RequiresSecondPass);
424}
425
Douglas Gregor4c678342009-01-28 21:54:33 +0000426/// Recursively replaces NULL values within the given initializer list
427/// with expressions that perform value-initialization of the
428/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000429void
430InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
431 InitListExpr *ILE,
432 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000433 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000434 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000435 SourceLocation Loc = ILE->getSourceRange().getBegin();
436 if (ILE->getSyntacticForm())
437 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Ted Kremenek6217b802009-07-29 21:53:49 +0000439 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000440 if (RType->getDecl()->isUnion() &&
441 ILE->getInitializedFieldInUnion())
442 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
443 Entity, ILE, RequiresSecondPass);
444 else {
445 unsigned Init = 0;
446 for (RecordDecl::field_iterator
447 Field = RType->getDecl()->field_begin(),
448 FieldEnd = RType->getDecl()->field_end();
449 Field != FieldEnd; ++Field) {
450 if (Field->isUnnamedBitfield())
451 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000452
Douglas Gregord6d37de2009-12-22 00:05:34 +0000453 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000454 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000455
456 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
457 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000458 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000459
Douglas Gregord6d37de2009-12-22 00:05:34 +0000460 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000461
Douglas Gregord6d37de2009-12-22 00:05:34 +0000462 // Only look at the first initialization of a union.
463 if (RType->getDecl()->isUnion())
464 break;
465 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000466 }
467
468 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000469 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000470
471 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000473 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000474 unsigned NumInits = ILE->getNumInits();
475 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000476 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000477 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000478 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
479 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000480 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
481 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000482 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000483 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000484 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000485 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
486 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000487 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000488 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000490
Douglas Gregor87fd7032009-02-02 17:43:21 +0000491 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000492 if (hadError)
493 return;
494
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000495 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayOrVectorElement)
496 ElementEntity.setElementIndex(Init);
497
Douglas Gregor87fd7032009-02-02 17:43:21 +0000498 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000499 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
500 true);
501 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
502 if (!InitSeq) {
503 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000504 hadError = true;
505 return;
506 }
507
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000508 Sema::OwningExprResult ElementInit
509 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
510 Sema::MultiExprArg(SemaRef, 0, 0));
511 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000512 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000513 return;
514 }
515
516 if (hadError) {
517 // Do nothing
518 } else if (Init < NumInits) {
519 ILE->setInit(Init, ElementInit.takeAs<Expr>());
520 } else if (InitSeq.getKind()
521 == InitializationSequence::ConstructorInitialization) {
522 // Value-initialization requires a constructor call, so
523 // extend the initializer list to include the constructor
524 // call and make a note that we'll need to take another pass
525 // through the initializer list.
526 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
527 RequiresSecondPass = true;
528 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000529 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000530 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
531 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000532 }
533}
534
Chris Lattner68355a52009-01-29 05:10:57 +0000535
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000536InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
537 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000538 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000539 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000540
Eli Friedmanb85f7072008-05-19 19:16:24 +0000541 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000542 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000543 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000544 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000545 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
546 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000547
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000548 if (!hadError) {
549 bool RequiresSecondPass = false;
550 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000551 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000552 FillInValueInitializations(Entity, FullyStructuredList,
553 RequiresSecondPass);
554 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000555}
556
557int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000558 // FIXME: use a proper constant
559 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000560 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000561 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000562 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
563 }
564 return maxElements;
565}
566
567int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000568 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000570 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000571 Field = structDecl->field_begin(),
572 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000573 Field != FieldEnd; ++Field) {
574 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
575 ++InitializableMembers;
576 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000577 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000578 return std::min(InitializableMembers, 1);
579 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000580}
581
Mike Stump1eb44332009-09-09 15:08:12 +0000582void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000583 QualType T, unsigned &Index,
584 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000585 unsigned &StructuredIndex,
586 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000587 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Steve Naroff0cca7492008-05-01 22:18:59 +0000589 if (T->isArrayType())
590 maxElements = numArrayElements(T);
591 else if (T->isStructureType() || T->isUnionType())
592 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000593 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000594 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000595 else
596 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000597
Eli Friedman402256f2008-05-25 13:49:22 +0000598 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000599 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000600 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000601 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000602 hadError = true;
603 return;
604 }
605
Douglas Gregor4c678342009-01-28 21:54:33 +0000606 // Build a structured initializer list corresponding to this subobject.
607 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000608 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
609 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000610 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
611 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000612 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000613
Douglas Gregor4c678342009-01-28 21:54:33 +0000614 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000615 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000616 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000617 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000618 StructuredSubobjectInitIndex,
619 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000620 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000621 StructuredSubobjectInitList->setType(T);
622
Douglas Gregored8a93d2009-03-01 17:12:46 +0000623 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000624 // range corresponds with the end of the last initializer it used.
625 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000626 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000627 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
628 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
629 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000630}
631
Steve Naroffa647caa2008-05-06 00:23:44 +0000632void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000633 unsigned &Index,
634 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000635 unsigned &StructuredIndex,
636 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000637 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 SyntacticToSemantic[IList] = StructuredList;
639 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000640 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000641 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000642 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000643 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000644 if (hadError)
645 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000646
Eli Friedman638e1442008-05-25 13:22:35 +0000647 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000648 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000649 if (StructuredIndex == 1 &&
650 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000651 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000652 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000653 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000654 hadError = true;
655 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000656 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000657 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000658 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000659 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000660 // Don't complain for incomplete types, since we'll get an error
661 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000662 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000663 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000664 CurrentObjectType->isArrayType()? 0 :
665 CurrentObjectType->isVectorType()? 1 :
666 CurrentObjectType->isScalarType()? 2 :
667 CurrentObjectType->isUnionType()? 3 :
668 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000669
670 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000671 if (SemaRef.getLangOptions().CPlusPlus) {
672 DK = diag::err_excess_initializers;
673 hadError = true;
674 }
Nate Begeman08634522009-07-07 21:53:06 +0000675 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
676 DK = diag::err_excess_initializers;
677 hadError = true;
678 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000679
Chris Lattner08202542009-02-24 22:50:46 +0000680 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000681 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000682 }
683 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000684
Eli Friedman759f2522009-05-16 11:45:48 +0000685 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000686 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000687 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000688 << CodeModificationHint::CreateRemoval(IList->getLocStart())
689 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000690}
691
Eli Friedmanb85f7072008-05-19 19:16:24 +0000692void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000693 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000694 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000695 unsigned &Index,
696 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000697 unsigned &StructuredIndex,
698 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000699 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000700 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000701 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000702 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000703 } else if (DeclType->isAggregateType()) {
704 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000705 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000706 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000707 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000708 StructuredList, StructuredIndex,
709 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000710 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000711 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000712 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000713 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000714 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
715 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000716 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000717 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000718 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
719 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000720 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000721 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000722 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000723 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000724 } else if (DeclType->isRecordType()) {
725 // C++ [dcl.init]p14:
726 // [...] If the class is an aggregate (8.5.1), and the initializer
727 // is a brace-enclosed list, see 8.5.1.
728 //
729 // Note: 8.5.1 is handled below; here, we diagnose the case where
730 // we have an initializer list and a destination type that is not
731 // an aggregate.
732 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000733 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000734 << DeclType << IList->getSourceRange();
735 hadError = true;
736 } else if (DeclType->isReferenceType()) {
737 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000738 } else {
739 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000740 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000741 assert(0 && "Unsupported initializer type");
742 }
743}
744
Eli Friedmanb85f7072008-05-19 19:16:24 +0000745void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000746 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000747 unsigned &Index,
748 InitListExpr *StructuredList,
749 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000750 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000751 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
752 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000753 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000754 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000755 = getStructuredSubobjectInit(IList, Index, ElemType,
756 StructuredList, StructuredIndex,
757 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000758 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000759 newStructuredList, newStructuredIndex);
760 ++StructuredIndex;
761 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000762 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
763 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000764 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000765 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000766 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000767 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000768 } else if (ElemType->isReferenceType()) {
769 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000770 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000771 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000772 // C++ [dcl.init.aggr]p12:
773 // All implicit type conversions (clause 4) are considered when
774 // initializing the aggregate member with an ini- tializer from
775 // an initializer-list. If the initializer can initialize a
776 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000777 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000778 = SemaRef.TryCopyInitialization(expr, ElemType,
779 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000780 /*ForceRValue=*/false,
781 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000782
Douglas Gregor930d8b52009-01-30 22:09:00 +0000783 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion) {
Mike Stump1eb44332009-09-09 15:08:12 +0000784 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000785 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000786 hadError = true;
787 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
788 ++Index;
789 return;
790 }
791
792 // Fall through for subaggregate initialization
793 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000794 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000795 //
796 // The initializer for a structure or union object that has
797 // automatic storage duration shall be either an initializer
798 // list as described below, or a single expression that has
799 // compatible structure or union type. In the latter case, the
800 // initial value of the object, including unnamed members, is
801 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000802 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000803 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000804 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
805 ++Index;
806 return;
807 }
808
809 // Fall through for subaggregate initialization
810 }
811
812 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000813 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000814 // [...] Otherwise, if the member is itself a non-empty
815 // subaggregate, brace elision is assumed and the initializer is
816 // considered for the initialization of the first member of
817 // the subaggregate.
818 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000819 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000820 StructuredIndex);
821 ++StructuredIndex;
822 } else {
823 // We cannot initialize this element, so let
824 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000825 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000826 hadError = true;
827 ++Index;
828 ++StructuredIndex;
829 }
830 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000831}
832
Douglas Gregor930d8b52009-01-30 22:09:00 +0000833void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000834 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000835 InitListExpr *StructuredList,
836 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000837 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000838 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000839 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000840 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000841 diag::err_many_braces_around_scalar_init)
842 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000843 hadError = true;
844 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000845 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000846 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000847 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000848 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000849 diag::err_designator_for_scalar_init)
850 << DeclType << expr->getSourceRange();
851 hadError = true;
852 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000853 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000854 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000855 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000856
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000857 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Chris Lattner08202542009-02-24 22:50:46 +0000858 if (CheckSingleInitializer(expr, DeclType, false, SemaRef))
Eli Friedmanbb504d32008-05-19 20:12:18 +0000859 hadError = true; // types weren't compatible.
Douglas Gregor05c13a32009-01-22 00:58:24 +0000860 else if (savExpr != expr) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000861 // The type was promoted, update initializer list.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000862 IList->setInit(Index, expr);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000863 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000864 if (hadError)
865 ++StructuredIndex;
866 else
867 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000868 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000869 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000870 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000871 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000872 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000873 ++Index;
874 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000875 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000876 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000877}
878
Douglas Gregor930d8b52009-01-30 22:09:00 +0000879void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
880 unsigned &Index,
881 InitListExpr *StructuredList,
882 unsigned &StructuredIndex) {
883 if (Index < IList->getNumInits()) {
884 Expr *expr = IList->getInit(Index);
885 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000886 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000887 << DeclType << IList->getSourceRange();
888 hadError = true;
889 ++Index;
890 ++StructuredIndex;
891 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000892 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000893
894 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000895 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000896 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000897 /*SuppressUserConversions=*/false,
898 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000899 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000900 hadError = true;
901 else if (savExpr != expr) {
902 // The type was promoted, update initializer list.
903 IList->setInit(Index, expr);
904 }
905 if (hadError)
906 ++StructuredIndex;
907 else
908 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
909 ++Index;
910 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000911 // FIXME: It would be wonderful if we could point at the actual member. In
912 // general, it would be useful to pass location information down the stack,
913 // so that we know the location (or decl) of the "current object" being
914 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000915 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000916 diag::err_init_reference_member_uninitialized)
917 << DeclType
918 << IList->getSourceRange();
919 hadError = true;
920 ++Index;
921 ++StructuredIndex;
922 return;
923 }
924}
925
Mike Stump1eb44332009-09-09 15:08:12 +0000926void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000927 unsigned &Index,
928 InitListExpr *StructuredList,
929 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000930 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000931 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000932 unsigned maxElements = VT->getNumElements();
933 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000934 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Nate Begeman2ef13e52009-08-10 23:49:36 +0000936 if (!SemaRef.getLangOptions().OpenCL) {
937 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
938 // Don't attempt to go past the end of the init list
939 if (Index >= IList->getNumInits())
940 break;
941 CheckSubElementType(IList, elementType, Index,
942 StructuredList, StructuredIndex);
943 }
944 } else {
945 // OpenCL initializers allows vectors to be constructed from vectors.
946 for (unsigned i = 0; i < maxElements; ++i) {
947 // Don't attempt to go past the end of the init list
948 if (Index >= IList->getNumInits())
949 break;
950 QualType IType = IList->getInit(Index)->getType();
951 if (!IType->isVectorType()) {
952 CheckSubElementType(IList, elementType, Index,
953 StructuredList, StructuredIndex);
954 ++numEltsInit;
955 } else {
John McCall183700f2009-09-21 23:43:11 +0000956 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000957 unsigned numIElts = IVT->getNumElements();
958 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
959 numIElts);
960 CheckSubElementType(IList, VecType, Index,
961 StructuredList, StructuredIndex);
962 numEltsInit += numIElts;
963 }
964 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Nate Begeman2ef13e52009-08-10 23:49:36 +0000967 // OpenCL & AltiVec require all elements to be initialized.
968 if (numEltsInit != maxElements)
969 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
970 SemaRef.Diag(IList->getSourceRange().getBegin(),
971 diag::err_vector_incorrect_num_initializers)
972 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000973 }
974}
975
Mike Stump1eb44332009-09-09 15:08:12 +0000976void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000977 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000978 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000979 unsigned &Index,
980 InitListExpr *StructuredList,
981 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000982 // Check for the special-case of initializing an array with a string.
983 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000984 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
985 SemaRef.Context)) {
986 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000987 // We place the string literal directly into the resulting
988 // initializer list. This is the only place where the structure
989 // of the structured initializer list doesn't match exactly,
990 // because doing so would involve allocating one character
991 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000992 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000993 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000994 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000995 return;
996 }
997 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000998 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000999 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001000 // Check for VLAs; in standard C it would be possible to check this
1001 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1002 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001003 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001004 diag::err_variable_object_no_init)
1005 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001006 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001007 ++Index;
1008 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001009 return;
1010 }
1011
Douglas Gregor05c13a32009-01-22 00:58:24 +00001012 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001013 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1014 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001015 bool maxElementsKnown = false;
1016 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +00001017 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001018 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001019 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001020 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001021 maxElementsKnown = true;
1022 }
1023
Chris Lattner08202542009-02-24 22:50:46 +00001024 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001025 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001026 while (Index < IList->getNumInits()) {
1027 Expr *Init = IList->getInit(Index);
1028 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001029 // If we're not the subobject that matches up with the '{' for
1030 // the designator, we shouldn't be handling the
1031 // designator. Return immediately.
1032 if (!SubobjectIsDesignatorContext)
1033 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001034
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001035 // Handle this designated initializer. elementIndex will be
1036 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +00001037 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001038 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001039 StructuredList, StructuredIndex, true,
1040 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001041 hadError = true;
1042 continue;
1043 }
1044
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001045 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1046 maxElements.extend(elementIndex.getBitWidth());
1047 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1048 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001049 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001050
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001051 // If the array is of incomplete type, keep track of the number of
1052 // elements in the initializer.
1053 if (!maxElementsKnown && elementIndex > maxElements)
1054 maxElements = elementIndex;
1055
Douglas Gregor05c13a32009-01-22 00:58:24 +00001056 continue;
1057 }
1058
1059 // If we know the maximum number of elements, and we've already
1060 // hit it, stop consuming elements in the initializer list.
1061 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001062 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001063
1064 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001065 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001066 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001067 ++elementIndex;
1068
1069 // If the array is of incomplete type, keep track of the number of
1070 // elements in the initializer.
1071 if (!maxElementsKnown && elementIndex > maxElements)
1072 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001073 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001074 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001075 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001076 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001077 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001078 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001079 // Sizing an array implicitly to zero is not allowed by ISO C,
1080 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001081 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001082 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001083 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001084
Mike Stump1eb44332009-09-09 15:08:12 +00001085 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001086 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001087 }
1088}
1089
Mike Stump1eb44332009-09-09 15:08:12 +00001090void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1091 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001092 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001093 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001094 unsigned &Index,
1095 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001096 unsigned &StructuredIndex,
1097 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001098 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Eli Friedmanb85f7072008-05-19 19:16:24 +00001100 // If the record is invalid, some of it's members are invalid. To avoid
1101 // confusion, we forgo checking the intializer for the entire record.
1102 if (structDecl->isInvalidDecl()) {
1103 hadError = true;
1104 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001105 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001106
1107 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1108 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001109 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001110 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001111 Field != FieldEnd; ++Field) {
1112 if (Field->getDeclName()) {
1113 StructuredList->setInitializedFieldInUnion(*Field);
1114 break;
1115 }
1116 }
1117 return;
1118 }
1119
Douglas Gregor05c13a32009-01-22 00:58:24 +00001120 // If structDecl is a forward declaration, this loop won't do
1121 // anything except look at designated initializers; That's okay,
1122 // because an error should get printed out elsewhere. It might be
1123 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001124 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001125 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001126 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001127 while (Index < IList->getNumInits()) {
1128 Expr *Init = IList->getInit(Index);
1129
1130 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001131 // If we're not the subobject that matches up with the '{' for
1132 // the designator, we shouldn't be handling the
1133 // designator. Return immediately.
1134 if (!SubobjectIsDesignatorContext)
1135 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001136
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001137 // Handle this designated initializer. Field will be updated to
1138 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001139 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001140 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001141 StructuredList, StructuredIndex,
1142 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001143 hadError = true;
1144
Douglas Gregordfb5e592009-02-12 19:00:39 +00001145 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001146 continue;
1147 }
1148
1149 if (Field == FieldEnd) {
1150 // We've run out of fields. We're done.
1151 break;
1152 }
1153
Douglas Gregordfb5e592009-02-12 19:00:39 +00001154 // We've already initialized a member of a union. We're done.
1155 if (InitializedSomething && DeclType->isUnionType())
1156 break;
1157
Douglas Gregor44b43212008-12-11 16:49:14 +00001158 // If we've hit the flexible array member at the end, we're done.
1159 if (Field->getType()->isIncompleteArrayType())
1160 break;
1161
Douglas Gregor0bb76892009-01-29 16:53:55 +00001162 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001163 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001164 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001165 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001166 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001167
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001168 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001169 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001170 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001171
1172 if (DeclType->isUnionType()) {
1173 // Initialize the first field within the union.
1174 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001175 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001176
1177 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001178 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001179
Mike Stump1eb44332009-09-09 15:08:12 +00001180 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001181 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001182 return;
1183
1184 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001185 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001186 (!isa<InitListExpr>(IList->getInit(Index)) ||
1187 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001188 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001189 diag::err_flexible_array_init_nonempty)
1190 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001191 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001192 << *Field;
1193 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001194 ++Index;
1195 return;
1196 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001197 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001198 diag::ext_flexible_array_init)
1199 << IList->getInit(Index)->getSourceRange().getBegin();
1200 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1201 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001202 }
1203
Douglas Gregora6457962009-03-20 00:32:56 +00001204 if (isa<InitListExpr>(IList->getInit(Index)))
1205 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1206 StructuredIndex);
1207 else
1208 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1209 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001210}
Steve Naroff0cca7492008-05-01 22:18:59 +00001211
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001212/// \brief Expand a field designator that refers to a member of an
1213/// anonymous struct or union into a series of field designators that
1214/// refers to the field within the appropriate subobject.
1215///
1216/// Field/FieldIndex will be updated to point to the (new)
1217/// currently-designated field.
1218static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001219 DesignatedInitExpr *DIE,
1220 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001221 FieldDecl *Field,
1222 RecordDecl::field_iterator &FieldIter,
1223 unsigned &FieldIndex) {
1224 typedef DesignatedInitExpr::Designator Designator;
1225
1226 // Build the path from the current object to the member of the
1227 // anonymous struct/union (backwards).
1228 llvm::SmallVector<FieldDecl *, 4> Path;
1229 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001231 // Build the replacement designators.
1232 llvm::SmallVector<Designator, 4> Replacements;
1233 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1234 FI = Path.rbegin(), FIEnd = Path.rend();
1235 FI != FIEnd; ++FI) {
1236 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001237 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001238 DIE->getDesignator(DesigIdx)->getDotLoc(),
1239 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1240 else
1241 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1242 SourceLocation()));
1243 Replacements.back().setField(*FI);
1244 }
1245
1246 // Expand the current designator into the set of replacement
1247 // designators, so we have a full subobject path down to where the
1248 // member of the anonymous struct/union is actually stored.
Mike Stump1eb44332009-09-09 15:08:12 +00001249 DIE->ExpandDesignator(DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001250 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001252 // Update FieldIter/FieldIndex;
1253 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001254 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001255 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001256 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001257 FieldIter != FEnd; ++FieldIter) {
1258 if (FieldIter->isUnnamedBitfield())
1259 continue;
1260
1261 if (*FieldIter == Path.back())
1262 return;
1263
1264 ++FieldIndex;
1265 }
1266
1267 assert(false && "Unable to find anonymous struct/union field");
1268}
1269
Douglas Gregor05c13a32009-01-22 00:58:24 +00001270/// @brief Check the well-formedness of a C99 designated initializer.
1271///
1272/// Determines whether the designated initializer @p DIE, which
1273/// resides at the given @p Index within the initializer list @p
1274/// IList, is well-formed for a current object of type @p DeclType
1275/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001276/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001277/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001278///
1279/// @param IList The initializer list in which this designated
1280/// initializer occurs.
1281///
Douglas Gregor71199712009-04-15 04:56:10 +00001282/// @param DIE The designated initializer expression.
1283///
1284/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001285///
1286/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1287/// into which the designation in @p DIE should refer.
1288///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001289/// @param NextField If non-NULL and the first designator in @p DIE is
1290/// a field, this will be set to the field declaration corresponding
1291/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001292///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001293/// @param NextElementIndex If non-NULL and the first designator in @p
1294/// DIE is an array designator or GNU array-range designator, this
1295/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001296///
1297/// @param Index Index into @p IList where the designated initializer
1298/// @p DIE occurs.
1299///
Douglas Gregor4c678342009-01-28 21:54:33 +00001300/// @param StructuredList The initializer list expression that
1301/// describes all of the subobject initializers in the order they'll
1302/// actually be initialized.
1303///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001304/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001305bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001306InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001307 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001308 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001309 QualType &CurrentObjectType,
1310 RecordDecl::field_iterator *NextField,
1311 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001312 unsigned &Index,
1313 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001314 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001315 bool FinishSubobjectInit,
1316 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001317 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001318 // Check the actual initialization for the designated object type.
1319 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001320
1321 // Temporarily remove the designator expression from the
1322 // initializer list that the child calls see, so that we don't try
1323 // to re-process the designator.
1324 unsigned OldIndex = Index;
1325 IList->setInit(OldIndex, DIE->getInit());
1326
1327 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001328 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001329
1330 // Restore the designated initializer expression in the syntactic
1331 // form of the initializer list.
1332 if (IList->getInit(OldIndex) != DIE->getInit())
1333 DIE->setInit(IList->getInit(OldIndex));
1334 IList->setInit(OldIndex, DIE);
1335
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001336 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001337 }
1338
Douglas Gregor71199712009-04-15 04:56:10 +00001339 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001340 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001341 "Need a non-designated initializer list to start from");
1342
Douglas Gregor71199712009-04-15 04:56:10 +00001343 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001344 // Determine the structural initializer list that corresponds to the
1345 // current subobject.
1346 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001347 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001348 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001349 SourceRange(D->getStartLocation(),
1350 DIE->getSourceRange().getEnd()));
1351 assert(StructuredList && "Expected a structured initializer list");
1352
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001353 if (D->isFieldDesignator()) {
1354 // C99 6.7.8p7:
1355 //
1356 // If a designator has the form
1357 //
1358 // . identifier
1359 //
1360 // then the current object (defined below) shall have
1361 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001362 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001363 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001364 if (!RT) {
1365 SourceLocation Loc = D->getDotLoc();
1366 if (Loc.isInvalid())
1367 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001368 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1369 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001370 ++Index;
1371 return true;
1372 }
1373
Douglas Gregor4c678342009-01-28 21:54:33 +00001374 // Note: we perform a linear search of the fields here, despite
1375 // the fact that we have a faster lookup method, because we always
1376 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001377 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001378 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001379 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001380 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001381 Field = RT->getDecl()->field_begin(),
1382 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001383 for (; Field != FieldEnd; ++Field) {
1384 if (Field->isUnnamedBitfield())
1385 continue;
1386
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001387 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001388 break;
1389
1390 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001391 }
1392
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001394 // There was no normal field in the struct with the designated
1395 // name. Perform another lookup for this name, which may find
1396 // something that we can't designate (e.g., a member function),
1397 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001398 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001399 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4c678342009-01-28 21:54:33 +00001400 if (Lookup.first == Lookup.second) {
1401 // Name lookup didn't find anything.
Chris Lattner08202542009-02-24 22:50:46 +00001402 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
Douglas Gregor4c678342009-01-28 21:54:33 +00001403 << FieldName << CurrentObjectType;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001404 ++Index;
1405 return true;
1406 } else if (!KnownField && isa<FieldDecl>(*Lookup.first) &&
1407 cast<RecordDecl>((*Lookup.first)->getDeclContext())
1408 ->isAnonymousStructOrUnion()) {
1409 // Handle an field designator that refers to a member of an
1410 // anonymous struct or union.
Mike Stump1eb44332009-09-09 15:08:12 +00001411 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001412 cast<FieldDecl>(*Lookup.first),
1413 Field, FieldIndex);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001414 D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001415 } else {
1416 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001417 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001418 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001419 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001420 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001421 ++Index;
1422 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001423 }
1424 } else if (!KnownField &&
1425 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001426 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001427 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1428 Field, FieldIndex);
1429 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001430 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001431
1432 // All of the fields of a union are located at the same place in
1433 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001434 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001435 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001436 StructuredList->setInitializedFieldInUnion(*Field);
1437 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001438
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001439 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001440 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Douglas Gregor4c678342009-01-28 21:54:33 +00001442 // Make sure that our non-designated initializer list has space
1443 // for a subobject corresponding to this field.
1444 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001445 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001446
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001447 // This designator names a flexible array member.
1448 if (Field->getType()->isIncompleteArrayType()) {
1449 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001450 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001451 // We can't designate an object within the flexible array
1452 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001453 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001454 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001455 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001456 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001457 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001458 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001459 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001460 << *Field;
1461 Invalid = true;
1462 }
1463
1464 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1465 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001466 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001467 diag::err_flexible_array_init_needs_braces)
1468 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001469 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001470 << *Field;
1471 Invalid = true;
1472 }
1473
1474 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001475 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001476 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001477 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001478 diag::err_flexible_array_init_nonempty)
1479 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001480 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001481 << *Field;
1482 Invalid = true;
1483 }
1484
1485 if (Invalid) {
1486 ++Index;
1487 return true;
1488 }
1489
1490 // Initialize the array.
1491 bool prevHadError = hadError;
1492 unsigned newStructuredIndex = FieldIndex;
1493 unsigned OldIndex = Index;
1494 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001495 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001496 StructuredList, newStructuredIndex);
1497 IList->setInit(OldIndex, DIE);
1498 if (hadError && !prevHadError) {
1499 ++Field;
1500 ++FieldIndex;
1501 if (NextField)
1502 *NextField = Field;
1503 StructuredIndex = FieldIndex;
1504 return true;
1505 }
1506 } else {
1507 // Recurse to check later designated subobjects.
1508 QualType FieldType = (*Field)->getType();
1509 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001510 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1511 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001512 true, false))
1513 return true;
1514 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001515
1516 // Find the position of the next field to be initialized in this
1517 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001518 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001519 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001520
1521 // If this the first designator, our caller will continue checking
1522 // the rest of this struct/class/union subobject.
1523 if (IsFirstDesignator) {
1524 if (NextField)
1525 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001526 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527 return false;
1528 }
1529
Douglas Gregor34e79462009-01-28 23:36:17 +00001530 if (!FinishSubobjectInit)
1531 return false;
1532
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001533 // We've already initialized something in the union; we're done.
1534 if (RT->getDecl()->isUnion())
1535 return hadError;
1536
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001537 // Check the remaining fields within this class/struct/union subobject.
1538 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001539 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1540 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001541 return hadError && !prevHadError;
1542 }
1543
1544 // C99 6.7.8p6:
1545 //
1546 // If a designator has the form
1547 //
1548 // [ constant-expression ]
1549 //
1550 // then the current object (defined below) shall have array
1551 // type and the expression shall be an integer constant
1552 // expression. If the array is of unknown size, any
1553 // nonnegative value is valid.
1554 //
1555 // Additionally, cope with the GNU extension that permits
1556 // designators of the form
1557 //
1558 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001559 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001560 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001561 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001562 << CurrentObjectType;
1563 ++Index;
1564 return true;
1565 }
1566
1567 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001568 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1569 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001570 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001571 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001572 DesignatedEndIndex = DesignatedStartIndex;
1573 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001574 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001575
Mike Stump1eb44332009-09-09 15:08:12 +00001576
1577 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001578 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001579 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001580 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001581 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001582
Chris Lattner3bf68932009-04-25 21:59:05 +00001583 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001584 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001585 }
1586
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001587 if (isa<ConstantArrayType>(AT)) {
1588 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001589 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1590 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1591 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1592 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1593 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001594 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001595 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001596 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001597 << IndexExpr->getSourceRange();
1598 ++Index;
1599 return true;
1600 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001601 } else {
1602 // Make sure the bit-widths and signedness match.
1603 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1604 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001605 else if (DesignatedStartIndex.getBitWidth() <
1606 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001607 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1608 DesignatedStartIndex.setIsUnsigned(true);
1609 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Douglas Gregor4c678342009-01-28 21:54:33 +00001612 // Make sure that our non-designated initializer list has space
1613 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001614 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001615 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001616 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001617
Douglas Gregor34e79462009-01-28 23:36:17 +00001618 // Repeatedly perform subobject initializations in the range
1619 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001620
Douglas Gregor34e79462009-01-28 23:36:17 +00001621 // Move to the next designator
1622 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1623 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001624 while (DesignatedStartIndex <= DesignatedEndIndex) {
1625 // Recurse to check later designated subobjects.
1626 QualType ElementType = AT->getElementType();
1627 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001628 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1629 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001630 (DesignatedStartIndex == DesignatedEndIndex),
1631 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001632 return true;
1633
1634 // Move to the next index in the array that we'll be initializing.
1635 ++DesignatedStartIndex;
1636 ElementIndex = DesignatedStartIndex.getZExtValue();
1637 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001638
1639 // If this the first designator, our caller will continue checking
1640 // the rest of this array subobject.
1641 if (IsFirstDesignator) {
1642 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001643 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001644 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001645 return false;
1646 }
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Douglas Gregor34e79462009-01-28 23:36:17 +00001648 if (!FinishSubobjectInit)
1649 return false;
1650
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001651 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001652 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001653 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001654 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001655 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001656}
1657
Douglas Gregor4c678342009-01-28 21:54:33 +00001658// Get the structured initializer list for a subobject of type
1659// @p CurrentObjectType.
1660InitListExpr *
1661InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1662 QualType CurrentObjectType,
1663 InitListExpr *StructuredList,
1664 unsigned StructuredIndex,
1665 SourceRange InitRange) {
1666 Expr *ExistingInit = 0;
1667 if (!StructuredList)
1668 ExistingInit = SyntacticToSemantic[IList];
1669 else if (StructuredIndex < StructuredList->getNumInits())
1670 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Douglas Gregor4c678342009-01-28 21:54:33 +00001672 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1673 return Result;
1674
1675 if (ExistingInit) {
1676 // We are creating an initializer list that initializes the
1677 // subobjects of the current object, but there was already an
1678 // initialization that completely initialized the current
1679 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001680 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001681 // struct X { int a, b; };
1682 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001683 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001684 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1685 // designated initializer re-initializes the whole
1686 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001687 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001688 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001689 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001690 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001691 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001692 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001693 << ExistingInit->getSourceRange();
1694 }
1695
Mike Stump1eb44332009-09-09 15:08:12 +00001696 InitListExpr *Result
1697 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001698 InitRange.getEnd());
1699
Douglas Gregor4c678342009-01-28 21:54:33 +00001700 Result->setType(CurrentObjectType);
1701
Douglas Gregorfa219202009-03-20 23:58:33 +00001702 // Pre-allocate storage for the structured initializer list.
1703 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001704 unsigned NumInits = 0;
1705 if (!StructuredList)
1706 NumInits = IList->getNumInits();
1707 else if (Index < IList->getNumInits()) {
1708 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1709 NumInits = SubList->getNumInits();
1710 }
1711
Mike Stump1eb44332009-09-09 15:08:12 +00001712 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001713 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1714 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1715 NumElements = CAType->getSize().getZExtValue();
1716 // Simple heuristic so that we don't allocate a very large
1717 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001718 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001719 NumElements = 0;
1720 }
John McCall183700f2009-09-21 23:43:11 +00001721 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001722 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001723 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001724 RecordDecl *RDecl = RType->getDecl();
1725 if (RDecl->isUnion())
1726 NumElements = 1;
1727 else
Mike Stump1eb44332009-09-09 15:08:12 +00001728 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001729 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001730 }
1731
Douglas Gregor08457732009-03-21 18:13:52 +00001732 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001733 NumElements = IList->getNumInits();
1734
1735 Result->reserveInits(NumElements);
1736
Douglas Gregor4c678342009-01-28 21:54:33 +00001737 // Link this new initializer list into the structured initializer
1738 // lists.
1739 if (StructuredList)
1740 StructuredList->updateInit(StructuredIndex, Result);
1741 else {
1742 Result->setSyntacticForm(IList);
1743 SyntacticToSemantic[IList] = Result;
1744 }
1745
1746 return Result;
1747}
1748
1749/// Update the initializer at index @p StructuredIndex within the
1750/// structured initializer list to the value @p expr.
1751void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1752 unsigned &StructuredIndex,
1753 Expr *expr) {
1754 // No structured initializer list to update
1755 if (!StructuredList)
1756 return;
1757
1758 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1759 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001760 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001761 diag::warn_initializer_overrides)
1762 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001763 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001764 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001765 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001766 << PrevInit->getSourceRange();
1767 }
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Douglas Gregor4c678342009-01-28 21:54:33 +00001769 ++StructuredIndex;
1770}
1771
Douglas Gregor05c13a32009-01-22 00:58:24 +00001772/// Check that the given Index expression is a valid array designator
1773/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001774/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001775/// and produces a reasonable diagnostic if there is a
1776/// failure. Returns true if there was an error, false otherwise. If
1777/// everything went okay, Value will receive the value of the constant
1778/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001779static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001780CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001781 SourceLocation Loc = Index->getSourceRange().getBegin();
1782
1783 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001784 if (S.VerifyIntegerConstantExpression(Index, &Value))
1785 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001786
Chris Lattner3bf68932009-04-25 21:59:05 +00001787 if (Value.isSigned() && Value.isNegative())
1788 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001789 << Value.toString(10) << Index->getSourceRange();
1790
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001791 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001792 return false;
1793}
1794
1795Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1796 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001797 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001798 OwningExprResult Init) {
1799 typedef DesignatedInitExpr::Designator ASTDesignator;
1800
1801 bool Invalid = false;
1802 llvm::SmallVector<ASTDesignator, 32> Designators;
1803 llvm::SmallVector<Expr *, 32> InitExpressions;
1804
1805 // Build designators and check array designator expressions.
1806 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1807 const Designator &D = Desig.getDesignator(Idx);
1808 switch (D.getKind()) {
1809 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001810 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001811 D.getFieldLoc()));
1812 break;
1813
1814 case Designator::ArrayDesignator: {
1815 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1816 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001817 if (!Index->isTypeDependent() &&
1818 !Index->isValueDependent() &&
1819 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001820 Invalid = true;
1821 else {
1822 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001823 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001824 D.getRBracketLoc()));
1825 InitExpressions.push_back(Index);
1826 }
1827 break;
1828 }
1829
1830 case Designator::ArrayRangeDesignator: {
1831 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1832 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1833 llvm::APSInt StartValue;
1834 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001835 bool StartDependent = StartIndex->isTypeDependent() ||
1836 StartIndex->isValueDependent();
1837 bool EndDependent = EndIndex->isTypeDependent() ||
1838 EndIndex->isValueDependent();
1839 if ((!StartDependent &&
1840 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1841 (!EndDependent &&
1842 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001843 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001844 else {
1845 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001846 if (StartDependent || EndDependent) {
1847 // Nothing to compute.
1848 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001849 EndValue.extend(StartValue.getBitWidth());
1850 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1851 StartValue.extend(EndValue.getBitWidth());
1852
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001853 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001854 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001855 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001856 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1857 Invalid = true;
1858 } else {
1859 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001860 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001861 D.getEllipsisLoc(),
1862 D.getRBracketLoc()));
1863 InitExpressions.push_back(StartIndex);
1864 InitExpressions.push_back(EndIndex);
1865 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001866 }
1867 break;
1868 }
1869 }
1870 }
1871
1872 if (Invalid || Init.isInvalid())
1873 return ExprError();
1874
1875 // Clear out the expressions within the designation.
1876 Desig.ClearExprs(*this);
1877
1878 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001879 = DesignatedInitExpr::Create(Context,
1880 Designators.data(), Designators.size(),
1881 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001882 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001883 return Owned(DIE);
1884}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001885
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001886bool Sema::CheckInitList(const InitializedEntity &Entity,
1887 InitListExpr *&InitList, QualType &DeclType) {
1888 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001889 if (!CheckInitList.HadError())
1890 InitList = CheckInitList.getFullyStructuredList();
1891
1892 return CheckInitList.HadError();
1893}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001894
Douglas Gregor20093b42009-12-09 23:02:17 +00001895//===----------------------------------------------------------------------===//
1896// Initialization entity
1897//===----------------------------------------------------------------------===//
1898
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001899InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1900 const InitializedEntity &Parent)
1901 : Kind(EK_ArrayOrVectorElement), Parent(&Parent), Index(Index)
1902{
1903 if (isa<ArrayType>(Parent.TL.getType())) {
1904 TL = cast<ArrayTypeLoc>(Parent.TL).getElementLoc();
1905 return;
1906 }
1907
1908 // FIXME: should be able to get type location information for vectors, too.
1909
1910 QualType T;
1911 if (const ArrayType *AT = Context.getAsArrayType(Parent.TL.getType()))
1912 T = AT->getElementType();
1913 else
1914 T = Parent.TL.getType()->getAs<VectorType>()->getElementType();
1915
1916 // FIXME: Once we've gone through the effort to create the fake
1917 // TypeSourceInfo, should we cache it somewhere? (If not, we "leak" it).
1918 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(T);
1919 DI->getTypeLoc().initialize(Parent.TL.getSourceRange().getBegin());
1920 TL = DI->getTypeLoc();
1921}
1922
Douglas Gregor20093b42009-12-09 23:02:17 +00001923void InitializedEntity::InitDeclLoc() {
1924 assert((Kind == EK_Variable || Kind == EK_Parameter || Kind == EK_Member) &&
1925 "InitDeclLoc cannot be used with non-declaration entities.");
1926
1927 if (TypeSourceInfo *DI = VariableOrMember->getTypeSourceInfo()) {
1928 TL = DI->getTypeLoc();
1929 return;
1930 }
1931
1932 // FIXME: Once we've gone through the effort to create the fake
1933 // TypeSourceInfo, should we cache it in the declaration?
1934 // (If not, we "leak" it).
1935 TypeSourceInfo *DI = VariableOrMember->getASTContext()
1936 .CreateTypeSourceInfo(VariableOrMember->getType());
1937 DI->getTypeLoc().initialize(VariableOrMember->getLocation());
1938 TL = DI->getTypeLoc();
1939}
1940
1941InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1942 CXXBaseSpecifier *Base)
1943{
1944 InitializedEntity Result;
1945 Result.Kind = EK_Base;
1946 Result.Base = Base;
1947 // FIXME: CXXBaseSpecifier should store a TypeLoc.
1948 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Base->getType());
1949 DI->getTypeLoc().initialize(Base->getSourceRange().getBegin());
1950 Result.TL = DI->getTypeLoc();
1951 return Result;
1952}
1953
Douglas Gregor99a2e602009-12-16 01:38:02 +00001954DeclarationName InitializedEntity::getName() const {
1955 switch (getKind()) {
1956 case EK_Variable:
1957 case EK_Parameter:
1958 case EK_Member:
1959 return VariableOrMember->getDeclName();
1960
1961 case EK_Result:
1962 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001963 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001964 case EK_Temporary:
1965 case EK_Base:
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001966 case EK_ArrayOrVectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001967 return DeclarationName();
1968 }
1969
1970 // Silence GCC warning
1971 return DeclarationName();
1972}
1973
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001974DeclaratorDecl *InitializedEntity::getDecl() const {
1975 switch (getKind()) {
1976 case EK_Variable:
1977 case EK_Parameter:
1978 case EK_Member:
1979 return VariableOrMember;
1980
1981 case EK_Result:
1982 case EK_Exception:
1983 case EK_New:
1984 case EK_Temporary:
1985 case EK_Base:
1986 case EK_ArrayOrVectorElement:
1987 return 0;
1988 }
1989
1990 // Silence GCC warning
1991 return 0;
1992}
1993
Douglas Gregor20093b42009-12-09 23:02:17 +00001994//===----------------------------------------------------------------------===//
1995// Initialization sequence
1996//===----------------------------------------------------------------------===//
1997
1998void InitializationSequence::Step::Destroy() {
1999 switch (Kind) {
2000 case SK_ResolveAddressOfOverloadedFunction:
2001 case SK_CastDerivedToBaseRValue:
2002 case SK_CastDerivedToBaseLValue:
2003 case SK_BindReference:
2004 case SK_BindReferenceToTemporary:
2005 case SK_UserConversion:
2006 case SK_QualificationConversionRValue:
2007 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002008 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002009 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002010 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002011 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002012 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00002013 break;
2014
2015 case SK_ConversionSequence:
2016 delete ICS;
2017 }
2018}
2019
2020void InitializationSequence::AddAddressOverloadResolutionStep(
2021 FunctionDecl *Function) {
2022 Step S;
2023 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2024 S.Type = Function->getType();
2025 S.Function = Function;
2026 Steps.push_back(S);
2027}
2028
2029void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
2030 bool IsLValue) {
2031 Step S;
2032 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
2033 S.Type = BaseType;
2034 Steps.push_back(S);
2035}
2036
2037void InitializationSequence::AddReferenceBindingStep(QualType T,
2038 bool BindingTemporary) {
2039 Step S;
2040 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2041 S.Type = T;
2042 Steps.push_back(S);
2043}
2044
Eli Friedman03981012009-12-11 02:42:07 +00002045void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2046 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002047 Step S;
2048 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002049 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00002050 S.Function = Function;
2051 Steps.push_back(S);
2052}
2053
2054void InitializationSequence::AddQualificationConversionStep(QualType Ty,
2055 bool IsLValue) {
2056 Step S;
2057 S.Kind = IsLValue? SK_QualificationConversionLValue
2058 : SK_QualificationConversionRValue;
2059 S.Type = Ty;
2060 Steps.push_back(S);
2061}
2062
2063void InitializationSequence::AddConversionSequenceStep(
2064 const ImplicitConversionSequence &ICS,
2065 QualType T) {
2066 Step S;
2067 S.Kind = SK_ConversionSequence;
2068 S.Type = T;
2069 S.ICS = new ImplicitConversionSequence(ICS);
2070 Steps.push_back(S);
2071}
2072
Douglas Gregord87b61f2009-12-10 17:56:55 +00002073void InitializationSequence::AddListInitializationStep(QualType T) {
2074 Step S;
2075 S.Kind = SK_ListInitialization;
2076 S.Type = T;
2077 Steps.push_back(S);
2078}
2079
Douglas Gregor51c56d62009-12-14 20:49:26 +00002080void
2081InitializationSequence::AddConstructorInitializationStep(
2082 CXXConstructorDecl *Constructor,
2083 QualType T) {
2084 Step S;
2085 S.Kind = SK_ConstructorInitialization;
2086 S.Type = T;
2087 S.Function = Constructor;
2088 Steps.push_back(S);
2089}
2090
Douglas Gregor71d17402009-12-15 00:01:57 +00002091void InitializationSequence::AddZeroInitializationStep(QualType T) {
2092 Step S;
2093 S.Kind = SK_ZeroInitialization;
2094 S.Type = T;
2095 Steps.push_back(S);
2096}
2097
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002098void InitializationSequence::AddCAssignmentStep(QualType T) {
2099 Step S;
2100 S.Kind = SK_CAssignment;
2101 S.Type = T;
2102 Steps.push_back(S);
2103}
2104
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002105void InitializationSequence::AddStringInitStep(QualType T) {
2106 Step S;
2107 S.Kind = SK_StringInit;
2108 S.Type = T;
2109 Steps.push_back(S);
2110}
2111
Douglas Gregor20093b42009-12-09 23:02:17 +00002112void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2113 OverloadingResult Result) {
2114 SequenceKind = FailedSequence;
2115 this->Failure = Failure;
2116 this->FailedOverloadResult = Result;
2117}
2118
2119//===----------------------------------------------------------------------===//
2120// Attempt initialization
2121//===----------------------------------------------------------------------===//
2122
2123/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002124static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002125 const InitializedEntity &Entity,
2126 const InitializationKind &Kind,
2127 InitListExpr *InitList,
2128 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002129 // FIXME: We only perform rudimentary checking of list
2130 // initializations at this point, then assume that any list
2131 // initialization of an array, aggregate, or scalar will be
2132 // well-formed. We we actually "perform" list initialization, we'll
2133 // do all of the necessary checking. C++0x initializer lists will
2134 // force us to perform more checking here.
2135 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2136
2137 QualType DestType = Entity.getType().getType();
2138
2139 // C++ [dcl.init]p13:
2140 // If T is a scalar type, then a declaration of the form
2141 //
2142 // T x = { a };
2143 //
2144 // is equivalent to
2145 //
2146 // T x = a;
2147 if (DestType->isScalarType()) {
2148 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2149 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2150 return;
2151 }
2152
2153 // Assume scalar initialization from a single value works.
2154 } else if (DestType->isAggregateType()) {
2155 // Assume aggregate initialization works.
2156 } else if (DestType->isVectorType()) {
2157 // Assume vector initialization works.
2158 } else if (DestType->isReferenceType()) {
2159 // FIXME: C++0x defines behavior for this.
2160 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2161 return;
2162 } else if (DestType->isRecordType()) {
2163 // FIXME: C++0x defines behavior for this
2164 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2165 }
2166
2167 // Add a general "list initialization" step.
2168 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002169}
2170
2171/// \brief Try a reference initialization that involves calling a conversion
2172/// function.
2173///
2174/// FIXME: look intos DRs 656, 896
2175static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2176 const InitializedEntity &Entity,
2177 const InitializationKind &Kind,
2178 Expr *Initializer,
2179 bool AllowRValues,
2180 InitializationSequence &Sequence) {
2181 QualType DestType = Entity.getType().getType();
2182 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2183 QualType T1 = cv1T1.getUnqualifiedType();
2184 QualType cv2T2 = Initializer->getType();
2185 QualType T2 = cv2T2.getUnqualifiedType();
2186
2187 bool DerivedToBase;
2188 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2189 T1, T2, DerivedToBase) &&
2190 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002191 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002192
2193 // Build the candidate set directly in the initialization sequence
2194 // structure, so that it will persist if we fail.
2195 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2196 CandidateSet.clear();
2197
2198 // Determine whether we are allowed to call explicit constructors or
2199 // explicit conversion operators.
2200 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2201
2202 const RecordType *T1RecordType = 0;
2203 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2204 // The type we're converting to is a class type. Enumerate its constructors
2205 // to see if there is a suitable conversion.
2206 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2207
2208 DeclarationName ConstructorName
2209 = S.Context.DeclarationNames.getCXXConstructorName(
2210 S.Context.getCanonicalType(T1).getUnqualifiedType());
2211 DeclContext::lookup_iterator Con, ConEnd;
2212 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2213 Con != ConEnd; ++Con) {
2214 // Find the constructor (which may be a template).
2215 CXXConstructorDecl *Constructor = 0;
2216 FunctionTemplateDecl *ConstructorTmpl
2217 = dyn_cast<FunctionTemplateDecl>(*Con);
2218 if (ConstructorTmpl)
2219 Constructor = cast<CXXConstructorDecl>(
2220 ConstructorTmpl->getTemplatedDecl());
2221 else
2222 Constructor = cast<CXXConstructorDecl>(*Con);
2223
2224 if (!Constructor->isInvalidDecl() &&
2225 Constructor->isConvertingConstructor(AllowExplicit)) {
2226 if (ConstructorTmpl)
2227 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2228 &Initializer, 1, CandidateSet);
2229 else
2230 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2231 }
2232 }
2233 }
2234
2235 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2236 // The type we're converting from is a class type, enumerate its conversion
2237 // functions.
2238 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2239
2240 // Determine the type we are converting to. If we are allowed to
2241 // convert to an rvalue, take the type that the destination type
2242 // refers to.
2243 QualType ToType = AllowRValues? cv1T1 : DestType;
2244
2245 const UnresolvedSet *Conversions
2246 = T2RecordDecl->getVisibleConversionFunctions();
2247 for (UnresolvedSet::iterator I = Conversions->begin(),
2248 E = Conversions->end();
2249 I != E; ++I) {
2250 NamedDecl *D = *I;
2251 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2252 if (isa<UsingShadowDecl>(D))
2253 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2254
2255 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2256 CXXConversionDecl *Conv;
2257 if (ConvTemplate)
2258 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2259 else
2260 Conv = cast<CXXConversionDecl>(*I);
2261
2262 // If the conversion function doesn't return a reference type,
2263 // it can't be considered for this conversion unless we're allowed to
2264 // consider rvalues.
2265 // FIXME: Do we need to make sure that we only consider conversion
2266 // candidates with reference-compatible results? That might be needed to
2267 // break recursion.
2268 if ((AllowExplicit || !Conv->isExplicit()) &&
2269 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2270 if (ConvTemplate)
2271 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2272 ToType, CandidateSet);
2273 else
2274 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2275 CandidateSet);
2276 }
2277 }
2278 }
2279
2280 SourceLocation DeclLoc = Initializer->getLocStart();
2281
2282 // Perform overload resolution. If it fails, return the failed result.
2283 OverloadCandidateSet::iterator Best;
2284 if (OverloadingResult Result
2285 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2286 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002287
Douglas Gregor20093b42009-12-09 23:02:17 +00002288 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002289
2290 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002291 if (isa<CXXConversionDecl>(Function))
2292 T2 = Function->getResultType();
2293 else
2294 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002295
2296 // Add the user-defined conversion step.
2297 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2298
2299 // Determine whether we need to perform derived-to-base or
2300 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002301 bool NewDerivedToBase = false;
2302 Sema::ReferenceCompareResult NewRefRelationship
2303 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2304 NewDerivedToBase);
2305 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2306 "Overload resolution picked a bad conversion function");
2307 (void)NewRefRelationship;
2308 if (NewDerivedToBase)
2309 Sequence.AddDerivedToBaseCastStep(
2310 S.Context.getQualifiedType(T1,
2311 T2.getNonReferenceType().getQualifiers()),
2312 /*isLValue=*/true);
2313
2314 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2315 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2316
2317 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2318 return OR_Success;
2319}
2320
2321/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2322static void TryReferenceInitialization(Sema &S,
2323 const InitializedEntity &Entity,
2324 const InitializationKind &Kind,
2325 Expr *Initializer,
2326 InitializationSequence &Sequence) {
2327 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2328
2329 QualType DestType = Entity.getType().getType();
2330 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2331 QualType T1 = cv1T1.getUnqualifiedType();
2332 QualType cv2T2 = Initializer->getType();
2333 QualType T2 = cv2T2.getUnqualifiedType();
2334 SourceLocation DeclLoc = Initializer->getLocStart();
2335
2336 // If the initializer is the address of an overloaded function, try
2337 // to resolve the overloaded function. If all goes well, T2 is the
2338 // type of the resulting function.
2339 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2340 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2341 T1,
2342 false);
2343 if (!Fn) {
2344 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2345 return;
2346 }
2347
2348 Sequence.AddAddressOverloadResolutionStep(Fn);
2349 cv2T2 = Fn->getType();
2350 T2 = cv2T2.getUnqualifiedType();
2351 }
2352
2353 // FIXME: Rvalue references
2354 bool ForceRValue = false;
2355
2356 // Compute some basic properties of the types and the initializer.
2357 bool isLValueRef = DestType->isLValueReferenceType();
2358 bool isRValueRef = !isLValueRef;
2359 bool DerivedToBase = false;
2360 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2361 Initializer->isLvalue(S.Context);
2362 Sema::ReferenceCompareResult RefRelationship
2363 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2364
2365 // C++0x [dcl.init.ref]p5:
2366 // A reference to type "cv1 T1" is initialized by an expression of type
2367 // "cv2 T2" as follows:
2368 //
2369 // - If the reference is an lvalue reference and the initializer
2370 // expression
2371 OverloadingResult ConvOvlResult = OR_Success;
2372 if (isLValueRef) {
2373 if (InitLvalue == Expr::LV_Valid &&
2374 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2375 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2376 // reference-compatible with "cv2 T2," or
2377 //
2378 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2379 // bit-field when we're determining whether the reference initialization
2380 // can occur. This property will be checked by PerformInitialization.
2381 if (DerivedToBase)
2382 Sequence.AddDerivedToBaseCastStep(
2383 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2384 /*isLValue=*/true);
2385 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2386 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2387 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2388 return;
2389 }
2390
2391 // - has a class type (i.e., T2 is a class type), where T1 is not
2392 // reference-related to T2, and can be implicitly converted to an
2393 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2394 // with "cv3 T3" (this conversion is selected by enumerating the
2395 // applicable conversion functions (13.3.1.6) and choosing the best
2396 // one through overload resolution (13.3)),
2397 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2398 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2399 Initializer,
2400 /*AllowRValues=*/false,
2401 Sequence);
2402 if (ConvOvlResult == OR_Success)
2403 return;
2404 }
2405 }
2406
2407 // - Otherwise, the reference shall be an lvalue reference to a
2408 // non-volatile const type (i.e., cv1 shall be const), or the reference
2409 // shall be an rvalue reference and the initializer expression shall
2410 // be an rvalue.
2411 if (!((isLValueRef && cv1T1.getCVRQualifiers() == Qualifiers::Const) ||
2412 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2413 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2414 Sequence.SetOverloadFailure(
2415 InitializationSequence::FK_ReferenceInitOverloadFailed,
2416 ConvOvlResult);
2417 else if (isLValueRef)
2418 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2419 ? (RefRelationship == Sema::Ref_Related
2420 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2421 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2422 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2423 else
2424 Sequence.SetFailed(
2425 InitializationSequence::FK_RValueReferenceBindingToLValue);
2426
2427 return;
2428 }
2429
2430 // - If T1 and T2 are class types and
2431 if (T1->isRecordType() && T2->isRecordType()) {
2432 // - the initializer expression is an rvalue and "cv1 T1" is
2433 // reference-compatible with "cv2 T2", or
2434 if (InitLvalue != Expr::LV_Valid &&
2435 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2436 if (DerivedToBase)
2437 Sequence.AddDerivedToBaseCastStep(
2438 S.Context.getQualifiedType(T1, cv2T2.getQualifiers()),
2439 /*isLValue=*/false);
2440 if (cv1T1.getQualifiers() != cv2T2.getQualifiers())
2441 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2442 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2443 return;
2444 }
2445
2446 // - T1 is not reference-related to T2 and the initializer expression
2447 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2448 // conversion is selected by enumerating the applicable conversion
2449 // functions (13.3.1.6) and choosing the best one through overload
2450 // resolution (13.3)),
2451 if (RefRelationship == Sema::Ref_Incompatible) {
2452 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2453 Kind, Initializer,
2454 /*AllowRValues=*/true,
2455 Sequence);
2456 if (ConvOvlResult)
2457 Sequence.SetOverloadFailure(
2458 InitializationSequence::FK_ReferenceInitOverloadFailed,
2459 ConvOvlResult);
2460
2461 return;
2462 }
2463
2464 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2465 return;
2466 }
2467
2468 // - If the initializer expression is an rvalue, with T2 an array type,
2469 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2470 // is bound to the object represented by the rvalue (see 3.10).
2471 // FIXME: How can an array type be reference-compatible with anything?
2472 // Don't we mean the element types of T1 and T2?
2473
2474 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2475 // from the initializer expression using the rules for a non-reference
2476 // copy initialization (8.5). The reference is then bound to the
2477 // temporary. [...]
2478 // Determine whether we are allowed to call explicit constructors or
2479 // explicit conversion operators.
2480 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2481 ImplicitConversionSequence ICS
2482 = S.TryImplicitConversion(Initializer, cv1T1,
2483 /*SuppressUserConversions=*/false, AllowExplicit,
2484 /*ForceRValue=*/false,
2485 /*FIXME:InOverloadResolution=*/false,
2486 /*UserCast=*/Kind.isExplicitCast());
2487
2488 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2489 // FIXME: Use the conversion function set stored in ICS to turn
2490 // this into an overloading ambiguity diagnostic. However, we need
2491 // to keep that set as an OverloadCandidateSet rather than as some
2492 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002493 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2494 Sequence.SetOverloadFailure(
2495 InitializationSequence::FK_ReferenceInitOverloadFailed,
2496 ConvOvlResult);
2497 else
2498 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002499 return;
2500 }
2501
2502 // [...] If T1 is reference-related to T2, cv1 must be the
2503 // same cv-qualification as, or greater cv-qualification
2504 // than, cv2; otherwise, the program is ill-formed.
2505 if (RefRelationship == Sema::Ref_Related &&
2506 !cv1T1.isAtLeastAsQualifiedAs(cv2T2)) {
2507 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2508 return;
2509 }
2510
2511 // Perform the actual conversion.
2512 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2513 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2514 return;
2515}
2516
2517/// \brief Attempt character array initialization from a string literal
2518/// (C++ [dcl.init.string], C99 6.7.8).
2519static void TryStringLiteralInitialization(Sema &S,
2520 const InitializedEntity &Entity,
2521 const InitializationKind &Kind,
2522 Expr *Initializer,
2523 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002524 Sequence.setSequenceKind(InitializationSequence::StringInit);
2525 Sequence.AddStringInitStep(Entity.getType().getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002526}
2527
Douglas Gregor20093b42009-12-09 23:02:17 +00002528/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2529/// enumerates the constructors of the initialized entity and performs overload
2530/// resolution to select the best.
2531static void TryConstructorInitialization(Sema &S,
2532 const InitializedEntity &Entity,
2533 const InitializationKind &Kind,
2534 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002535 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002536 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002537 if (Kind.getKind() == InitializationKind::IK_Copy)
2538 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2539 else
2540 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002541
2542 // Build the candidate set directly in the initialization sequence
2543 // structure, so that it will persist if we fail.
2544 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2545 CandidateSet.clear();
2546
2547 // Determine whether we are allowed to call explicit constructors or
2548 // explicit conversion operators.
2549 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2550 Kind.getKind() == InitializationKind::IK_Value ||
2551 Kind.getKind() == InitializationKind::IK_Default);
2552
2553 // The type we're converting to is a class type. Enumerate its constructors
2554 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002555 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2556 assert(DestRecordType && "Constructor initialization requires record type");
2557 CXXRecordDecl *DestRecordDecl
2558 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2559
2560 DeclarationName ConstructorName
2561 = S.Context.DeclarationNames.getCXXConstructorName(
2562 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2563 DeclContext::lookup_iterator Con, ConEnd;
2564 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2565 Con != ConEnd; ++Con) {
2566 // Find the constructor (which may be a template).
2567 CXXConstructorDecl *Constructor = 0;
2568 FunctionTemplateDecl *ConstructorTmpl
2569 = dyn_cast<FunctionTemplateDecl>(*Con);
2570 if (ConstructorTmpl)
2571 Constructor = cast<CXXConstructorDecl>(
2572 ConstructorTmpl->getTemplatedDecl());
2573 else
2574 Constructor = cast<CXXConstructorDecl>(*Con);
2575
2576 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002577 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002578 if (ConstructorTmpl)
2579 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2580 Args, NumArgs, CandidateSet);
2581 else
2582 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2583 }
2584 }
2585
2586 SourceLocation DeclLoc = Kind.getLocation();
2587
2588 // Perform overload resolution. If it fails, return the failed result.
2589 OverloadCandidateSet::iterator Best;
2590 if (OverloadingResult Result
2591 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2592 Sequence.SetOverloadFailure(
2593 InitializationSequence::FK_ConstructorOverloadFailed,
2594 Result);
2595 return;
2596 }
2597
2598 // Add the constructor initialization step. Any cv-qualification conversion is
2599 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002600 if (Kind.getKind() == InitializationKind::IK_Copy) {
2601 Sequence.AddUserConversionStep(Best->Function, DestType);
2602 } else {
2603 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002604 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002605 DestType);
2606 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002607}
2608
Douglas Gregor71d17402009-12-15 00:01:57 +00002609/// \brief Attempt value initialization (C++ [dcl.init]p7).
2610static void TryValueInitialization(Sema &S,
2611 const InitializedEntity &Entity,
2612 const InitializationKind &Kind,
2613 InitializationSequence &Sequence) {
2614 // C++ [dcl.init]p5:
2615 //
2616 // To value-initialize an object of type T means:
2617 QualType T = Entity.getType().getType();
2618
2619 // -- if T is an array type, then each element is value-initialized;
2620 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2621 T = AT->getElementType();
2622
2623 if (const RecordType *RT = T->getAs<RecordType>()) {
2624 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2625 // -- if T is a class type (clause 9) with a user-declared
2626 // constructor (12.1), then the default constructor for T is
2627 // called (and the initialization is ill-formed if T has no
2628 // accessible default constructor);
2629 //
2630 // FIXME: we really want to refer to a single subobject of the array,
2631 // but Entity doesn't have a way to capture that (yet).
2632 if (ClassDecl->hasUserDeclaredConstructor())
2633 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2634
Douglas Gregor16006c92009-12-16 18:50:27 +00002635 // -- if T is a (possibly cv-qualified) non-union class type
2636 // without a user-provided constructor, then the object is
2637 // zero-initialized and, if T’s implicitly-declared default
2638 // constructor is non-trivial, that constructor is called.
2639 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2640 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2641 !ClassDecl->hasTrivialConstructor()) {
2642 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2643 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2644 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002645 }
2646 }
2647
2648 Sequence.AddZeroInitializationStep(Entity.getType().getType());
2649 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2650}
2651
Douglas Gregor99a2e602009-12-16 01:38:02 +00002652/// \brief Attempt default initialization (C++ [dcl.init]p6).
2653static void TryDefaultInitialization(Sema &S,
2654 const InitializedEntity &Entity,
2655 const InitializationKind &Kind,
2656 InitializationSequence &Sequence) {
2657 assert(Kind.getKind() == InitializationKind::IK_Default);
2658
2659 // C++ [dcl.init]p6:
2660 // To default-initialize an object of type T means:
2661 // - if T is an array type, each element is default-initialized;
2662 QualType DestType = Entity.getType().getType();
2663 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2664 DestType = Array->getElementType();
2665
2666 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2667 // constructor for T is called (and the initialization is ill-formed if
2668 // T has no accessible default constructor);
2669 if (DestType->isRecordType()) {
2670 // FIXME: If a program calls for the default initialization of an object of
2671 // a const-qualified type T, T shall be a class type with a user-provided
2672 // default constructor.
2673 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2674 Sequence);
2675 }
2676
2677 // - otherwise, no initialization is performed.
2678 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2679
2680 // If a program calls for the default initialization of an object of
2681 // a const-qualified type T, T shall be a class type with a user-provided
2682 // default constructor.
2683 if (DestType.isConstQualified())
2684 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2685}
2686
Douglas Gregor20093b42009-12-09 23:02:17 +00002687/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2688/// which enumerates all conversion functions and performs overload resolution
2689/// to select the best.
2690static void TryUserDefinedConversion(Sema &S,
2691 const InitializedEntity &Entity,
2692 const InitializationKind &Kind,
2693 Expr *Initializer,
2694 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002695 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2696
2697 QualType DestType = Entity.getType().getType();
2698 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2699 QualType SourceType = Initializer->getType();
2700 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2701 "Must have a class type to perform a user-defined conversion");
2702
2703 // Build the candidate set directly in the initialization sequence
2704 // structure, so that it will persist if we fail.
2705 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2706 CandidateSet.clear();
2707
2708 // Determine whether we are allowed to call explicit constructors or
2709 // explicit conversion operators.
2710 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2711
2712 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2713 // The type we're converting to is a class type. Enumerate its constructors
2714 // to see if there is a suitable conversion.
2715 CXXRecordDecl *DestRecordDecl
2716 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2717
2718 DeclarationName ConstructorName
2719 = S.Context.DeclarationNames.getCXXConstructorName(
2720 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2721 DeclContext::lookup_iterator Con, ConEnd;
2722 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2723 Con != ConEnd; ++Con) {
2724 // Find the constructor (which may be a template).
2725 CXXConstructorDecl *Constructor = 0;
2726 FunctionTemplateDecl *ConstructorTmpl
2727 = dyn_cast<FunctionTemplateDecl>(*Con);
2728 if (ConstructorTmpl)
2729 Constructor = cast<CXXConstructorDecl>(
2730 ConstructorTmpl->getTemplatedDecl());
2731 else
2732 Constructor = cast<CXXConstructorDecl>(*Con);
2733
2734 if (!Constructor->isInvalidDecl() &&
2735 Constructor->isConvertingConstructor(AllowExplicit)) {
2736 if (ConstructorTmpl)
2737 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2738 &Initializer, 1, CandidateSet);
2739 else
2740 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2741 }
2742 }
2743 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002744
2745 SourceLocation DeclLoc = Initializer->getLocStart();
2746
Douglas Gregor4a520a22009-12-14 17:27:33 +00002747 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2748 // The type we're converting from is a class type, enumerate its conversion
2749 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002750
Eli Friedman33c2da92009-12-20 22:12:03 +00002751 // We can only enumerate the conversion functions for a complete type; if
2752 // the type isn't complete, simply skip this step.
2753 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2754 CXXRecordDecl *SourceRecordDecl
2755 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002756
Eli Friedman33c2da92009-12-20 22:12:03 +00002757 const UnresolvedSet *Conversions
2758 = SourceRecordDecl->getVisibleConversionFunctions();
2759 for (UnresolvedSet::iterator I = Conversions->begin(),
2760 E = Conversions->end();
2761 I != E; ++I) {
2762 NamedDecl *D = *I;
2763 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2764 if (isa<UsingShadowDecl>(D))
2765 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2766
2767 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2768 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002769 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002770 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002771 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002772 Conv = cast<CXXConversionDecl>(*I);
2773
2774 if (AllowExplicit || !Conv->isExplicit()) {
2775 if (ConvTemplate)
2776 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2777 Initializer, DestType,
2778 CandidateSet);
2779 else
2780 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2781 CandidateSet);
2782 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002783 }
2784 }
2785 }
2786
Douglas Gregor4a520a22009-12-14 17:27:33 +00002787 // Perform overload resolution. If it fails, return the failed result.
2788 OverloadCandidateSet::iterator Best;
2789 if (OverloadingResult Result
2790 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2791 Sequence.SetOverloadFailure(
2792 InitializationSequence::FK_UserConversionOverloadFailed,
2793 Result);
2794 return;
2795 }
2796
2797 FunctionDecl *Function = Best->Function;
2798
2799 if (isa<CXXConstructorDecl>(Function)) {
2800 // Add the user-defined conversion step. Any cv-qualification conversion is
2801 // subsumed by the initialization.
2802 Sequence.AddUserConversionStep(Function, DestType);
2803 return;
2804 }
2805
2806 // Add the user-defined conversion step that calls the conversion function.
2807 QualType ConvType = Function->getResultType().getNonReferenceType();
2808 Sequence.AddUserConversionStep(Function, ConvType);
2809
2810 // If the conversion following the call to the conversion function is
2811 // interesting, add it as a separate step.
2812 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2813 Best->FinalConversion.Third) {
2814 ImplicitConversionSequence ICS;
2815 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2816 ICS.Standard = Best->FinalConversion;
2817 Sequence.AddConversionSequenceStep(ICS, DestType);
2818 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002819}
2820
2821/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2822/// non-class type to another.
2823static void TryImplicitConversion(Sema &S,
2824 const InitializedEntity &Entity,
2825 const InitializationKind &Kind,
2826 Expr *Initializer,
2827 InitializationSequence &Sequence) {
2828 ImplicitConversionSequence ICS
2829 = S.TryImplicitConversion(Initializer, Entity.getType().getType(),
2830 /*SuppressUserConversions=*/true,
2831 /*AllowExplicit=*/false,
2832 /*ForceRValue=*/false,
2833 /*FIXME:InOverloadResolution=*/false,
2834 /*UserCast=*/Kind.isExplicitCast());
2835
2836 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
2837 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2838 return;
2839 }
2840
2841 Sequence.AddConversionSequenceStep(ICS, Entity.getType().getType());
2842}
2843
2844InitializationSequence::InitializationSequence(Sema &S,
2845 const InitializedEntity &Entity,
2846 const InitializationKind &Kind,
2847 Expr **Args,
2848 unsigned NumArgs) {
2849 ASTContext &Context = S.Context;
2850
2851 // C++0x [dcl.init]p16:
2852 // The semantics of initializers are as follows. The destination type is
2853 // the type of the object or reference being initialized and the source
2854 // type is the type of the initializer expression. The source type is not
2855 // defined when the initializer is a braced-init-list or when it is a
2856 // parenthesized list of expressions.
2857 QualType DestType = Entity.getType().getType();
2858
2859 if (DestType->isDependentType() ||
2860 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2861 SequenceKind = DependentSequence;
2862 return;
2863 }
2864
2865 QualType SourceType;
2866 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002867 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002868 Initializer = Args[0];
2869 if (!isa<InitListExpr>(Initializer))
2870 SourceType = Initializer->getType();
2871 }
2872
2873 // - If the initializer is a braced-init-list, the object is
2874 // list-initialized (8.5.4).
2875 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2876 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002877 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002878 }
2879
2880 // - If the destination type is a reference type, see 8.5.3.
2881 if (DestType->isReferenceType()) {
2882 // C++0x [dcl.init.ref]p1:
2883 // A variable declared to be a T& or T&&, that is, "reference to type T"
2884 // (8.3.2), shall be initialized by an object, or function, of type T or
2885 // by an object that can be converted into a T.
2886 // (Therefore, multiple arguments are not permitted.)
2887 if (NumArgs != 1)
2888 SetFailed(FK_TooManyInitsForReference);
2889 else
2890 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2891 return;
2892 }
2893
2894 // - If the destination type is an array of characters, an array of
2895 // char16_t, an array of char32_t, or an array of wchar_t, and the
2896 // initializer is a string literal, see 8.5.2.
2897 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2898 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2899 return;
2900 }
2901
2902 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002903 if (Kind.getKind() == InitializationKind::IK_Value ||
2904 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002905 TryValueInitialization(S, Entity, Kind, *this);
2906 return;
2907 }
2908
Douglas Gregor99a2e602009-12-16 01:38:02 +00002909 // Handle default initialization.
2910 if (Kind.getKind() == InitializationKind::IK_Default){
2911 TryDefaultInitialization(S, Entity, Kind, *this);
2912 return;
2913 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002914
Douglas Gregor20093b42009-12-09 23:02:17 +00002915 // - Otherwise, if the destination type is an array, the program is
2916 // ill-formed.
2917 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2918 if (AT->getElementType()->isAnyCharacterType())
2919 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2920 else
2921 SetFailed(FK_ArrayNeedsInitList);
2922
2923 return;
2924 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002925
2926 // Handle initialization in C
2927 if (!S.getLangOptions().CPlusPlus) {
2928 setSequenceKind(CAssignment);
2929 AddCAssignmentStep(DestType);
2930 return;
2931 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002932
2933 // - If the destination type is a (possibly cv-qualified) class type:
2934 if (DestType->isRecordType()) {
2935 // - If the initialization is direct-initialization, or if it is
2936 // copy-initialization where the cv-unqualified version of the
2937 // source type is the same class as, or a derived class of, the
2938 // class of the destination, constructors are considered. [...]
2939 if (Kind.getKind() == InitializationKind::IK_Direct ||
2940 (Kind.getKind() == InitializationKind::IK_Copy &&
2941 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2942 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002943 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
2944 Entity.getType().getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002945 // - Otherwise (i.e., for the remaining copy-initialization cases),
2946 // user-defined conversion sequences that can convert from the source
2947 // type to the destination type or (when a conversion function is
2948 // used) to a derived class thereof are enumerated as described in
2949 // 13.3.1.4, and the best one is chosen through overload resolution
2950 // (13.3).
2951 else
2952 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2953 return;
2954 }
2955
Douglas Gregor99a2e602009-12-16 01:38:02 +00002956 if (NumArgs > 1) {
2957 SetFailed(FK_TooManyInitsForScalar);
2958 return;
2959 }
2960 assert(NumArgs == 1 && "Zero-argument case handled above");
2961
Douglas Gregor20093b42009-12-09 23:02:17 +00002962 // - Otherwise, if the source type is a (possibly cv-qualified) class
2963 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002964 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002965 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2966 return;
2967 }
2968
2969 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002970 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002971 // conversions (Clause 4) will be used, if necessary, to convert the
2972 // initializer expression to the cv-unqualified version of the
2973 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002974 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002975 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2976}
2977
2978InitializationSequence::~InitializationSequence() {
2979 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2980 StepEnd = Steps.end();
2981 Step != StepEnd; ++Step)
2982 Step->Destroy();
2983}
2984
2985//===----------------------------------------------------------------------===//
2986// Perform initialization
2987//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002988static Sema::AssignmentAction
2989getAssignmentAction(const InitializedEntity &Entity) {
2990 switch(Entity.getKind()) {
2991 case InitializedEntity::EK_Variable:
2992 case InitializedEntity::EK_New:
2993 return Sema::AA_Initializing;
2994
2995 case InitializedEntity::EK_Parameter:
2996 // FIXME: Can we tell when we're sending vs. passing?
2997 return Sema::AA_Passing;
2998
2999 case InitializedEntity::EK_Result:
3000 return Sema::AA_Returning;
3001
3002 case InitializedEntity::EK_Exception:
3003 case InitializedEntity::EK_Base:
3004 llvm_unreachable("No assignment action for C++-specific initialization");
3005 break;
3006
3007 case InitializedEntity::EK_Temporary:
3008 // FIXME: Can we tell apart casting vs. converting?
3009 return Sema::AA_Casting;
3010
3011 case InitializedEntity::EK_Member:
3012 case InitializedEntity::EK_ArrayOrVectorElement:
3013 return Sema::AA_Initializing;
3014 }
3015
3016 return Sema::AA_Converting;
3017}
3018
3019static bool shouldBindAsTemporary(const InitializedEntity &Entity,
3020 bool IsCopy) {
3021 switch (Entity.getKind()) {
3022 case InitializedEntity::EK_Result:
3023 case InitializedEntity::EK_Exception:
3024 return !IsCopy;
3025
3026 case InitializedEntity::EK_New:
3027 case InitializedEntity::EK_Variable:
3028 case InitializedEntity::EK_Base:
3029 case InitializedEntity::EK_Member:
3030 case InitializedEntity::EK_ArrayOrVectorElement:
3031 return false;
3032
3033 case InitializedEntity::EK_Parameter:
3034 case InitializedEntity::EK_Temporary:
3035 return true;
3036 }
3037
3038 llvm_unreachable("missed an InitializedEntity kind?");
3039}
3040
3041/// \brief If we need to perform an additional copy of the initialized object
3042/// for this kind of entity (e.g., the result of a function or an object being
3043/// thrown), make the copy.
3044static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
3045 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003046 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003047 Sema::OwningExprResult CurInit) {
3048 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003049
3050 switch (Entity.getKind()) {
3051 case InitializedEntity::EK_Result:
3052 if (Entity.getType().getType()->isReferenceType())
3053 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003054 Loc = Entity.getReturnLoc();
3055 break;
3056
3057 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003058 Loc = Entity.getThrowLoc();
3059 break;
3060
3061 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003062 if (Entity.getType().getType()->isReferenceType() ||
3063 Kind.getKind() != InitializationKind::IK_Copy)
3064 return move(CurInit);
3065 Loc = Entity.getDecl()->getLocation();
3066 break;
3067
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003068 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003069 // FIXME: Do we need this initialization for a parameter?
3070 return move(CurInit);
3071
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003072 case InitializedEntity::EK_New:
3073 case InitializedEntity::EK_Temporary:
3074 case InitializedEntity::EK_Base:
3075 case InitializedEntity::EK_Member:
3076 case InitializedEntity::EK_ArrayOrVectorElement:
3077 // We don't need to copy for any of these initialized entities.
3078 return move(CurInit);
3079 }
3080
3081 Expr *CurInitExpr = (Expr *)CurInit.get();
3082 CXXRecordDecl *Class = 0;
3083 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3084 Class = cast<CXXRecordDecl>(Record->getDecl());
3085 if (!Class)
3086 return move(CurInit);
3087
3088 // Perform overload resolution using the class's copy constructors.
3089 DeclarationName ConstructorName
3090 = S.Context.DeclarationNames.getCXXConstructorName(
3091 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3092 DeclContext::lookup_iterator Con, ConEnd;
3093 OverloadCandidateSet CandidateSet;
3094 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3095 Con != ConEnd; ++Con) {
3096 // Find the constructor (which may be a template).
3097 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3098 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003099 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003100 continue;
3101
3102 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3103 }
3104
3105 OverloadCandidateSet::iterator Best;
3106 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3107 case OR_Success:
3108 break;
3109
3110 case OR_No_Viable_Function:
3111 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003112 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003113 << CurInitExpr->getSourceRange();
3114 S.PrintOverloadCandidates(CandidateSet, false);
3115 return S.ExprError();
3116
3117 case OR_Ambiguous:
3118 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003119 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003120 << CurInitExpr->getSourceRange();
3121 S.PrintOverloadCandidates(CandidateSet, true);
3122 return S.ExprError();
3123
3124 case OR_Deleted:
3125 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003126 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003127 << CurInitExpr->getSourceRange();
3128 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3129 << Best->Function->isDeleted();
3130 return S.ExprError();
3131 }
3132
3133 CurInit.release();
3134 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3135 cast<CXXConstructorDecl>(Best->Function),
3136 /*Elidable=*/true,
3137 Sema::MultiExprArg(S,
3138 (void**)&CurInitExpr, 1));
3139}
Douglas Gregor20093b42009-12-09 23:02:17 +00003140
3141Action::OwningExprResult
3142InitializationSequence::Perform(Sema &S,
3143 const InitializedEntity &Entity,
3144 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003145 Action::MultiExprArg Args,
3146 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003147 if (SequenceKind == FailedSequence) {
3148 unsigned NumArgs = Args.size();
3149 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3150 return S.ExprError();
3151 }
3152
3153 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003154 // If the declaration is a non-dependent, incomplete array type
3155 // that has an initializer, then its type will be completed once
3156 // the initializer is instantiated.
3157 if (ResultType && !Entity.getType().getType()->isDependentType() &&
3158 Args.size() == 1) {
3159 QualType DeclType = Entity.getType().getType();
3160 if (const IncompleteArrayType *ArrayT
3161 = S.Context.getAsIncompleteArrayType(DeclType)) {
3162 // FIXME: We don't currently have the ability to accurately
3163 // compute the length of an initializer list without
3164 // performing full type-checking of the initializer list
3165 // (since we have to determine where braces are implicitly
3166 // introduced and such). So, we fall back to making the array
3167 // type a dependently-sized array type with no specified
3168 // bound.
3169 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3170 SourceRange Brackets;
3171 // Scavange the location of the brackets from the entity, if we can.
3172 if (isa<IncompleteArrayTypeLoc>(Entity.getType())) {
3173 IncompleteArrayTypeLoc ArrayLoc
3174 = cast<IncompleteArrayTypeLoc>(Entity.getType());
3175 Brackets = ArrayLoc.getBracketsRange();
3176 }
3177
3178 *ResultType
3179 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3180 /*NumElts=*/0,
3181 ArrayT->getSizeModifier(),
3182 ArrayT->getIndexTypeCVRQualifiers(),
3183 Brackets);
3184 }
3185
3186 }
3187 }
3188
Douglas Gregor20093b42009-12-09 23:02:17 +00003189 if (Kind.getKind() == InitializationKind::IK_Copy)
3190 return Sema::OwningExprResult(S, Args.release()[0]);
3191
3192 unsigned NumArgs = Args.size();
3193 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3194 SourceLocation(),
3195 (Expr **)Args.release(),
3196 NumArgs,
3197 SourceLocation()));
3198 }
3199
Douglas Gregor99a2e602009-12-16 01:38:02 +00003200 if (SequenceKind == NoInitialization)
3201 return S.Owned((Expr *)0);
3202
Douglas Gregor20093b42009-12-09 23:02:17 +00003203 QualType DestType = Entity.getType().getType().getNonReferenceType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003204 if (ResultType)
3205 *ResultType = Entity.getType().getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003206
Douglas Gregor99a2e602009-12-16 01:38:02 +00003207 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3208
3209 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3210
3211 // For initialization steps that start with a single initializer,
3212 // grab the only argument out the Args and place it into the "current"
3213 // initializer.
3214 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003215 case SK_ResolveAddressOfOverloadedFunction:
3216 case SK_CastDerivedToBaseRValue:
3217 case SK_CastDerivedToBaseLValue:
3218 case SK_BindReference:
3219 case SK_BindReferenceToTemporary:
3220 case SK_UserConversion:
3221 case SK_QualificationConversionLValue:
3222 case SK_QualificationConversionRValue:
3223 case SK_ConversionSequence:
3224 case SK_ListInitialization:
3225 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003226 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003227 assert(Args.size() == 1);
3228 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3229 if (CurInit.isInvalid())
3230 return S.ExprError();
3231 break;
3232
3233 case SK_ConstructorInitialization:
3234 case SK_ZeroInitialization:
3235 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003236 }
3237
3238 // Walk through the computed steps for the initialization sequence,
3239 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003240 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003241 for (step_iterator Step = step_begin(), StepEnd = step_end();
3242 Step != StepEnd; ++Step) {
3243 if (CurInit.isInvalid())
3244 return S.ExprError();
3245
3246 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003247 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003248
3249 switch (Step->Kind) {
3250 case SK_ResolveAddressOfOverloadedFunction:
3251 // Overload resolution determined which function invoke; update the
3252 // initializer to reflect that choice.
3253 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3254 break;
3255
3256 case SK_CastDerivedToBaseRValue:
3257 case SK_CastDerivedToBaseLValue: {
3258 // We have a derived-to-base cast that produces either an rvalue or an
3259 // lvalue. Perform that cast.
3260
3261 // Casts to inaccessible base classes are allowed with C-style casts.
3262 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3263 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3264 CurInitExpr->getLocStart(),
3265 CurInitExpr->getSourceRange(),
3266 IgnoreBaseAccess))
3267 return S.ExprError();
3268
3269 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3270 CastExpr::CK_DerivedToBase,
3271 (Expr*)CurInit.release(),
3272 Step->Kind == SK_CastDerivedToBaseLValue));
3273 break;
3274 }
3275
3276 case SK_BindReference:
3277 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3278 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3279 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
3280 << Entity.getType().getType().isVolatileQualified()
3281 << BitField->getDeclName()
3282 << CurInitExpr->getSourceRange();
3283 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3284 return S.ExprError();
3285 }
3286
3287 // Reference binding does not have any corresponding ASTs.
3288
3289 // Check exception specifications
3290 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3291 return S.ExprError();
3292 break;
3293
3294 case SK_BindReferenceToTemporary:
3295 // Check exception specifications
3296 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3297 return S.ExprError();
3298
3299 // FIXME: At present, we have no AST to describe when we need to make a
3300 // temporary to bind a reference to. We should.
3301 break;
3302
3303 case SK_UserConversion: {
3304 // We have a user-defined conversion that invokes either a constructor
3305 // or a conversion function.
3306 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003307 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 if (CXXConstructorDecl *Constructor
3309 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3310 // Build a call to the selected constructor.
3311 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3312 SourceLocation Loc = CurInitExpr->getLocStart();
3313 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3314
3315 // Determine the arguments required to actually perform the constructor
3316 // call.
3317 if (S.CompleteConstructorCall(Constructor,
3318 Sema::MultiExprArg(S,
3319 (void **)&CurInitExpr,
3320 1),
3321 Loc, ConstructorArgs))
3322 return S.ExprError();
3323
3324 // Build the an expression that constructs a temporary.
3325 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3326 move_arg(ConstructorArgs));
3327 if (CurInit.isInvalid())
3328 return S.ExprError();
3329
3330 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003331 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3332 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3333 S.IsDerivedFrom(SourceType, Class))
3334 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003335 } else {
3336 // Build a call to the conversion function.
3337 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003338
Douglas Gregor20093b42009-12-09 23:02:17 +00003339 // FIXME: Should we move this initialization into a separate
3340 // derived-to-base conversion? I believe the answer is "no", because
3341 // we don't want to turn off access control here for c-style casts.
3342 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3343 return S.ExprError();
3344
3345 // Do a little dance to make sure that CurInit has the proper
3346 // pointer.
3347 CurInit.release();
3348
3349 // Build the actual call to the conversion function.
3350 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3351 if (CurInit.isInvalid() || !CurInit.get())
3352 return S.ExprError();
3353
3354 CastKind = CastExpr::CK_UserDefinedConversion;
3355 }
3356
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003357 if (shouldBindAsTemporary(Entity, IsCopy))
3358 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3359
Douglas Gregor20093b42009-12-09 23:02:17 +00003360 CurInitExpr = CurInit.takeAs<Expr>();
3361 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3362 CastKind,
3363 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003364 false));
3365
3366 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003367 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003368 break;
3369 }
3370
3371 case SK_QualificationConversionLValue:
3372 case SK_QualificationConversionRValue:
3373 // Perform a qualification conversion; these can never go wrong.
3374 S.ImpCastExprToType(CurInitExpr, Step->Type,
3375 CastExpr::CK_NoOp,
3376 Step->Kind == SK_QualificationConversionLValue);
3377 CurInit.release();
3378 CurInit = S.Owned(CurInitExpr);
3379 break;
3380
3381 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003382 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003383 false, false, *Step->ICS))
3384 return S.ExprError();
3385
3386 CurInit.release();
3387 CurInit = S.Owned(CurInitExpr);
3388 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003389
3390 case SK_ListInitialization: {
3391 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3392 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003393 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003394 return S.ExprError();
3395
3396 CurInit.release();
3397 CurInit = S.Owned(InitList);
3398 break;
3399 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003400
3401 case SK_ConstructorInitialization: {
3402 CXXConstructorDecl *Constructor
3403 = cast<CXXConstructorDecl>(Step->Function);
3404
3405 // Build a call to the selected constructor.
3406 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3407 SourceLocation Loc = Kind.getLocation();
3408
3409 // Determine the arguments required to actually perform the constructor
3410 // call.
3411 if (S.CompleteConstructorCall(Constructor, move(Args),
3412 Loc, ConstructorArgs))
3413 return S.ExprError();
3414
3415 // Build the an expression that constructs a temporary.
Douglas Gregor745880f2009-12-20 22:01:25 +00003416 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType().getType(),
3417 Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003418 move_arg(ConstructorArgs),
3419 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003420 if (CurInit.isInvalid())
3421 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003422
3423 bool Elidable
3424 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3425 if (shouldBindAsTemporary(Entity, Elidable))
3426 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3427
3428 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003429 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003430 break;
3431 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003432
3433 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003434 step_iterator NextStep = Step;
3435 ++NextStep;
3436 if (NextStep != StepEnd &&
3437 NextStep->Kind == SK_ConstructorInitialization) {
3438 // The need for zero-initialization is recorded directly into
3439 // the call to the object's constructor within the next step.
3440 ConstructorInitRequiresZeroInit = true;
3441 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3442 S.getLangOptions().CPlusPlus &&
3443 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003444 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3445 Kind.getRange().getBegin(),
3446 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003447 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003448 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003449 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003450 break;
3451 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003452
3453 case SK_CAssignment: {
3454 QualType SourceType = CurInitExpr->getType();
3455 Sema::AssignConvertType ConvTy =
3456 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
3457 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3458 Step->Type, SourceType,
3459 CurInitExpr, getAssignmentAction(Entity)))
3460 return S.ExprError();
3461
3462 CurInit.release();
3463 CurInit = S.Owned(CurInitExpr);
3464 break;
3465 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003466
3467 case SK_StringInit: {
3468 QualType Ty = Step->Type;
3469 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3470 break;
3471 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003472 }
3473 }
3474
3475 return move(CurInit);
3476}
3477
3478//===----------------------------------------------------------------------===//
3479// Diagnose initialization failures
3480//===----------------------------------------------------------------------===//
3481bool InitializationSequence::Diagnose(Sema &S,
3482 const InitializedEntity &Entity,
3483 const InitializationKind &Kind,
3484 Expr **Args, unsigned NumArgs) {
3485 if (SequenceKind != FailedSequence)
3486 return false;
3487
3488 QualType DestType = Entity.getType().getType();
3489 switch (Failure) {
3490 case FK_TooManyInitsForReference:
3491 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3492 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3493 break;
3494
3495 case FK_ArrayNeedsInitList:
3496 case FK_ArrayNeedsInitListOrStringLiteral:
3497 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3498 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3499 break;
3500
3501 case FK_AddressOfOverloadFailed:
3502 S.ResolveAddressOfOverloadedFunction(Args[0],
3503 DestType.getNonReferenceType(),
3504 true);
3505 break;
3506
3507 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003508 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003509 switch (FailedOverloadResult) {
3510 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003511 if (Failure == FK_UserConversionOverloadFailed)
3512 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3513 << Args[0]->getType() << DestType
3514 << Args[0]->getSourceRange();
3515 else
3516 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3517 << DestType << Args[0]->getType()
3518 << Args[0]->getSourceRange();
3519
Douglas Gregor20093b42009-12-09 23:02:17 +00003520 S.PrintOverloadCandidates(FailedCandidateSet, true);
3521 break;
3522
3523 case OR_No_Viable_Function:
3524 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3525 << Args[0]->getType() << DestType.getNonReferenceType()
3526 << Args[0]->getSourceRange();
3527 S.PrintOverloadCandidates(FailedCandidateSet, false);
3528 break;
3529
3530 case OR_Deleted: {
3531 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3532 << Args[0]->getType() << DestType.getNonReferenceType()
3533 << Args[0]->getSourceRange();
3534 OverloadCandidateSet::iterator Best;
3535 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3536 Kind.getLocation(),
3537 Best);
3538 if (Ovl == OR_Deleted) {
3539 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3540 << Best->Function->isDeleted();
3541 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003542 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003543 }
3544 break;
3545 }
3546
3547 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003548 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003549 break;
3550 }
3551 break;
3552
3553 case FK_NonConstLValueReferenceBindingToTemporary:
3554 case FK_NonConstLValueReferenceBindingToUnrelated:
3555 S.Diag(Kind.getLocation(),
3556 Failure == FK_NonConstLValueReferenceBindingToTemporary
3557 ? diag::err_lvalue_reference_bind_to_temporary
3558 : diag::err_lvalue_reference_bind_to_unrelated)
3559 << DestType.getNonReferenceType()
3560 << Args[0]->getType()
3561 << Args[0]->getSourceRange();
3562 break;
3563
3564 case FK_RValueReferenceBindingToLValue:
3565 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3566 << Args[0]->getSourceRange();
3567 break;
3568
3569 case FK_ReferenceInitDropsQualifiers:
3570 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3571 << DestType.getNonReferenceType()
3572 << Args[0]->getType()
3573 << Args[0]->getSourceRange();
3574 break;
3575
3576 case FK_ReferenceInitFailed:
3577 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3578 << DestType.getNonReferenceType()
3579 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3580 << Args[0]->getType()
3581 << Args[0]->getSourceRange();
3582 break;
3583
3584 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003585 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3586 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003587 << DestType
3588 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3589 << Args[0]->getType()
3590 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003591 break;
3592
3593 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003594 SourceRange R;
3595
3596 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3597 R = SourceRange(InitList->getInit(1)->getLocStart(),
3598 InitList->getLocEnd());
3599 else
3600 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003601
3602 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003603 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003604 break;
3605 }
3606
3607 case FK_ReferenceBindingToInitList:
3608 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3609 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3610 break;
3611
3612 case FK_InitListBadDestinationType:
3613 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3614 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3615 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003616
3617 case FK_ConstructorOverloadFailed: {
3618 SourceRange ArgsRange;
3619 if (NumArgs)
3620 ArgsRange = SourceRange(Args[0]->getLocStart(),
3621 Args[NumArgs - 1]->getLocEnd());
3622
3623 // FIXME: Using "DestType" for the entity we're printing is probably
3624 // bad.
3625 switch (FailedOverloadResult) {
3626 case OR_Ambiguous:
3627 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3628 << DestType << ArgsRange;
3629 S.PrintOverloadCandidates(FailedCandidateSet, true);
3630 break;
3631
3632 case OR_No_Viable_Function:
3633 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3634 << DestType << ArgsRange;
3635 S.PrintOverloadCandidates(FailedCandidateSet, false);
3636 break;
3637
3638 case OR_Deleted: {
3639 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3640 << true << DestType << ArgsRange;
3641 OverloadCandidateSet::iterator Best;
3642 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3643 Kind.getLocation(),
3644 Best);
3645 if (Ovl == OR_Deleted) {
3646 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3647 << Best->Function->isDeleted();
3648 } else {
3649 llvm_unreachable("Inconsistent overload resolution?");
3650 }
3651 break;
3652 }
3653
3654 case OR_Success:
3655 llvm_unreachable("Conversion did not fail!");
3656 break;
3657 }
3658 break;
3659 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003660
3661 case FK_DefaultInitOfConst:
3662 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3663 << DestType;
3664 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003665 }
3666
3667 return true;
3668}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003669
3670//===----------------------------------------------------------------------===//
3671// Initialization helper functions
3672//===----------------------------------------------------------------------===//
3673Sema::OwningExprResult
3674Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3675 SourceLocation EqualLoc,
3676 OwningExprResult Init) {
3677 if (Init.isInvalid())
3678 return ExprError();
3679
3680 Expr *InitE = (Expr *)Init.get();
3681 assert(InitE && "No initialization expression?");
3682
3683 if (EqualLoc.isInvalid())
3684 EqualLoc = InitE->getLocStart();
3685
3686 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3687 EqualLoc);
3688 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3689 Init.release();
3690 return Seq.Perform(*this, Entity, Kind,
3691 MultiExprArg(*this, (void**)&InitE, 1));
3692}