blob: 06f4ee63510dfe02a8901b41ee7b55aff28c3325 [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"
Douglas Gregorc171e3b2010-01-01 00:03:05 +000019#include "Lookup.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000020#include "Sema.h"
Douglas Gregor05c13a32009-01-22 00:58:24 +000021#include "clang/Parse/Designator.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000022#include "clang/AST/ASTContext.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
Chris Lattner79e079d2009-02-24 23:10:27 +000034static Expr *IsStringInit(Expr *Init, QualType DeclType, ASTContext &Context) {
Chris Lattner8879e3b2009-02-26 23:26:43 +000035 const ArrayType *AT = Context.getAsArrayType(DeclType);
36 if (!AT) return 0;
37
Eli Friedman8718a6a2009-05-29 18:22:49 +000038 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
39 return 0;
40
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // See if this is a string literal or @encode.
42 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner8879e3b2009-02-26 23:26:43 +000044 // Handle @encode, which is a narrow string.
45 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
46 return Init;
47
48 // Otherwise we can only handle string literals.
49 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000050 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000051
52 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Chris Lattner8879e3b2009-02-26 23:26:43 +000053 // char array can be initialized with a narrow string.
54 // Only allow char x[] = "foo"; not char x[] = L"foo";
55 if (!SL->isWide())
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Chris Lattner8879e3b2009-02-26 23:26:43 +000057
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
59 // correction from DR343): "An array with element type compatible with a
60 // qualified or unqualified version of wchar_t may be initialized by a wide
61 // string literal, optionally enclosed in braces."
62 if (Context.typesAreCompatible(Context.getWCharType(),
63 ElemTy.getUnqualifiedType()))
Chris Lattner8879e3b2009-02-26 23:26:43 +000064 return Init;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattnerdd8e0062009-02-24 22:27:37 +000066 return 0;
67}
68
Anders Carlssonc07b8c02010-01-23 18:35:41 +000069static Sema::OwningExprResult
70CheckSingleInitializer(const InitializedEntity *Entity,
71 Sema::OwningExprResult Init, QualType DeclType, Sema &S){
72 Expr *InitExpr = Init.takeAs<Expr>();
73
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074 // Get the type before calling CheckSingleAssignmentConstraints(), since
75 // it can promote the expression.
Anders Carlssonc07b8c02010-01-23 18:35:41 +000076 QualType InitType = InitExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +000077
Chris Lattner95e8d652009-02-24 22:46:58 +000078 if (S.getLangOptions().CPlusPlus) {
Anders Carlsson1f243502010-01-23 19:22:30 +000079 if (Entity) {
80 assert(Entity->getType() == DeclType);
81
82 // C++ [dcl.init.aggr]p2:
83 // Each member is copy-initialized from the corresponding
84 // initializer-clause
85 Sema::OwningExprResult Result =
86 S.PerformCopyInitialization(*Entity, InitExpr->getLocStart(),
87 S.Owned(InitExpr));
88
89 return move(Result);
90 } else {
91 // FIXME: I dislike this error message. A lot.
92 if (S.PerformImplicitConversion(InitExpr, DeclType,
93 Sema::AA_Initializing,
94 /*DirectInit=*/false)) {
95 ImplicitConversionSequence ICS;
96 OverloadCandidateSet CandidateSet;
97 if (S.IsUserDefinedConversion(InitExpr, DeclType, ICS.UserDefined,
98 CandidateSet,
99 true, false, false) != OR_Ambiguous) {
100 S.Diag(InitExpr->getSourceRange().getBegin(),
101 diag::err_typecheck_convert_incompatible)
102 << DeclType << InitExpr->getType()
103 << Sema::AA_Initializing
104 << InitExpr->getSourceRange();
105 return S.ExprError();
106 }
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000107 S.Diag(InitExpr->getSourceRange().getBegin(),
Anders Carlsson1f243502010-01-23 19:22:30 +0000108 diag::err_typecheck_convert_ambiguous)
109 << DeclType << InitExpr->getType() << InitExpr->getSourceRange();
110 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
111 &InitExpr, 1);
112
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000113 return S.ExprError();
114 }
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000115
Anders Carlsson1f243502010-01-23 19:22:30 +0000116 Init.release();
117 return S.Owned(InitExpr);
118 }
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattner95e8d652009-02-24 22:46:58 +0000121 Sema::AssignConvertType ConvTy =
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000122 S.CheckSingleAssignmentConstraints(DeclType, InitExpr);
123 if (S.DiagnoseAssignmentResult(ConvTy, InitExpr->getLocStart(), DeclType,
124 InitType, InitExpr, Sema::AA_Initializing))
125 return S.ExprError();
126
127 Init.release();
128 return S.Owned(InitExpr);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000129}
130
Chris Lattner79e079d2009-02-24 23:10:27 +0000131static void CheckStringInit(Expr *Str, QualType &DeclT, Sema &S) {
132 // Get the length of the string as parsed.
133 uint64_t StrLength =
134 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
135
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Chris Lattner79e079d2009-02-24 23:10:27 +0000137 const ArrayType *AT = S.Context.getAsArrayType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000138 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000139 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000140 // being initialized to a string literal.
141 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000142 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000143 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +0000144 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
145 ConstVal,
146 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000147 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000148 }
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Eli Friedman8718a6a2009-05-29 18:22:49 +0000150 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Eli Friedman8718a6a2009-05-29 18:22:49 +0000152 // C99 6.7.8p14. We have an array of character type with known size. However,
153 // the size may be smaller or larger than the string we are initializing.
154 // FIXME: Avoid truncation for 64-bit length strings.
155 if (StrLength-1 > CAT->getSize().getZExtValue())
156 S.Diag(Str->getSourceRange().getBegin(),
157 diag::warn_initializer_string_for_char_array_too_long)
158 << Str->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Eli Friedman8718a6a2009-05-29 18:22:49 +0000160 // Set the type to the actual size that we are initializing. If we have
161 // something like:
162 // char x[1] = "foo";
163 // then this will set the string literal's type to char[1].
164 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000165}
166
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000167//===----------------------------------------------------------------------===//
168// Semantic checking for initializer lists.
169//===----------------------------------------------------------------------===//
170
Douglas Gregor9e80f722009-01-29 01:05:33 +0000171/// @brief Semantic checking for initializer lists.
172///
173/// The InitListChecker class contains a set of routines that each
174/// handle the initialization of a certain kind of entity, e.g.,
175/// arrays, vectors, struct/union types, scalars, etc. The
176/// InitListChecker itself performs a recursive walk of the subobject
177/// structure of the type to be initialized, while stepping through
178/// the initializer list one element at a time. The IList and Index
179/// parameters to each of the Check* routines contain the active
180/// (syntactic) initializer list and the index into that initializer
181/// list that represents the current initializer. Each routine is
182/// responsible for moving that Index forward as it consumes elements.
183///
184/// Each Check* routine also has a StructuredList/StructuredIndex
185/// arguments, which contains the current the "structured" (semantic)
186/// initializer list and the index into that initializer list where we
187/// are copying initializers as we map them over to the semantic
188/// list. Once we have completed our recursive walk of the subobject
189/// structure, we will have constructed a full semantic initializer
190/// list.
191///
192/// C99 designators cause changes in the initializer list traversal,
193/// because they make the initialization "jump" into a specific
194/// subobject and then continue the initialization from that
195/// point. CheckDesignatedInitializer() recursively steps into the
196/// designated subobject and manages backing out the recursion to
197/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000198namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000199class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000200 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000201 bool hadError;
202 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
203 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000204
205 void CheckImplicitInitList(InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000206 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000207 unsigned &StructuredIndex,
208 bool TopLevelObject = false);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000209 void CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000210 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000211 unsigned &StructuredIndex,
212 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000213 void CheckListElementTypes(InitListExpr *IList, QualType &DeclType,
214 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000215 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000217 unsigned &StructuredIndex,
218 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000219 void CheckSubElementType(InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000220 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000221 InitListExpr *StructuredList,
222 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000223 void CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000224 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000225 InitListExpr *StructuredList,
226 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000227 void CheckReferenceType(InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000228 unsigned &Index,
229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000231 void CheckVectorType(InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000232 InitListExpr *StructuredList,
233 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000234 void CheckStructUnionTypes(InitListExpr *IList, QualType DeclType,
235 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000237 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000238 unsigned &StructuredIndex,
239 bool TopLevelObject = false);
Mike Stump1eb44332009-09-09 15:08:12 +0000240 void CheckArrayType(InitListExpr *IList, QualType &DeclType,
241 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000243 InitListExpr *StructuredList,
244 unsigned &StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +0000245 bool CheckDesignatedInitializer(InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000246 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000247 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000248 RecordDecl::field_iterator *NextField,
249 llvm::APSInt *NextElementIndex,
250 unsigned &Index,
251 InitListExpr *StructuredList,
252 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000253 bool FinishSubobjectInit,
254 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000255 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
256 QualType CurrentObjectType,
257 InitListExpr *StructuredList,
258 unsigned StructuredIndex,
259 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000260 void UpdateStructuredListElement(InitListExpr *StructuredList,
261 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000262 Expr *expr);
263 int numArrayElements(QualType DeclType);
264 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000265
Douglas Gregord6d37de2009-12-22 00:05:34 +0000266 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
267 const InitializedEntity &ParentEntity,
268 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000269 void FillInValueInitializations(const InitializedEntity &Entity,
270 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000271public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000272 InitListChecker(Sema &S, const InitializedEntity &Entity,
273 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000274 bool HadError() { return hadError; }
275
276 // @brief Retrieves the fully-structured initializer list used for
277 // semantic analysis and code generation.
278 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
279};
Chris Lattner8b419b92009-02-24 22:48:58 +0000280} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000281
Douglas Gregord6d37de2009-12-22 00:05:34 +0000282void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
283 const InitializedEntity &ParentEntity,
284 InitListExpr *ILE,
285 bool &RequiresSecondPass) {
286 SourceLocation Loc = ILE->getSourceRange().getBegin();
287 unsigned NumInits = ILE->getNumInits();
288 InitializedEntity MemberEntity
289 = InitializedEntity::InitializeMember(Field, &ParentEntity);
290 if (Init >= NumInits || !ILE->getInit(Init)) {
291 // FIXME: We probably don't need to handle references
292 // specially here, since value-initialization of references is
293 // handled in InitializationSequence.
294 if (Field->getType()->isReferenceType()) {
295 // C++ [dcl.init.aggr]p9:
296 // If an incomplete or empty initializer-list leaves a
297 // member of reference type uninitialized, the program is
298 // ill-formed.
299 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
300 << Field->getType()
301 << ILE->getSyntacticForm()->getSourceRange();
302 SemaRef.Diag(Field->getLocation(),
303 diag::note_uninit_reference_member);
304 hadError = true;
305 return;
306 }
307
308 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
309 true);
310 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
311 if (!InitSeq) {
312 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
313 hadError = true;
314 return;
315 }
316
317 Sema::OwningExprResult MemberInit
318 = InitSeq.Perform(SemaRef, MemberEntity, Kind,
319 Sema::MultiExprArg(SemaRef, 0, 0));
320 if (MemberInit.isInvalid()) {
321 hadError = true;
322 return;
323 }
324
325 if (hadError) {
326 // Do nothing
327 } else if (Init < NumInits) {
328 ILE->setInit(Init, MemberInit.takeAs<Expr>());
329 } else if (InitSeq.getKind()
330 == InitializationSequence::ConstructorInitialization) {
331 // Value-initialization requires a constructor call, so
332 // extend the initializer list to include the constructor
333 // call and make a note that we'll need to take another pass
334 // through the initializer list.
335 ILE->updateInit(Init, MemberInit.takeAs<Expr>());
336 RequiresSecondPass = true;
337 }
338 } else if (InitListExpr *InnerILE
339 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
340 FillInValueInitializations(MemberEntity, InnerILE,
341 RequiresSecondPass);
342}
343
Douglas Gregor4c678342009-01-28 21:54:33 +0000344/// Recursively replaces NULL values within the given initializer list
345/// with expressions that perform value-initialization of the
346/// appropriate type.
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000347void
348InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
349 InitListExpr *ILE,
350 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000351 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000352 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000353 SourceLocation Loc = ILE->getSourceRange().getBegin();
354 if (ILE->getSyntacticForm())
355 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Ted Kremenek6217b802009-07-29 21:53:49 +0000357 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000358 if (RType->getDecl()->isUnion() &&
359 ILE->getInitializedFieldInUnion())
360 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
361 Entity, ILE, RequiresSecondPass);
362 else {
363 unsigned Init = 0;
364 for (RecordDecl::field_iterator
365 Field = RType->getDecl()->field_begin(),
366 FieldEnd = RType->getDecl()->field_end();
367 Field != FieldEnd; ++Field) {
368 if (Field->isUnnamedBitfield())
369 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000370
Douglas Gregord6d37de2009-12-22 00:05:34 +0000371 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000372 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000373
374 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
375 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000376 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000377
Douglas Gregord6d37de2009-12-22 00:05:34 +0000378 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000379
Douglas Gregord6d37de2009-12-22 00:05:34 +0000380 // Only look at the first initialization of a union.
381 if (RType->getDecl()->isUnion())
382 break;
383 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000384 }
385
386 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000387 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000388
389 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000391 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000392 unsigned NumInits = ILE->getNumInits();
393 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000394 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000395 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000396 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
397 NumElements = CAType->getSize().getZExtValue();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000398 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
399 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000400 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000401 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000402 NumElements = VType->getNumElements();
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000403 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
404 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000405 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000406 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000408
Douglas Gregor87fd7032009-02-02 17:43:21 +0000409 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000410 if (hadError)
411 return;
412
Anders Carlssond3d824d2010-01-23 04:34:47 +0000413 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
414 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000415 ElementEntity.setElementIndex(Init);
416
Douglas Gregor87fd7032009-02-02 17:43:21 +0000417 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
419 true);
420 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
421 if (!InitSeq) {
422 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000423 hadError = true;
424 return;
425 }
426
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000427 Sema::OwningExprResult ElementInit
428 = InitSeq.Perform(SemaRef, ElementEntity, Kind,
429 Sema::MultiExprArg(SemaRef, 0, 0));
430 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000431 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000432 return;
433 }
434
435 if (hadError) {
436 // Do nothing
437 } else if (Init < NumInits) {
438 ILE->setInit(Init, ElementInit.takeAs<Expr>());
439 } else if (InitSeq.getKind()
440 == InitializationSequence::ConstructorInitialization) {
441 // Value-initialization requires a constructor call, so
442 // extend the initializer list to include the constructor
443 // call and make a note that we'll need to take another pass
444 // through the initializer list.
445 ILE->updateInit(Init, ElementInit.takeAs<Expr>());
446 RequiresSecondPass = true;
447 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000448 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000449 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
450 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000451 }
452}
453
Chris Lattner68355a52009-01-29 05:10:57 +0000454
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000455InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
456 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000457 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000458 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000459
Eli Friedmanb85f7072008-05-19 19:16:24 +0000460 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000461 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000462 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000463 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000464 CheckExplicitInitList(IL, T, newIndex, FullyStructuredList, newStructuredIndex,
465 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000466
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000467 if (!hadError) {
468 bool RequiresSecondPass = false;
469 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000470 if (RequiresSecondPass && !hadError)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000471 FillInValueInitializations(Entity, FullyStructuredList,
472 RequiresSecondPass);
473 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000474}
475
476int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000477 // FIXME: use a proper constant
478 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000479 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000480 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000481 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
482 }
483 return maxElements;
484}
485
486int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000487 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000488 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000489 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000490 Field = structDecl->field_begin(),
491 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000492 Field != FieldEnd; ++Field) {
493 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
494 ++InitializableMembers;
495 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000496 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000497 return std::min(InitializableMembers, 1);
498 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000499}
500
Mike Stump1eb44332009-09-09 15:08:12 +0000501void InitListChecker::CheckImplicitInitList(InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000502 QualType T, unsigned &Index,
503 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000504 unsigned &StructuredIndex,
505 bool TopLevelObject) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000506 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Steve Naroff0cca7492008-05-01 22:18:59 +0000508 if (T->isArrayType())
509 maxElements = numArrayElements(T);
510 else if (T->isStructureType() || T->isUnionType())
511 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000512 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000513 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000514 else
515 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000516
Eli Friedman402256f2008-05-25 13:49:22 +0000517 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000518 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000519 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000520 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000521 hadError = true;
522 return;
523 }
524
Douglas Gregor4c678342009-01-28 21:54:33 +0000525 // Build a structured initializer list corresponding to this subobject.
526 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000527 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
528 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000529 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
530 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000531 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000532
Douglas Gregor4c678342009-01-28 21:54:33 +0000533 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000534 unsigned StartIndex = Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000535 CheckListElementTypes(ParentIList, T, false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000536 StructuredSubobjectInitList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000537 StructuredSubobjectInitIndex,
538 TopLevelObject);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000539 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000540 StructuredSubobjectInitList->setType(T);
541
Douglas Gregored8a93d2009-03-01 17:12:46 +0000542 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000543 // range corresponds with the end of the last initializer it used.
544 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000545 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000546 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
547 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
548 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000549}
550
Steve Naroffa647caa2008-05-06 00:23:44 +0000551void InitListChecker::CheckExplicitInitList(InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000552 unsigned &Index,
553 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000554 unsigned &StructuredIndex,
555 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000556 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000557 SyntacticToSemantic[IList] = StructuredList;
558 StructuredList->setSyntacticForm(IList);
Mike Stump1eb44332009-09-09 15:08:12 +0000559 CheckListElementTypes(IList, T, true, Index, StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000560 StructuredIndex, TopLevelObject);
Steve Naroffa647caa2008-05-06 00:23:44 +0000561 IList->setType(T);
Douglas Gregor4c678342009-01-28 21:54:33 +0000562 StructuredList->setType(T);
Eli Friedman638e1442008-05-25 13:22:35 +0000563 if (hadError)
564 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000565
Eli Friedman638e1442008-05-25 13:22:35 +0000566 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000567 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000568 if (StructuredIndex == 1 &&
569 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000570 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000571 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000572 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000573 hadError = true;
574 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000575 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000576 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000577 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000578 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000579 // Don't complain for incomplete types, since we'll get an error
580 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000581 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000582 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000583 CurrentObjectType->isArrayType()? 0 :
584 CurrentObjectType->isVectorType()? 1 :
585 CurrentObjectType->isScalarType()? 2 :
586 CurrentObjectType->isUnionType()? 3 :
587 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000588
589 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000590 if (SemaRef.getLangOptions().CPlusPlus) {
591 DK = diag::err_excess_initializers;
592 hadError = true;
593 }
Nate Begeman08634522009-07-07 21:53:06 +0000594 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
595 DK = diag::err_excess_initializers;
596 hadError = true;
597 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000598
Chris Lattner08202542009-02-24 22:50:46 +0000599 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000600 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000601 }
602 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000603
Eli Friedman759f2522009-05-16 11:45:48 +0000604 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000605 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000606 << IList->getSourceRange()
Chris Lattner29d9c1a2009-12-06 17:36:05 +0000607 << CodeModificationHint::CreateRemoval(IList->getLocStart())
608 << CodeModificationHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000609}
610
Eli Friedmanb85f7072008-05-19 19:16:24 +0000611void InitListChecker::CheckListElementTypes(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000612 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000613 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000614 unsigned &Index,
615 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000616 unsigned &StructuredIndex,
617 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000618 if (DeclType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000619 CheckScalarType(IList, DeclType, Index, StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000620 } else if (DeclType->isVectorType()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000621 CheckVectorType(IList, DeclType, Index, StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000622 } else if (DeclType->isAggregateType()) {
623 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000624 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000625 CheckStructUnionTypes(IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000626 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000627 StructuredList, StructuredIndex,
628 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000629 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000630 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000631 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000632 false);
Douglas Gregor4c678342009-01-28 21:54:33 +0000633 CheckArrayType(IList, DeclType, Zero, SubobjectIsDesignatorContext, Index,
634 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000635 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000636 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000637 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
638 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000639 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000640 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000641 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000642 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000643 } else if (DeclType->isRecordType()) {
644 // C++ [dcl.init]p14:
645 // [...] If the class is an aggregate (8.5.1), and the initializer
646 // is a brace-enclosed list, see 8.5.1.
647 //
648 // Note: 8.5.1 is handled below; here, we diagnose the case where
649 // we have an initializer list and a destination type that is not
650 // an aggregate.
651 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000652 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000653 << DeclType << IList->getSourceRange();
654 hadError = true;
655 } else if (DeclType->isReferenceType()) {
656 CheckReferenceType(IList, DeclType, Index, StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000657 } else {
658 // In C, all types are either scalars or aggregates, but
Mike Stump1eb44332009-09-09 15:08:12 +0000659 // additional handling is needed here for C++ (and possibly others?).
Steve Naroff0cca7492008-05-01 22:18:59 +0000660 assert(0 && "Unsupported initializer type");
661 }
662}
663
Eli Friedmanb85f7072008-05-19 19:16:24 +0000664void InitListChecker::CheckSubElementType(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000665 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000666 unsigned &Index,
667 InitListExpr *StructuredList,
668 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000669 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000670 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
671 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000672 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000673 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000674 = getStructuredSubobjectInit(IList, Index, ElemType,
675 StructuredList, StructuredIndex,
676 SubInitList->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +0000677 CheckExplicitInitList(SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000678 newStructuredList, newStructuredIndex);
679 ++StructuredIndex;
680 ++Index;
Chris Lattner79e079d2009-02-24 23:10:27 +0000681 } else if (Expr *Str = IsStringInit(expr, ElemType, SemaRef.Context)) {
682 CheckStringInit(Str, ElemType, SemaRef);
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000683 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor4c678342009-01-28 21:54:33 +0000684 ++Index;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000685 } else if (ElemType->isScalarType()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000686 CheckScalarType(IList, ElemType, Index, StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000687 } else if (ElemType->isReferenceType()) {
688 CheckReferenceType(IList, ElemType, Index, StructuredList, StructuredIndex);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000689 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000690 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000691 // C++ [dcl.init.aggr]p12:
692 // All implicit type conversions (clause 4) are considered when
693 // initializing the aggregate member with an ini- tializer from
694 // an initializer-list. If the initializer can initialize a
695 // member, the member is initialized. [...]
Mike Stump1eb44332009-09-09 15:08:12 +0000696 ImplicitConversionSequence ICS
Anders Carlssond28b4282009-08-27 17:18:13 +0000697 = SemaRef.TryCopyInitialization(expr, ElemType,
698 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +0000699 /*ForceRValue=*/false,
700 /*InOverloadResolution=*/false);
Anders Carlssond28b4282009-08-27 17:18:13 +0000701
John McCall1d318332010-01-12 00:44:57 +0000702 if (!ICS.isBad()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000703 if (SemaRef.PerformImplicitConversion(expr, ElemType, ICS,
Douglas Gregor68647482009-12-16 03:45:30 +0000704 Sema::AA_Initializing))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000705 hadError = true;
706 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
707 ++Index;
708 return;
709 }
710
711 // Fall through for subaggregate initialization
712 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000713 // C99 6.7.8p13:
Douglas Gregor930d8b52009-01-30 22:09:00 +0000714 //
715 // The initializer for a structure or union object that has
716 // automatic storage duration shall be either an initializer
717 // list as described below, or a single expression that has
718 // compatible structure or union type. In the latter case, the
719 // initial value of the object, including unnamed members, is
720 // that of the expression.
Eli Friedman6b5374f2009-06-13 10:38:46 +0000721 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Eli Friedman8718a6a2009-05-29 18:22:49 +0000722 SemaRef.Context.hasSameUnqualifiedType(expr->getType(), ElemType)) {
Douglas Gregor930d8b52009-01-30 22:09:00 +0000723 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
724 ++Index;
725 return;
726 }
727
728 // Fall through for subaggregate initialization
729 }
730
731 // C++ [dcl.init.aggr]p12:
Mike Stump1eb44332009-09-09 15:08:12 +0000732 //
Douglas Gregor930d8b52009-01-30 22:09:00 +0000733 // [...] Otherwise, if the member is itself a non-empty
734 // subaggregate, brace elision is assumed and the initializer is
735 // considered for the initialization of the first member of
736 // the subaggregate.
737 if (ElemType->isAggregateType() || ElemType->isVectorType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000738 CheckImplicitInitList(IList, ElemType, Index, StructuredList,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000739 StructuredIndex);
740 ++StructuredIndex;
741 } else {
742 // We cannot initialize this element, so let
743 // PerformCopyInitialization produce the appropriate diagnostic.
Douglas Gregor68647482009-12-16 03:45:30 +0000744 SemaRef.PerformCopyInitialization(expr, ElemType, Sema::AA_Initializing);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000745 hadError = true;
746 ++Index;
747 ++StructuredIndex;
748 }
749 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000750}
751
Douglas Gregor930d8b52009-01-30 22:09:00 +0000752void InitListChecker::CheckScalarType(InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000753 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000754 InitListExpr *StructuredList,
755 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000756 if (Index < IList->getNumInits()) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000757 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000758 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000759 SemaRef.Diag(IList->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000760 diag::err_many_braces_around_scalar_init)
761 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000762 hadError = true;
763 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000764 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000765 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000766 } else if (isa<DesignatedInitExpr>(expr)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000767 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor05c13a32009-01-22 00:58:24 +0000768 diag::err_designator_for_scalar_init)
769 << DeclType << expr->getSourceRange();
770 hadError = true;
771 ++Index;
Douglas Gregor4c678342009-01-28 21:54:33 +0000772 ++StructuredIndex;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000773 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000774 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000775
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000776 Sema::OwningExprResult Result =
777 CheckSingleInitializer(0, SemaRef.Owned(expr), DeclType, SemaRef);
778
779 Expr *ResultExpr;
780
781 if (Result.isInvalid())
Eli Friedmanbb504d32008-05-19 20:12:18 +0000782 hadError = true; // types weren't compatible.
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000783 else {
784 ResultExpr = Result.takeAs<Expr>();
785
786 if (ResultExpr != expr) {
787 // The type was promoted, update initializer list.
788 IList->setInit(Index, ResultExpr);
789 }
Douglas Gregor05c13a32009-01-22 00:58:24 +0000790 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000791 if (hadError)
792 ++StructuredIndex;
793 else
Anders Carlssonc07b8c02010-01-23 18:35:41 +0000794 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
Steve Naroff0cca7492008-05-01 22:18:59 +0000795 ++Index;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000796 } else {
Chris Lattner08202542009-02-24 22:50:46 +0000797 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000798 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000799 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000800 ++Index;
801 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000802 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000803 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000804}
805
Douglas Gregor930d8b52009-01-30 22:09:00 +0000806void InitListChecker::CheckReferenceType(InitListExpr *IList, QualType DeclType,
807 unsigned &Index,
808 InitListExpr *StructuredList,
809 unsigned &StructuredIndex) {
810 if (Index < IList->getNumInits()) {
811 Expr *expr = IList->getInit(Index);
812 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000813 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000814 << DeclType << IList->getSourceRange();
815 hadError = true;
816 ++Index;
817 ++StructuredIndex;
818 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000819 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000820
821 Expr *savExpr = expr; // Might be promoted by CheckSingleInitializer.
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000822 if (SemaRef.CheckReferenceInit(expr, DeclType,
Douglas Gregor739d8282009-09-23 23:04:10 +0000823 /*FIXME:*/expr->getLocStart(),
Anders Carlsson2de3ace2009-08-27 17:30:43 +0000824 /*SuppressUserConversions=*/false,
825 /*AllowExplicit=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +0000826 /*ForceRValue=*/false))
Douglas Gregor930d8b52009-01-30 22:09:00 +0000827 hadError = true;
828 else if (savExpr != expr) {
829 // The type was promoted, update initializer list.
830 IList->setInit(Index, expr);
831 }
832 if (hadError)
833 ++StructuredIndex;
834 else
835 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
836 ++Index;
837 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000838 // FIXME: It would be wonderful if we could point at the actual member. In
839 // general, it would be useful to pass location information down the stack,
840 // so that we know the location (or decl) of the "current object" being
841 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000842 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000843 diag::err_init_reference_member_uninitialized)
844 << DeclType
845 << IList->getSourceRange();
846 hadError = true;
847 ++Index;
848 ++StructuredIndex;
849 return;
850 }
851}
852
Mike Stump1eb44332009-09-09 15:08:12 +0000853void InitListChecker::CheckVectorType(InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000854 unsigned &Index,
855 InitListExpr *StructuredList,
856 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000857 if (Index < IList->getNumInits()) {
John McCall183700f2009-09-21 23:43:11 +0000858 const VectorType *VT = DeclType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000859 unsigned maxElements = VT->getNumElements();
860 unsigned numEltsInit = 0;
Steve Naroff0cca7492008-05-01 22:18:59 +0000861 QualType elementType = VT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Nate Begeman2ef13e52009-08-10 23:49:36 +0000863 if (!SemaRef.getLangOptions().OpenCL) {
864 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
865 // Don't attempt to go past the end of the init list
866 if (Index >= IList->getNumInits())
867 break;
868 CheckSubElementType(IList, elementType, Index,
869 StructuredList, StructuredIndex);
870 }
871 } else {
872 // OpenCL initializers allows vectors to be constructed from vectors.
873 for (unsigned i = 0; i < maxElements; ++i) {
874 // Don't attempt to go past the end of the init list
875 if (Index >= IList->getNumInits())
876 break;
877 QualType IType = IList->getInit(Index)->getType();
878 if (!IType->isVectorType()) {
879 CheckSubElementType(IList, elementType, Index,
880 StructuredList, StructuredIndex);
881 ++numEltsInit;
882 } else {
John McCall183700f2009-09-21 23:43:11 +0000883 const VectorType *IVT = IType->getAs<VectorType>();
Nate Begeman2ef13e52009-08-10 23:49:36 +0000884 unsigned numIElts = IVT->getNumElements();
885 QualType VecType = SemaRef.Context.getExtVectorType(elementType,
886 numIElts);
887 CheckSubElementType(IList, VecType, Index,
888 StructuredList, StructuredIndex);
889 numEltsInit += numIElts;
890 }
891 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000892 }
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Nate Begeman2ef13e52009-08-10 23:49:36 +0000894 // OpenCL & AltiVec require all elements to be initialized.
895 if (numEltsInit != maxElements)
896 if (SemaRef.getLangOptions().OpenCL || SemaRef.getLangOptions().AltiVec)
897 SemaRef.Diag(IList->getSourceRange().getBegin(),
898 diag::err_vector_incorrect_num_initializers)
899 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +0000900 }
901}
902
Mike Stump1eb44332009-09-09 15:08:12 +0000903void InitListChecker::CheckArrayType(InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000904 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +0000905 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000906 unsigned &Index,
907 InitListExpr *StructuredList,
908 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000909 // Check for the special-case of initializing an array with a string.
910 if (Index < IList->getNumInits()) {
Chris Lattner79e079d2009-02-24 23:10:27 +0000911 if (Expr *Str = IsStringInit(IList->getInit(Index), DeclType,
912 SemaRef.Context)) {
913 CheckStringInit(Str, DeclType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +0000914 // We place the string literal directly into the resulting
915 // initializer list. This is the only place where the structure
916 // of the structured initializer list doesn't match exactly,
917 // because doing so would involve allocating one character
918 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +0000919 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +0000920 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +0000921 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000922 return;
923 }
924 }
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000925 if (const VariableArrayType *VAT =
Chris Lattner08202542009-02-24 22:50:46 +0000926 SemaRef.Context.getAsVariableArrayType(DeclType)) {
Eli Friedman638e1442008-05-25 13:22:35 +0000927 // Check for VLAs; in standard C it would be possible to check this
928 // earlier, but I don't know where clang accepts VLAs (gcc accepts
929 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +0000930 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000931 diag::err_variable_object_no_init)
932 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +0000933 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000934 ++Index;
935 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +0000936 return;
937 }
938
Douglas Gregor05c13a32009-01-22 00:58:24 +0000939 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +0000940 llvm::APSInt maxElements(elementIndex.getBitWidth(),
941 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000942 bool maxElementsKnown = false;
943 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000944 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000945 maxElements = CAT->getSize();
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000946 elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000947 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +0000948 maxElementsKnown = true;
949 }
950
Chris Lattner08202542009-02-24 22:50:46 +0000951 QualType elementType = SemaRef.Context.getAsArrayType(DeclType)
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000952 ->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +0000953 while (Index < IList->getNumInits()) {
954 Expr *Init = IList->getInit(Index);
955 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000956 // If we're not the subobject that matches up with the '{' for
957 // the designator, we shouldn't be handling the
958 // designator. Return immediately.
959 if (!SubobjectIsDesignatorContext)
960 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000961
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000962 // Handle this designated initializer. elementIndex will be
963 // updated to be the next array element we'll initialize.
Mike Stump1eb44332009-09-09 15:08:12 +0000964 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +0000965 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000966 StructuredList, StructuredIndex, true,
967 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000968 hadError = true;
969 continue;
970 }
971
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000972 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
973 maxElements.extend(elementIndex.getBitWidth());
974 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
975 elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +0000976 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000977
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000978 // If the array is of incomplete type, keep track of the number of
979 // elements in the initializer.
980 if (!maxElementsKnown && elementIndex > maxElements)
981 maxElements = elementIndex;
982
Douglas Gregor05c13a32009-01-22 00:58:24 +0000983 continue;
984 }
985
986 // If we know the maximum number of elements, and we've already
987 // hit it, stop consuming elements in the initializer list.
988 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +0000989 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +0000990
991 // Check this element.
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000992 CheckSubElementType(IList, elementType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000993 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +0000994 ++elementIndex;
995
996 // If the array is of incomplete type, keep track of the number of
997 // elements in the initializer.
998 if (!maxElementsKnown && elementIndex > maxElements)
999 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001000 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001001 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001002 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001003 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001004 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001005 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001006 // Sizing an array implicitly to zero is not allowed by ISO C,
1007 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001008 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001009 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001010 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001011
Mike Stump1eb44332009-09-09 15:08:12 +00001012 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001013 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001014 }
1015}
1016
Mike Stump1eb44332009-09-09 15:08:12 +00001017void InitListChecker::CheckStructUnionTypes(InitListExpr *IList,
1018 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001019 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001020 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001021 unsigned &Index,
1022 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001023 unsigned &StructuredIndex,
1024 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001025 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Eli Friedmanb85f7072008-05-19 19:16:24 +00001027 // If the record is invalid, some of it's members are invalid. To avoid
1028 // confusion, we forgo checking the intializer for the entire record.
1029 if (structDecl->isInvalidDecl()) {
1030 hadError = true;
1031 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001032 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001033
1034 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1035 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001036 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001037 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001038 Field != FieldEnd; ++Field) {
1039 if (Field->getDeclName()) {
1040 StructuredList->setInitializedFieldInUnion(*Field);
1041 break;
1042 }
1043 }
1044 return;
1045 }
1046
Douglas Gregor05c13a32009-01-22 00:58:24 +00001047 // If structDecl is a forward declaration, this loop won't do
1048 // anything except look at designated initializers; That's okay,
1049 // because an error should get printed out elsewhere. It might be
1050 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001051 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001052 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001053 bool InitializedSomething = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001054 while (Index < IList->getNumInits()) {
1055 Expr *Init = IList->getInit(Index);
1056
1057 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001058 // If we're not the subobject that matches up with the '{' for
1059 // the designator, we shouldn't be handling the
1060 // designator. Return immediately.
1061 if (!SubobjectIsDesignatorContext)
1062 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001063
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001064 // Handle this designated initializer. Field will be updated to
1065 // the next field that we'll be initializing.
Mike Stump1eb44332009-09-09 15:08:12 +00001066 if (CheckDesignatedInitializer(IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001067 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001068 StructuredList, StructuredIndex,
1069 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001070 hadError = true;
1071
Douglas Gregordfb5e592009-02-12 19:00:39 +00001072 InitializedSomething = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001073 continue;
1074 }
1075
1076 if (Field == FieldEnd) {
1077 // We've run out of fields. We're done.
1078 break;
1079 }
1080
Douglas Gregordfb5e592009-02-12 19:00:39 +00001081 // We've already initialized a member of a union. We're done.
1082 if (InitializedSomething && DeclType->isUnionType())
1083 break;
1084
Douglas Gregor44b43212008-12-11 16:49:14 +00001085 // If we've hit the flexible array member at the end, we're done.
1086 if (Field->getType()->isIncompleteArrayType())
1087 break;
1088
Douglas Gregor0bb76892009-01-29 16:53:55 +00001089 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001090 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001091 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001092 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001093 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001094
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001095 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001096 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001097 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001098
1099 if (DeclType->isUnionType()) {
1100 // Initialize the first field within the union.
1101 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001102 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001103
1104 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001105 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001106
Mike Stump1eb44332009-09-09 15:08:12 +00001107 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001108 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001109 return;
1110
1111 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001112 if (!TopLevelObject &&
Douglas Gregora6457962009-03-20 00:32:56 +00001113 (!isa<InitListExpr>(IList->getInit(Index)) ||
1114 cast<InitListExpr>(IList->getInit(Index))->getNumInits() > 0)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001115 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001116 diag::err_flexible_array_init_nonempty)
1117 << IList->getInit(Index)->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001118 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001119 << *Field;
1120 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001121 ++Index;
1122 return;
1123 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001124 SemaRef.Diag(IList->getInit(Index)->getSourceRange().getBegin(),
Douglas Gregora6457962009-03-20 00:32:56 +00001125 diag::ext_flexible_array_init)
1126 << IList->getInit(Index)->getSourceRange().getBegin();
1127 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1128 << *Field;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001129 }
1130
Douglas Gregora6457962009-03-20 00:32:56 +00001131 if (isa<InitListExpr>(IList->getInit(Index)))
1132 CheckSubElementType(IList, Field->getType(), Index, StructuredList,
1133 StructuredIndex);
1134 else
1135 CheckImplicitInitList(IList, Field->getType(), Index, StructuredList,
1136 StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001137}
Steve Naroff0cca7492008-05-01 22:18:59 +00001138
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001139/// \brief Expand a field designator that refers to a member of an
1140/// anonymous struct or union into a series of field designators that
1141/// refers to the field within the appropriate subobject.
1142///
1143/// Field/FieldIndex will be updated to point to the (new)
1144/// currently-designated field.
1145static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001146 DesignatedInitExpr *DIE,
1147 unsigned DesigIdx,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001148 FieldDecl *Field,
1149 RecordDecl::field_iterator &FieldIter,
1150 unsigned &FieldIndex) {
1151 typedef DesignatedInitExpr::Designator Designator;
1152
1153 // Build the path from the current object to the member of the
1154 // anonymous struct/union (backwards).
1155 llvm::SmallVector<FieldDecl *, 4> Path;
1156 SemaRef.BuildAnonymousStructUnionMemberPath(Field, Path);
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001158 // Build the replacement designators.
1159 llvm::SmallVector<Designator, 4> Replacements;
1160 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
1161 FI = Path.rbegin(), FIEnd = Path.rend();
1162 FI != FIEnd; ++FI) {
1163 if (FI + 1 == FIEnd)
Mike Stump1eb44332009-09-09 15:08:12 +00001164 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001165 DIE->getDesignator(DesigIdx)->getDotLoc(),
1166 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1167 else
1168 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1169 SourceLocation()));
1170 Replacements.back().setField(*FI);
1171 }
1172
1173 // Expand the current designator into the set of replacement
1174 // designators, so we have a full subobject path down to where the
1175 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001176 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001177 &Replacements[0] + Replacements.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001179 // Update FieldIter/FieldIndex;
1180 RecordDecl *Record = cast<RecordDecl>(Path.back()->getDeclContext());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001181 FieldIter = Record->field_begin();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001182 FieldIndex = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001183 for (RecordDecl::field_iterator FEnd = Record->field_end();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001184 FieldIter != FEnd; ++FieldIter) {
1185 if (FieldIter->isUnnamedBitfield())
1186 continue;
1187
1188 if (*FieldIter == Path.back())
1189 return;
1190
1191 ++FieldIndex;
1192 }
1193
1194 assert(false && "Unable to find anonymous struct/union field");
1195}
1196
Douglas Gregor05c13a32009-01-22 00:58:24 +00001197/// @brief Check the well-formedness of a C99 designated initializer.
1198///
1199/// Determines whether the designated initializer @p DIE, which
1200/// resides at the given @p Index within the initializer list @p
1201/// IList, is well-formed for a current object of type @p DeclType
1202/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001203/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001204/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001205///
1206/// @param IList The initializer list in which this designated
1207/// initializer occurs.
1208///
Douglas Gregor71199712009-04-15 04:56:10 +00001209/// @param DIE The designated initializer expression.
1210///
1211/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001212///
1213/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1214/// into which the designation in @p DIE should refer.
1215///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001216/// @param NextField If non-NULL and the first designator in @p DIE is
1217/// a field, this will be set to the field declaration corresponding
1218/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001219///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001220/// @param NextElementIndex If non-NULL and the first designator in @p
1221/// DIE is an array designator or GNU array-range designator, this
1222/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001223///
1224/// @param Index Index into @p IList where the designated initializer
1225/// @p DIE occurs.
1226///
Douglas Gregor4c678342009-01-28 21:54:33 +00001227/// @param StructuredList The initializer list expression that
1228/// describes all of the subobject initializers in the order they'll
1229/// actually be initialized.
1230///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001231/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001232bool
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001233InitListChecker::CheckDesignatedInitializer(InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001234 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001235 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001236 QualType &CurrentObjectType,
1237 RecordDecl::field_iterator *NextField,
1238 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001239 unsigned &Index,
1240 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001241 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001242 bool FinishSubobjectInit,
1243 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001244 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001245 // Check the actual initialization for the designated object type.
1246 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001247
1248 // Temporarily remove the designator expression from the
1249 // initializer list that the child calls see, so that we don't try
1250 // to re-process the designator.
1251 unsigned OldIndex = Index;
1252 IList->setInit(OldIndex, DIE->getInit());
1253
1254 CheckSubElementType(IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001255 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001256
1257 // Restore the designated initializer expression in the syntactic
1258 // form of the initializer list.
1259 if (IList->getInit(OldIndex) != DIE->getInit())
1260 DIE->setInit(IList->getInit(OldIndex));
1261 IList->setInit(OldIndex, DIE);
1262
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001263 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001264 }
1265
Douglas Gregor71199712009-04-15 04:56:10 +00001266 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001267 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001268 "Need a non-designated initializer list to start from");
1269
Douglas Gregor71199712009-04-15 04:56:10 +00001270 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001271 // Determine the structural initializer list that corresponds to the
1272 // current subobject.
1273 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001274 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001275 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001276 SourceRange(D->getStartLocation(),
1277 DIE->getSourceRange().getEnd()));
1278 assert(StructuredList && "Expected a structured initializer list");
1279
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001280 if (D->isFieldDesignator()) {
1281 // C99 6.7.8p7:
1282 //
1283 // If a designator has the form
1284 //
1285 // . identifier
1286 //
1287 // then the current object (defined below) shall have
1288 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001289 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001290 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001291 if (!RT) {
1292 SourceLocation Loc = D->getDotLoc();
1293 if (Loc.isInvalid())
1294 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001295 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1296 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001297 ++Index;
1298 return true;
1299 }
1300
Douglas Gregor4c678342009-01-28 21:54:33 +00001301 // Note: we perform a linear search of the fields here, despite
1302 // the fact that we have a faster lookup method, because we always
1303 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001304 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001305 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001306 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001307 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001308 Field = RT->getDecl()->field_begin(),
1309 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001310 for (; Field != FieldEnd; ++Field) {
1311 if (Field->isUnnamedBitfield())
1312 continue;
1313
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001314 if (KnownField == *Field || Field->getIdentifier() == FieldName)
Douglas Gregor4c678342009-01-28 21:54:33 +00001315 break;
1316
1317 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001318 }
1319
Douglas Gregor4c678342009-01-28 21:54:33 +00001320 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001321 // There was no normal field in the struct with the designated
1322 // name. Perform another lookup for this name, which may find
1323 // something that we can't designate (e.g., a member function),
1324 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001325 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001326 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001327 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001328 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001329 // Name lookup didn't find anything. Determine whether this
1330 // was a typo for another field name.
1331 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
1332 Sema::LookupMemberName);
1333 if (SemaRef.CorrectTypo(R, /*Scope=*/0, /*SS=*/0, RT->getDecl()) &&
1334 (ReplacementField = R.getAsSingle<FieldDecl>()) &&
1335 ReplacementField->getDeclContext()->getLookupContext()
1336 ->Equals(RT->getDecl())) {
1337 SemaRef.Diag(D->getFieldLoc(),
1338 diag::err_field_designator_unknown_suggest)
1339 << FieldName << CurrentObjectType << R.getLookupName()
1340 << CodeModificationHint::CreateReplacement(D->getFieldLoc(),
1341 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00001342 SemaRef.Diag(ReplacementField->getLocation(),
1343 diag::note_previous_decl)
1344 << ReplacementField->getDeclName();
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001345 } else {
1346 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1347 << FieldName << CurrentObjectType;
1348 ++Index;
1349 return true;
1350 }
1351 } else if (!KnownField) {
1352 // Determine whether we found a field at all.
1353 ReplacementField = dyn_cast<FieldDecl>(*Lookup.first);
1354 }
1355
1356 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001357 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001358 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001359 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001360 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001361 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001362 ++Index;
1363 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001364 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001365
1366 if (!KnownField &&
1367 cast<RecordDecl>((ReplacementField)->getDeclContext())
1368 ->isAnonymousStructOrUnion()) {
1369 // Handle an field designator that refers to a member of an
1370 // anonymous struct or union.
1371 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx,
1372 ReplacementField,
1373 Field, FieldIndex);
1374 D = DIE->getDesignator(DesigIdx);
1375 } else if (!KnownField) {
1376 // The replacement field comes from typo correction; find it
1377 // in the list of fields.
1378 FieldIndex = 0;
1379 Field = RT->getDecl()->field_begin();
1380 for (; Field != FieldEnd; ++Field) {
1381 if (Field->isUnnamedBitfield())
1382 continue;
1383
1384 if (ReplacementField == *Field ||
1385 Field->getIdentifier() == ReplacementField->getIdentifier())
1386 break;
1387
1388 ++FieldIndex;
1389 }
1390 }
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001391 } else if (!KnownField &&
1392 cast<RecordDecl>((*Field)->getDeclContext())
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 ->isAnonymousStructOrUnion()) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001394 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, *Field,
1395 Field, FieldIndex);
1396 D = DIE->getDesignator(DesigIdx);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001397 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001398
1399 // All of the fields of a union are located at the same place in
1400 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001401 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001402 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001403 StructuredList->setInitializedFieldInUnion(*Field);
1404 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001405
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001406 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001407 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Douglas Gregor4c678342009-01-28 21:54:33 +00001409 // Make sure that our non-designated initializer list has space
1410 // for a subobject corresponding to this field.
1411 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001412 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001413
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001414 // This designator names a flexible array member.
1415 if (Field->getType()->isIncompleteArrayType()) {
1416 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001417 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001418 // We can't designate an object within the flexible array
1419 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001420 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001421 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001422 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001423 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001424 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001425 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001426 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001427 << *Field;
1428 Invalid = true;
1429 }
1430
1431 if (!hadError && !isa<InitListExpr>(DIE->getInit())) {
1432 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001433 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001434 diag::err_flexible_array_init_needs_braces)
1435 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001436 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001437 << *Field;
1438 Invalid = true;
1439 }
1440
1441 // Handle GNU flexible array initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001442 if (!Invalid && !TopLevelObject &&
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001443 cast<InitListExpr>(DIE->getInit())->getNumInits() > 0) {
Mike Stump1eb44332009-09-09 15:08:12 +00001444 SemaRef.Diag(DIE->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001445 diag::err_flexible_array_init_nonempty)
1446 << DIE->getSourceRange().getBegin();
Chris Lattner08202542009-02-24 22:50:46 +00001447 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001448 << *Field;
1449 Invalid = true;
1450 }
1451
1452 if (Invalid) {
1453 ++Index;
1454 return true;
1455 }
1456
1457 // Initialize the array.
1458 bool prevHadError = hadError;
1459 unsigned newStructuredIndex = FieldIndex;
1460 unsigned OldIndex = Index;
1461 IList->setInit(Index, DIE->getInit());
Mike Stump1eb44332009-09-09 15:08:12 +00001462 CheckSubElementType(IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001463 StructuredList, newStructuredIndex);
1464 IList->setInit(OldIndex, DIE);
1465 if (hadError && !prevHadError) {
1466 ++Field;
1467 ++FieldIndex;
1468 if (NextField)
1469 *NextField = Field;
1470 StructuredIndex = FieldIndex;
1471 return true;
1472 }
1473 } else {
1474 // Recurse to check later designated subobjects.
1475 QualType FieldType = (*Field)->getType();
1476 unsigned newStructuredIndex = FieldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001477 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, FieldType, 0, 0,
1478 Index, StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001479 true, false))
1480 return true;
1481 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001482
1483 // Find the position of the next field to be initialized in this
1484 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001485 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001486 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001487
1488 // If this the first designator, our caller will continue checking
1489 // the rest of this struct/class/union subobject.
1490 if (IsFirstDesignator) {
1491 if (NextField)
1492 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001493 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001494 return false;
1495 }
1496
Douglas Gregor34e79462009-01-28 23:36:17 +00001497 if (!FinishSubobjectInit)
1498 return false;
1499
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001500 // We've already initialized something in the union; we're done.
1501 if (RT->getDecl()->isUnion())
1502 return hadError;
1503
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001504 // Check the remaining fields within this class/struct/union subobject.
1505 bool prevHadError = hadError;
Douglas Gregor4c678342009-01-28 21:54:33 +00001506 CheckStructUnionTypes(IList, CurrentObjectType, Field, false, Index,
1507 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001508 return hadError && !prevHadError;
1509 }
1510
1511 // C99 6.7.8p6:
1512 //
1513 // If a designator has the form
1514 //
1515 // [ constant-expression ]
1516 //
1517 // then the current object (defined below) shall have array
1518 // type and the expression shall be an integer constant
1519 // expression. If the array is of unknown size, any
1520 // nonnegative value is valid.
1521 //
1522 // Additionally, cope with the GNU extension that permits
1523 // designators of the form
1524 //
1525 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001526 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001527 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001528 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001529 << CurrentObjectType;
1530 ++Index;
1531 return true;
1532 }
1533
1534 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001535 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1536 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001537 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001538 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001539 DesignatedEndIndex = DesignatedStartIndex;
1540 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001541 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001542
Mike Stump1eb44332009-09-09 15:08:12 +00001543
1544 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001545 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001546 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001547 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001548 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001549
Chris Lattner3bf68932009-04-25 21:59:05 +00001550 if (DesignatedStartIndex.getZExtValue() !=DesignatedEndIndex.getZExtValue())
Douglas Gregora9c87802009-01-29 19:42:23 +00001551 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001552 }
1553
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001554 if (isa<ConstantArrayType>(AT)) {
1555 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Douglas Gregor34e79462009-01-28 23:36:17 +00001556 DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
1557 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
1558 DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
1559 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1560 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001561 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001562 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001563 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001564 << IndexExpr->getSourceRange();
1565 ++Index;
1566 return true;
1567 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001568 } else {
1569 // Make sure the bit-widths and signedness match.
1570 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
1571 DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001572 else if (DesignatedStartIndex.getBitWidth() <
1573 DesignatedEndIndex.getBitWidth())
Douglas Gregor34e79462009-01-28 23:36:17 +00001574 DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
1575 DesignatedStartIndex.setIsUnsigned(true);
1576 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001577 }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Douglas Gregor4c678342009-01-28 21:54:33 +00001579 // Make sure that our non-designated initializer list has space
1580 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001581 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001582 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001583 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001584
Douglas Gregor34e79462009-01-28 23:36:17 +00001585 // Repeatedly perform subobject initializations in the range
1586 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001587
Douglas Gregor34e79462009-01-28 23:36:17 +00001588 // Move to the next designator
1589 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1590 unsigned OldIndex = Index;
Douglas Gregor34e79462009-01-28 23:36:17 +00001591 while (DesignatedStartIndex <= DesignatedEndIndex) {
1592 // Recurse to check later designated subobjects.
1593 QualType ElementType = AT->getElementType();
1594 Index = OldIndex;
Douglas Gregor71199712009-04-15 04:56:10 +00001595 if (CheckDesignatedInitializer(IList, DIE, DesigIdx + 1, ElementType, 0, 0,
1596 Index, StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001597 (DesignatedStartIndex == DesignatedEndIndex),
1598 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001599 return true;
1600
1601 // Move to the next index in the array that we'll be initializing.
1602 ++DesignatedStartIndex;
1603 ElementIndex = DesignatedStartIndex.getZExtValue();
1604 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001605
1606 // If this the first designator, our caller will continue checking
1607 // the rest of this array subobject.
1608 if (IsFirstDesignator) {
1609 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001610 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001611 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001612 return false;
1613 }
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Douglas Gregor34e79462009-01-28 23:36:17 +00001615 if (!FinishSubobjectInit)
1616 return false;
1617
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001618 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001619 bool prevHadError = hadError;
Douglas Gregorfdf55692009-02-09 19:45:19 +00001620 CheckArrayType(IList, CurrentObjectType, DesignatedStartIndex, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001621 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001622 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001623}
1624
Douglas Gregor4c678342009-01-28 21:54:33 +00001625// Get the structured initializer list for a subobject of type
1626// @p CurrentObjectType.
1627InitListExpr *
1628InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1629 QualType CurrentObjectType,
1630 InitListExpr *StructuredList,
1631 unsigned StructuredIndex,
1632 SourceRange InitRange) {
1633 Expr *ExistingInit = 0;
1634 if (!StructuredList)
1635 ExistingInit = SyntacticToSemantic[IList];
1636 else if (StructuredIndex < StructuredList->getNumInits())
1637 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001638
Douglas Gregor4c678342009-01-28 21:54:33 +00001639 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1640 return Result;
1641
1642 if (ExistingInit) {
1643 // We are creating an initializer list that initializes the
1644 // subobjects of the current object, but there was already an
1645 // initialization that completely initialized the current
1646 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001647 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001648 // struct X { int a, b; };
1649 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001650 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001651 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1652 // designated initializer re-initializes the whole
1653 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001654 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001655 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001656 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001657 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001658 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001659 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001660 << ExistingInit->getSourceRange();
1661 }
1662
Mike Stump1eb44332009-09-09 15:08:12 +00001663 InitListExpr *Result
1664 = new (SemaRef.Context) InitListExpr(InitRange.getBegin(), 0, 0,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001665 InitRange.getEnd());
1666
Douglas Gregor4c678342009-01-28 21:54:33 +00001667 Result->setType(CurrentObjectType);
1668
Douglas Gregorfa219202009-03-20 23:58:33 +00001669 // Pre-allocate storage for the structured initializer list.
1670 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001671 unsigned NumInits = 0;
1672 if (!StructuredList)
1673 NumInits = IList->getNumInits();
1674 else if (Index < IList->getNumInits()) {
1675 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index)))
1676 NumInits = SubList->getNumInits();
1677 }
1678
Mike Stump1eb44332009-09-09 15:08:12 +00001679 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001680 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1681 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1682 NumElements = CAType->getSize().getZExtValue();
1683 // Simple heuristic so that we don't allocate a very large
1684 // initializer with many empty entries at the end.
Douglas Gregor08457732009-03-21 18:13:52 +00001685 if (NumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001686 NumElements = 0;
1687 }
John McCall183700f2009-09-21 23:43:11 +00001688 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001689 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001690 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001691 RecordDecl *RDecl = RType->getDecl();
1692 if (RDecl->isUnion())
1693 NumElements = 1;
1694 else
Mike Stump1eb44332009-09-09 15:08:12 +00001695 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001696 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001697 }
1698
Douglas Gregor08457732009-03-21 18:13:52 +00001699 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001700 NumElements = IList->getNumInits();
1701
1702 Result->reserveInits(NumElements);
1703
Douglas Gregor4c678342009-01-28 21:54:33 +00001704 // Link this new initializer list into the structured initializer
1705 // lists.
1706 if (StructuredList)
1707 StructuredList->updateInit(StructuredIndex, Result);
1708 else {
1709 Result->setSyntacticForm(IList);
1710 SyntacticToSemantic[IList] = Result;
1711 }
1712
1713 return Result;
1714}
1715
1716/// Update the initializer at index @p StructuredIndex within the
1717/// structured initializer list to the value @p expr.
1718void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1719 unsigned &StructuredIndex,
1720 Expr *expr) {
1721 // No structured initializer list to update
1722 if (!StructuredList)
1723 return;
1724
1725 if (Expr *PrevInit = StructuredList->updateInit(StructuredIndex, expr)) {
1726 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001727 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001728 diag::warn_initializer_overrides)
1729 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001730 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001731 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001732 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001733 << PrevInit->getSourceRange();
1734 }
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Douglas Gregor4c678342009-01-28 21:54:33 +00001736 ++StructuredIndex;
1737}
1738
Douglas Gregor05c13a32009-01-22 00:58:24 +00001739/// Check that the given Index expression is a valid array designator
1740/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001741/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001742/// and produces a reasonable diagnostic if there is a
1743/// failure. Returns true if there was an error, false otherwise. If
1744/// everything went okay, Value will receive the value of the constant
1745/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001746static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001747CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001748 SourceLocation Loc = Index->getSourceRange().getBegin();
1749
1750 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001751 if (S.VerifyIntegerConstantExpression(Index, &Value))
1752 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001753
Chris Lattner3bf68932009-04-25 21:59:05 +00001754 if (Value.isSigned() && Value.isNegative())
1755 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001756 << Value.toString(10) << Index->getSourceRange();
1757
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001758 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001759 return false;
1760}
1761
1762Sema::OwningExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
1763 SourceLocation Loc,
Douglas Gregoreeae8f02009-03-28 00:41:23 +00001764 bool GNUSyntax,
Douglas Gregor05c13a32009-01-22 00:58:24 +00001765 OwningExprResult Init) {
1766 typedef DesignatedInitExpr::Designator ASTDesignator;
1767
1768 bool Invalid = false;
1769 llvm::SmallVector<ASTDesignator, 32> Designators;
1770 llvm::SmallVector<Expr *, 32> InitExpressions;
1771
1772 // Build designators and check array designator expressions.
1773 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1774 const Designator &D = Desig.getDesignator(Idx);
1775 switch (D.getKind()) {
1776 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001777 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001778 D.getFieldLoc()));
1779 break;
1780
1781 case Designator::ArrayDesignator: {
1782 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1783 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001784 if (!Index->isTypeDependent() &&
1785 !Index->isValueDependent() &&
1786 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001787 Invalid = true;
1788 else {
1789 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001790 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001791 D.getRBracketLoc()));
1792 InitExpressions.push_back(Index);
1793 }
1794 break;
1795 }
1796
1797 case Designator::ArrayRangeDesignator: {
1798 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1799 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1800 llvm::APSInt StartValue;
1801 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001802 bool StartDependent = StartIndex->isTypeDependent() ||
1803 StartIndex->isValueDependent();
1804 bool EndDependent = EndIndex->isTypeDependent() ||
1805 EndIndex->isValueDependent();
1806 if ((!StartDependent &&
1807 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1808 (!EndDependent &&
1809 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001810 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001811 else {
1812 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001813 if (StartDependent || EndDependent) {
1814 // Nothing to compute.
1815 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Douglas Gregord6f584f2009-01-23 22:22:29 +00001816 EndValue.extend(StartValue.getBitWidth());
1817 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
1818 StartValue.extend(EndValue.getBitWidth());
1819
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00001820 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00001821 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00001822 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00001823 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
1824 Invalid = true;
1825 } else {
1826 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001827 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00001828 D.getEllipsisLoc(),
1829 D.getRBracketLoc()));
1830 InitExpressions.push_back(StartIndex);
1831 InitExpressions.push_back(EndIndex);
1832 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001833 }
1834 break;
1835 }
1836 }
1837 }
1838
1839 if (Invalid || Init.isInvalid())
1840 return ExprError();
1841
1842 // Clear out the expressions within the designation.
1843 Desig.ClearExprs(*this);
1844
1845 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00001846 = DesignatedInitExpr::Create(Context,
1847 Designators.data(), Designators.size(),
1848 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00001849 Loc, GNUSyntax, Init.takeAs<Expr>());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001850 return Owned(DIE);
1851}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001852
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001853bool Sema::CheckInitList(const InitializedEntity &Entity,
1854 InitListExpr *&InitList, QualType &DeclType) {
1855 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001856 if (!CheckInitList.HadError())
1857 InitList = CheckInitList.getFullyStructuredList();
1858
1859 return CheckInitList.HadError();
1860}
Douglas Gregor87fd7032009-02-02 17:43:21 +00001861
Douglas Gregor20093b42009-12-09 23:02:17 +00001862//===----------------------------------------------------------------------===//
1863// Initialization entity
1864//===----------------------------------------------------------------------===//
1865
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001866InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
1867 const InitializedEntity &Parent)
Anders Carlssond3d824d2010-01-23 04:34:47 +00001868 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00001869{
Anders Carlssond3d824d2010-01-23 04:34:47 +00001870 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
1871 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001872 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001873 } else {
1874 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00001875 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00001876 }
Douglas Gregor20093b42009-12-09 23:02:17 +00001877}
1878
1879InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
1880 CXXBaseSpecifier *Base)
1881{
1882 InitializedEntity Result;
1883 Result.Kind = EK_Base;
1884 Result.Base = Base;
Douglas Gregord6542d82009-12-22 15:35:07 +00001885 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00001886 return Result;
1887}
1888
Douglas Gregor99a2e602009-12-16 01:38:02 +00001889DeclarationName InitializedEntity::getName() const {
1890 switch (getKind()) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00001891 case EK_Parameter:
Douglas Gregora188ff22009-12-22 16:09:06 +00001892 if (!VariableOrMember)
1893 return DeclarationName();
1894 // Fall through
1895
1896 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001897 case EK_Member:
1898 return VariableOrMember->getDeclName();
1899
1900 case EK_Result:
1901 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001902 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001903 case EK_Temporary:
1904 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001905 case EK_ArrayElement:
1906 case EK_VectorElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00001907 return DeclarationName();
1908 }
1909
1910 // Silence GCC warning
1911 return DeclarationName();
1912}
1913
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001914DeclaratorDecl *InitializedEntity::getDecl() const {
1915 switch (getKind()) {
1916 case EK_Variable:
1917 case EK_Parameter:
1918 case EK_Member:
1919 return VariableOrMember;
1920
1921 case EK_Result:
1922 case EK_Exception:
1923 case EK_New:
1924 case EK_Temporary:
1925 case EK_Base:
Anders Carlssond3d824d2010-01-23 04:34:47 +00001926 case EK_ArrayElement:
1927 case EK_VectorElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00001928 return 0;
1929 }
1930
1931 // Silence GCC warning
1932 return 0;
1933}
1934
Douglas Gregor20093b42009-12-09 23:02:17 +00001935//===----------------------------------------------------------------------===//
1936// Initialization sequence
1937//===----------------------------------------------------------------------===//
1938
1939void InitializationSequence::Step::Destroy() {
1940 switch (Kind) {
1941 case SK_ResolveAddressOfOverloadedFunction:
1942 case SK_CastDerivedToBaseRValue:
1943 case SK_CastDerivedToBaseLValue:
1944 case SK_BindReference:
1945 case SK_BindReferenceToTemporary:
1946 case SK_UserConversion:
1947 case SK_QualificationConversionRValue:
1948 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00001949 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00001950 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00001951 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00001952 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00001953 case SK_StringInit:
Douglas Gregor20093b42009-12-09 23:02:17 +00001954 break;
1955
1956 case SK_ConversionSequence:
1957 delete ICS;
1958 }
1959}
1960
1961void InitializationSequence::AddAddressOverloadResolutionStep(
1962 FunctionDecl *Function) {
1963 Step S;
1964 S.Kind = SK_ResolveAddressOfOverloadedFunction;
1965 S.Type = Function->getType();
1966 S.Function = Function;
1967 Steps.push_back(S);
1968}
1969
1970void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
1971 bool IsLValue) {
1972 Step S;
1973 S.Kind = IsLValue? SK_CastDerivedToBaseLValue : SK_CastDerivedToBaseRValue;
1974 S.Type = BaseType;
1975 Steps.push_back(S);
1976}
1977
1978void InitializationSequence::AddReferenceBindingStep(QualType T,
1979 bool BindingTemporary) {
1980 Step S;
1981 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
1982 S.Type = T;
1983 Steps.push_back(S);
1984}
1985
Eli Friedman03981012009-12-11 02:42:07 +00001986void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
1987 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00001988 Step S;
1989 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00001990 S.Type = T;
Douglas Gregor20093b42009-12-09 23:02:17 +00001991 S.Function = Function;
1992 Steps.push_back(S);
1993}
1994
1995void InitializationSequence::AddQualificationConversionStep(QualType Ty,
1996 bool IsLValue) {
1997 Step S;
1998 S.Kind = IsLValue? SK_QualificationConversionLValue
1999 : SK_QualificationConversionRValue;
2000 S.Type = Ty;
2001 Steps.push_back(S);
2002}
2003
2004void InitializationSequence::AddConversionSequenceStep(
2005 const ImplicitConversionSequence &ICS,
2006 QualType T) {
2007 Step S;
2008 S.Kind = SK_ConversionSequence;
2009 S.Type = T;
2010 S.ICS = new ImplicitConversionSequence(ICS);
2011 Steps.push_back(S);
2012}
2013
Douglas Gregord87b61f2009-12-10 17:56:55 +00002014void InitializationSequence::AddListInitializationStep(QualType T) {
2015 Step S;
2016 S.Kind = SK_ListInitialization;
2017 S.Type = T;
2018 Steps.push_back(S);
2019}
2020
Douglas Gregor51c56d62009-12-14 20:49:26 +00002021void
2022InitializationSequence::AddConstructorInitializationStep(
2023 CXXConstructorDecl *Constructor,
2024 QualType T) {
2025 Step S;
2026 S.Kind = SK_ConstructorInitialization;
2027 S.Type = T;
2028 S.Function = Constructor;
2029 Steps.push_back(S);
2030}
2031
Douglas Gregor71d17402009-12-15 00:01:57 +00002032void InitializationSequence::AddZeroInitializationStep(QualType T) {
2033 Step S;
2034 S.Kind = SK_ZeroInitialization;
2035 S.Type = T;
2036 Steps.push_back(S);
2037}
2038
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002039void InitializationSequence::AddCAssignmentStep(QualType T) {
2040 Step S;
2041 S.Kind = SK_CAssignment;
2042 S.Type = T;
2043 Steps.push_back(S);
2044}
2045
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002046void InitializationSequence::AddStringInitStep(QualType T) {
2047 Step S;
2048 S.Kind = SK_StringInit;
2049 S.Type = T;
2050 Steps.push_back(S);
2051}
2052
Douglas Gregor20093b42009-12-09 23:02:17 +00002053void InitializationSequence::SetOverloadFailure(FailureKind Failure,
2054 OverloadingResult Result) {
2055 SequenceKind = FailedSequence;
2056 this->Failure = Failure;
2057 this->FailedOverloadResult = Result;
2058}
2059
2060//===----------------------------------------------------------------------===//
2061// Attempt initialization
2062//===----------------------------------------------------------------------===//
2063
2064/// \brief Attempt list initialization (C++0x [dcl.init.list])
Douglas Gregord87b61f2009-12-10 17:56:55 +00002065static void TryListInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002066 const InitializedEntity &Entity,
2067 const InitializationKind &Kind,
2068 InitListExpr *InitList,
2069 InitializationSequence &Sequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00002070 // FIXME: We only perform rudimentary checking of list
2071 // initializations at this point, then assume that any list
2072 // initialization of an array, aggregate, or scalar will be
2073 // well-formed. We we actually "perform" list initialization, we'll
2074 // do all of the necessary checking. C++0x initializer lists will
2075 // force us to perform more checking here.
2076 Sequence.setSequenceKind(InitializationSequence::ListInitialization);
2077
Douglas Gregord6542d82009-12-22 15:35:07 +00002078 QualType DestType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00002079
2080 // C++ [dcl.init]p13:
2081 // If T is a scalar type, then a declaration of the form
2082 //
2083 // T x = { a };
2084 //
2085 // is equivalent to
2086 //
2087 // T x = a;
2088 if (DestType->isScalarType()) {
2089 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2090 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2091 return;
2092 }
2093
2094 // Assume scalar initialization from a single value works.
2095 } else if (DestType->isAggregateType()) {
2096 // Assume aggregate initialization works.
2097 } else if (DestType->isVectorType()) {
2098 // Assume vector initialization works.
2099 } else if (DestType->isReferenceType()) {
2100 // FIXME: C++0x defines behavior for this.
2101 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2102 return;
2103 } else if (DestType->isRecordType()) {
2104 // FIXME: C++0x defines behavior for this
2105 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2106 }
2107
2108 // Add a general "list initialization" step.
2109 Sequence.AddListInitializationStep(DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00002110}
2111
2112/// \brief Try a reference initialization that involves calling a conversion
2113/// function.
2114///
2115/// FIXME: look intos DRs 656, 896
2116static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2117 const InitializedEntity &Entity,
2118 const InitializationKind &Kind,
2119 Expr *Initializer,
2120 bool AllowRValues,
2121 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002122 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002123 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2124 QualType T1 = cv1T1.getUnqualifiedType();
2125 QualType cv2T2 = Initializer->getType();
2126 QualType T2 = cv2T2.getUnqualifiedType();
2127
2128 bool DerivedToBase;
2129 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
2130 T1, T2, DerivedToBase) &&
2131 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002132 (void)DerivedToBase;
Douglas Gregor20093b42009-12-09 23:02:17 +00002133
2134 // Build the candidate set directly in the initialization sequence
2135 // structure, so that it will persist if we fail.
2136 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2137 CandidateSet.clear();
2138
2139 // Determine whether we are allowed to call explicit constructors or
2140 // explicit conversion operators.
2141 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2142
2143 const RecordType *T1RecordType = 0;
2144 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>())) {
2145 // The type we're converting to is a class type. Enumerate its constructors
2146 // to see if there is a suitable conversion.
2147 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
2148
2149 DeclarationName ConstructorName
2150 = S.Context.DeclarationNames.getCXXConstructorName(
2151 S.Context.getCanonicalType(T1).getUnqualifiedType());
2152 DeclContext::lookup_iterator Con, ConEnd;
2153 for (llvm::tie(Con, ConEnd) = T1RecordDecl->lookup(ConstructorName);
2154 Con != ConEnd; ++Con) {
2155 // Find the constructor (which may be a template).
2156 CXXConstructorDecl *Constructor = 0;
2157 FunctionTemplateDecl *ConstructorTmpl
2158 = dyn_cast<FunctionTemplateDecl>(*Con);
2159 if (ConstructorTmpl)
2160 Constructor = cast<CXXConstructorDecl>(
2161 ConstructorTmpl->getTemplatedDecl());
2162 else
2163 Constructor = cast<CXXConstructorDecl>(*Con);
2164
2165 if (!Constructor->isInvalidDecl() &&
2166 Constructor->isConvertingConstructor(AllowExplicit)) {
2167 if (ConstructorTmpl)
2168 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2169 &Initializer, 1, CandidateSet);
2170 else
2171 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2172 }
2173 }
2174 }
2175
2176 if (const RecordType *T2RecordType = T2->getAs<RecordType>()) {
2177 // The type we're converting from is a class type, enumerate its conversion
2178 // functions.
2179 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2180
2181 // Determine the type we are converting to. If we are allowed to
2182 // convert to an rvalue, take the type that the destination type
2183 // refers to.
2184 QualType ToType = AllowRValues? cv1T1 : DestType;
2185
John McCalleec51cf2010-01-20 00:46:10 +00002186 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002187 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002188 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2189 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002190 NamedDecl *D = *I;
2191 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2192 if (isa<UsingShadowDecl>(D))
2193 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2194
2195 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2196 CXXConversionDecl *Conv;
2197 if (ConvTemplate)
2198 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2199 else
2200 Conv = cast<CXXConversionDecl>(*I);
2201
2202 // If the conversion function doesn't return a reference type,
2203 // it can't be considered for this conversion unless we're allowed to
2204 // consider rvalues.
2205 // FIXME: Do we need to make sure that we only consider conversion
2206 // candidates with reference-compatible results? That might be needed to
2207 // break recursion.
2208 if ((AllowExplicit || !Conv->isExplicit()) &&
2209 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2210 if (ConvTemplate)
2211 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC, Initializer,
2212 ToType, CandidateSet);
2213 else
2214 S.AddConversionCandidate(Conv, ActingDC, Initializer, cv1T1,
2215 CandidateSet);
2216 }
2217 }
2218 }
2219
2220 SourceLocation DeclLoc = Initializer->getLocStart();
2221
2222 // Perform overload resolution. If it fails, return the failed result.
2223 OverloadCandidateSet::iterator Best;
2224 if (OverloadingResult Result
2225 = S.BestViableFunction(CandidateSet, DeclLoc, Best))
2226 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002227
Douglas Gregor20093b42009-12-09 23:02:17 +00002228 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002229
2230 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002231 if (isa<CXXConversionDecl>(Function))
2232 T2 = Function->getResultType();
2233 else
2234 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002235
2236 // Add the user-defined conversion step.
2237 Sequence.AddUserConversionStep(Function, T2.getNonReferenceType());
2238
2239 // Determine whether we need to perform derived-to-base or
2240 // cv-qualification adjustments.
Douglas Gregor20093b42009-12-09 23:02:17 +00002241 bool NewDerivedToBase = false;
2242 Sema::ReferenceCompareResult NewRefRelationship
2243 = S.CompareReferenceRelationship(DeclLoc, T1, T2.getNonReferenceType(),
2244 NewDerivedToBase);
2245 assert(NewRefRelationship != Sema::Ref_Incompatible &&
2246 "Overload resolution picked a bad conversion function");
2247 (void)NewRefRelationship;
2248 if (NewDerivedToBase)
2249 Sequence.AddDerivedToBaseCastStep(
2250 S.Context.getQualifiedType(T1,
2251 T2.getNonReferenceType().getQualifiers()),
2252 /*isLValue=*/true);
2253
2254 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
2255 Sequence.AddQualificationConversionStep(cv1T1, T2->isReferenceType());
2256
2257 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2258 return OR_Success;
2259}
2260
2261/// \brief Attempt reference initialization (C++0x [dcl.init.list])
2262static void TryReferenceInitialization(Sema &S,
2263 const InitializedEntity &Entity,
2264 const InitializationKind &Kind,
2265 Expr *Initializer,
2266 InitializationSequence &Sequence) {
2267 Sequence.setSequenceKind(InitializationSequence::ReferenceBinding);
2268
Douglas Gregord6542d82009-12-22 15:35:07 +00002269 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002270 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002271 Qualifiers T1Quals;
2272 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002273 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002274 Qualifiers T2Quals;
2275 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002276 SourceLocation DeclLoc = Initializer->getLocStart();
2277
2278 // If the initializer is the address of an overloaded function, try
2279 // to resolve the overloaded function. If all goes well, T2 is the
2280 // type of the resulting function.
2281 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2282 FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
2283 T1,
2284 false);
2285 if (!Fn) {
2286 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2287 return;
2288 }
2289
2290 Sequence.AddAddressOverloadResolutionStep(Fn);
2291 cv2T2 = Fn->getType();
2292 T2 = cv2T2.getUnqualifiedType();
2293 }
2294
2295 // FIXME: Rvalue references
2296 bool ForceRValue = false;
2297
2298 // Compute some basic properties of the types and the initializer.
2299 bool isLValueRef = DestType->isLValueReferenceType();
2300 bool isRValueRef = !isLValueRef;
2301 bool DerivedToBase = false;
2302 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2303 Initializer->isLvalue(S.Context);
2304 Sema::ReferenceCompareResult RefRelationship
2305 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase);
2306
2307 // C++0x [dcl.init.ref]p5:
2308 // A reference to type "cv1 T1" is initialized by an expression of type
2309 // "cv2 T2" as follows:
2310 //
2311 // - If the reference is an lvalue reference and the initializer
2312 // expression
2313 OverloadingResult ConvOvlResult = OR_Success;
2314 if (isLValueRef) {
2315 if (InitLvalue == Expr::LV_Valid &&
2316 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2317 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
2318 // reference-compatible with "cv2 T2," or
2319 //
2320 // Per C++ [over.best.ics]p2, we ignore whether the lvalue is a
2321 // bit-field when we're determining whether the reference initialization
2322 // can occur. This property will be checked by PerformInitialization.
2323 if (DerivedToBase)
2324 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002325 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002326 /*isLValue=*/true);
Chandler Carruth5535c382010-01-12 20:32:25 +00002327 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002328 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/true);
2329 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/false);
2330 return;
2331 }
2332
2333 // - has a class type (i.e., T2 is a class type), where T1 is not
2334 // reference-related to T2, and can be implicitly converted to an
2335 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2336 // with "cv3 T3" (this conversion is selected by enumerating the
2337 // applicable conversion functions (13.3.1.6) and choosing the best
2338 // one through overload resolution (13.3)),
2339 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType()) {
2340 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
2341 Initializer,
2342 /*AllowRValues=*/false,
2343 Sequence);
2344 if (ConvOvlResult == OR_Success)
2345 return;
John McCall1d318332010-01-12 00:44:57 +00002346 if (ConvOvlResult != OR_No_Viable_Function) {
2347 Sequence.SetOverloadFailure(
2348 InitializationSequence::FK_ReferenceInitOverloadFailed,
2349 ConvOvlResult);
2350 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002351 }
2352 }
2353
2354 // - Otherwise, the reference shall be an lvalue reference to a
2355 // non-volatile const type (i.e., cv1 shall be const), or the reference
2356 // shall be an rvalue reference and the initializer expression shall
2357 // be an rvalue.
Chandler Carruth5535c382010-01-12 20:32:25 +00002358 if (!((isLValueRef && T1Quals.hasConst()) ||
Douglas Gregor20093b42009-12-09 23:02:17 +00002359 (isRValueRef && InitLvalue != Expr::LV_Valid))) {
2360 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2361 Sequence.SetOverloadFailure(
2362 InitializationSequence::FK_ReferenceInitOverloadFailed,
2363 ConvOvlResult);
2364 else if (isLValueRef)
2365 Sequence.SetFailed(InitLvalue == Expr::LV_Valid
2366 ? (RefRelationship == Sema::Ref_Related
2367 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2368 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2369 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
2370 else
2371 Sequence.SetFailed(
2372 InitializationSequence::FK_RValueReferenceBindingToLValue);
2373
2374 return;
2375 }
2376
2377 // - If T1 and T2 are class types and
2378 if (T1->isRecordType() && T2->isRecordType()) {
2379 // - the initializer expression is an rvalue and "cv1 T1" is
2380 // reference-compatible with "cv2 T2", or
2381 if (InitLvalue != Expr::LV_Valid &&
2382 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2383 if (DerivedToBase)
2384 Sequence.AddDerivedToBaseCastStep(
Chandler Carruth5535c382010-01-12 20:32:25 +00002385 S.Context.getQualifiedType(T1, T2Quals),
Douglas Gregor20093b42009-12-09 23:02:17 +00002386 /*isLValue=*/false);
Chandler Carruth5535c382010-01-12 20:32:25 +00002387 if (T1Quals != T2Quals)
Douglas Gregor20093b42009-12-09 23:02:17 +00002388 Sequence.AddQualificationConversionStep(cv1T1, /*IsLValue=*/false);
2389 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2390 return;
2391 }
2392
2393 // - T1 is not reference-related to T2 and the initializer expression
2394 // can be implicitly converted to an rvalue of type "cv3 T3" (this
2395 // conversion is selected by enumerating the applicable conversion
2396 // functions (13.3.1.6) and choosing the best one through overload
2397 // resolution (13.3)),
2398 if (RefRelationship == Sema::Ref_Incompatible) {
2399 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2400 Kind, Initializer,
2401 /*AllowRValues=*/true,
2402 Sequence);
2403 if (ConvOvlResult)
2404 Sequence.SetOverloadFailure(
2405 InitializationSequence::FK_ReferenceInitOverloadFailed,
2406 ConvOvlResult);
2407
2408 return;
2409 }
2410
2411 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2412 return;
2413 }
2414
2415 // - If the initializer expression is an rvalue, with T2 an array type,
2416 // and "cv1 T1" is reference-compatible with "cv2 T2," the reference
2417 // is bound to the object represented by the rvalue (see 3.10).
2418 // FIXME: How can an array type be reference-compatible with anything?
2419 // Don't we mean the element types of T1 and T2?
2420
2421 // - Otherwise, a temporary of type “cv1 T1” is created and initialized
2422 // from the initializer expression using the rules for a non-reference
2423 // copy initialization (8.5). The reference is then bound to the
2424 // temporary. [...]
2425 // Determine whether we are allowed to call explicit constructors or
2426 // explicit conversion operators.
2427 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
2428 ImplicitConversionSequence ICS
2429 = S.TryImplicitConversion(Initializer, cv1T1,
2430 /*SuppressUserConversions=*/false, AllowExplicit,
2431 /*ForceRValue=*/false,
2432 /*FIXME:InOverloadResolution=*/false,
2433 /*UserCast=*/Kind.isExplicitCast());
2434
John McCall1d318332010-01-12 00:44:57 +00002435 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002436 // FIXME: Use the conversion function set stored in ICS to turn
2437 // this into an overloading ambiguity diagnostic. However, we need
2438 // to keep that set as an OverloadCandidateSet rather than as some
2439 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002440 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
2441 Sequence.SetOverloadFailure(
2442 InitializationSequence::FK_ReferenceInitOverloadFailed,
2443 ConvOvlResult);
2444 else
2445 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00002446 return;
2447 }
2448
2449 // [...] If T1 is reference-related to T2, cv1 must be the
2450 // same cv-qualification as, or greater cv-qualification
2451 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00002452 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
2453 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
Douglas Gregor20093b42009-12-09 23:02:17 +00002454 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00002455 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002456 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2457 return;
2458 }
2459
2460 // Perform the actual conversion.
2461 Sequence.AddConversionSequenceStep(ICS, cv1T1);
2462 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
2463 return;
2464}
2465
2466/// \brief Attempt character array initialization from a string literal
2467/// (C++ [dcl.init.string], C99 6.7.8).
2468static void TryStringLiteralInitialization(Sema &S,
2469 const InitializedEntity &Entity,
2470 const InitializationKind &Kind,
2471 Expr *Initializer,
2472 InitializationSequence &Sequence) {
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002473 Sequence.setSequenceKind(InitializationSequence::StringInit);
Douglas Gregord6542d82009-12-22 15:35:07 +00002474 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002475}
2476
Douglas Gregor20093b42009-12-09 23:02:17 +00002477/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2478/// enumerates the constructors of the initialized entity and performs overload
2479/// resolution to select the best.
2480static void TryConstructorInitialization(Sema &S,
2481 const InitializedEntity &Entity,
2482 const InitializationKind &Kind,
2483 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00002484 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00002485 InitializationSequence &Sequence) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002486 if (Kind.getKind() == InitializationKind::IK_Copy)
2487 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2488 else
2489 Sequence.setSequenceKind(InitializationSequence::ConstructorInitialization);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002490
2491 // Build the candidate set directly in the initialization sequence
2492 // structure, so that it will persist if we fail.
2493 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2494 CandidateSet.clear();
2495
2496 // Determine whether we are allowed to call explicit constructors or
2497 // explicit conversion operators.
2498 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2499 Kind.getKind() == InitializationKind::IK_Value ||
2500 Kind.getKind() == InitializationKind::IK_Default);
2501
2502 // The type we're converting to is a class type. Enumerate its constructors
2503 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00002504 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2505 assert(DestRecordType && "Constructor initialization requires record type");
2506 CXXRecordDecl *DestRecordDecl
2507 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2508
2509 DeclarationName ConstructorName
2510 = S.Context.DeclarationNames.getCXXConstructorName(
2511 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2512 DeclContext::lookup_iterator Con, ConEnd;
2513 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2514 Con != ConEnd; ++Con) {
2515 // Find the constructor (which may be a template).
2516 CXXConstructorDecl *Constructor = 0;
2517 FunctionTemplateDecl *ConstructorTmpl
2518 = dyn_cast<FunctionTemplateDecl>(*Con);
2519 if (ConstructorTmpl)
2520 Constructor = cast<CXXConstructorDecl>(
2521 ConstructorTmpl->getTemplatedDecl());
2522 else
2523 Constructor = cast<CXXConstructorDecl>(*Con);
2524
2525 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00002526 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002527 if (ConstructorTmpl)
2528 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2529 Args, NumArgs, CandidateSet);
2530 else
2531 S.AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2532 }
2533 }
2534
2535 SourceLocation DeclLoc = Kind.getLocation();
2536
2537 // Perform overload resolution. If it fails, return the failed result.
2538 OverloadCandidateSet::iterator Best;
2539 if (OverloadingResult Result
2540 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2541 Sequence.SetOverloadFailure(
2542 InitializationSequence::FK_ConstructorOverloadFailed,
2543 Result);
2544 return;
2545 }
2546
2547 // Add the constructor initialization step. Any cv-qualification conversion is
2548 // subsumed by the initialization.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002549 if (Kind.getKind() == InitializationKind::IK_Copy) {
2550 Sequence.AddUserConversionStep(Best->Function, DestType);
2551 } else {
2552 Sequence.AddConstructorInitializationStep(
Douglas Gregor51c56d62009-12-14 20:49:26 +00002553 cast<CXXConstructorDecl>(Best->Function),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002554 DestType);
2555 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002556}
2557
Douglas Gregor71d17402009-12-15 00:01:57 +00002558/// \brief Attempt value initialization (C++ [dcl.init]p7).
2559static void TryValueInitialization(Sema &S,
2560 const InitializedEntity &Entity,
2561 const InitializationKind &Kind,
2562 InitializationSequence &Sequence) {
2563 // C++ [dcl.init]p5:
2564 //
2565 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00002566 QualType T = Entity.getType();
Douglas Gregor71d17402009-12-15 00:01:57 +00002567
2568 // -- if T is an array type, then each element is value-initialized;
2569 while (const ArrayType *AT = S.Context.getAsArrayType(T))
2570 T = AT->getElementType();
2571
2572 if (const RecordType *RT = T->getAs<RecordType>()) {
2573 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2574 // -- if T is a class type (clause 9) with a user-declared
2575 // constructor (12.1), then the default constructor for T is
2576 // called (and the initialization is ill-formed if T has no
2577 // accessible default constructor);
2578 //
2579 // FIXME: we really want to refer to a single subobject of the array,
2580 // but Entity doesn't have a way to capture that (yet).
2581 if (ClassDecl->hasUserDeclaredConstructor())
2582 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2583
Douglas Gregor16006c92009-12-16 18:50:27 +00002584 // -- if T is a (possibly cv-qualified) non-union class type
2585 // without a user-provided constructor, then the object is
2586 // zero-initialized and, if T’s implicitly-declared default
2587 // constructor is non-trivial, that constructor is called.
2588 if ((ClassDecl->getTagKind() == TagDecl::TK_class ||
2589 ClassDecl->getTagKind() == TagDecl::TK_struct) &&
2590 !ClassDecl->hasTrivialConstructor()) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002591 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor16006c92009-12-16 18:50:27 +00002592 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
2593 }
Douglas Gregor71d17402009-12-15 00:01:57 +00002594 }
2595 }
2596
Douglas Gregord6542d82009-12-22 15:35:07 +00002597 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00002598 Sequence.setSequenceKind(InitializationSequence::ZeroInitialization);
2599}
2600
Douglas Gregor99a2e602009-12-16 01:38:02 +00002601/// \brief Attempt default initialization (C++ [dcl.init]p6).
2602static void TryDefaultInitialization(Sema &S,
2603 const InitializedEntity &Entity,
2604 const InitializationKind &Kind,
2605 InitializationSequence &Sequence) {
2606 assert(Kind.getKind() == InitializationKind::IK_Default);
2607
2608 // C++ [dcl.init]p6:
2609 // To default-initialize an object of type T means:
2610 // - if T is an array type, each element is default-initialized;
Douglas Gregord6542d82009-12-22 15:35:07 +00002611 QualType DestType = Entity.getType();
Douglas Gregor99a2e602009-12-16 01:38:02 +00002612 while (const ArrayType *Array = S.Context.getAsArrayType(DestType))
2613 DestType = Array->getElementType();
2614
2615 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
2616 // constructor for T is called (and the initialization is ill-formed if
2617 // T has no accessible default constructor);
2618 if (DestType->isRecordType()) {
2619 // FIXME: If a program calls for the default initialization of an object of
2620 // a const-qualified type T, T shall be a class type with a user-provided
2621 // default constructor.
2622 return TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType,
2623 Sequence);
2624 }
2625
2626 // - otherwise, no initialization is performed.
2627 Sequence.setSequenceKind(InitializationSequence::NoInitialization);
2628
2629 // If a program calls for the default initialization of an object of
2630 // a const-qualified type T, T shall be a class type with a user-provided
2631 // default constructor.
2632 if (DestType.isConstQualified())
2633 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
2634}
2635
Douglas Gregor20093b42009-12-09 23:02:17 +00002636/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
2637/// which enumerates all conversion functions and performs overload resolution
2638/// to select the best.
2639static void TryUserDefinedConversion(Sema &S,
2640 const InitializedEntity &Entity,
2641 const InitializationKind &Kind,
2642 Expr *Initializer,
2643 InitializationSequence &Sequence) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00002644 Sequence.setSequenceKind(InitializationSequence::UserDefinedConversion);
2645
Douglas Gregord6542d82009-12-22 15:35:07 +00002646 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002647 assert(!DestType->isReferenceType() && "References are handled elsewhere");
2648 QualType SourceType = Initializer->getType();
2649 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
2650 "Must have a class type to perform a user-defined conversion");
2651
2652 // Build the candidate set directly in the initialization sequence
2653 // structure, so that it will persist if we fail.
2654 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2655 CandidateSet.clear();
2656
2657 // Determine whether we are allowed to call explicit constructors or
2658 // explicit conversion operators.
2659 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
2660
2661 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
2662 // The type we're converting to is a class type. Enumerate its constructors
2663 // to see if there is a suitable conversion.
2664 CXXRecordDecl *DestRecordDecl
2665 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2666
2667 DeclarationName ConstructorName
2668 = S.Context.DeclarationNames.getCXXConstructorName(
2669 S.Context.getCanonicalType(DestType).getUnqualifiedType());
2670 DeclContext::lookup_iterator Con, ConEnd;
2671 for (llvm::tie(Con, ConEnd) = DestRecordDecl->lookup(ConstructorName);
2672 Con != ConEnd; ++Con) {
2673 // Find the constructor (which may be a template).
2674 CXXConstructorDecl *Constructor = 0;
2675 FunctionTemplateDecl *ConstructorTmpl
2676 = dyn_cast<FunctionTemplateDecl>(*Con);
2677 if (ConstructorTmpl)
2678 Constructor = cast<CXXConstructorDecl>(
2679 ConstructorTmpl->getTemplatedDecl());
2680 else
2681 Constructor = cast<CXXConstructorDecl>(*Con);
2682
2683 if (!Constructor->isInvalidDecl() &&
2684 Constructor->isConvertingConstructor(AllowExplicit)) {
2685 if (ConstructorTmpl)
2686 S.AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
2687 &Initializer, 1, CandidateSet);
2688 else
2689 S.AddOverloadCandidate(Constructor, &Initializer, 1, CandidateSet);
2690 }
2691 }
2692 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002693
2694 SourceLocation DeclLoc = Initializer->getLocStart();
2695
Douglas Gregor4a520a22009-12-14 17:27:33 +00002696 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
2697 // The type we're converting from is a class type, enumerate its conversion
2698 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002699
Eli Friedman33c2da92009-12-20 22:12:03 +00002700 // We can only enumerate the conversion functions for a complete type; if
2701 // the type isn't complete, simply skip this step.
2702 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
2703 CXXRecordDecl *SourceRecordDecl
2704 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002705
John McCalleec51cf2010-01-20 00:46:10 +00002706 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00002707 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002708 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
Eli Friedman33c2da92009-12-20 22:12:03 +00002709 E = Conversions->end();
2710 I != E; ++I) {
2711 NamedDecl *D = *I;
2712 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2713 if (isa<UsingShadowDecl>(D))
2714 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2715
2716 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2717 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00002718 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00002719 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00002720 else
Eli Friedman33c2da92009-12-20 22:12:03 +00002721 Conv = cast<CXXConversionDecl>(*I);
2722
2723 if (AllowExplicit || !Conv->isExplicit()) {
2724 if (ConvTemplate)
2725 S.AddTemplateConversionCandidate(ConvTemplate, ActingDC,
2726 Initializer, DestType,
2727 CandidateSet);
2728 else
2729 S.AddConversionCandidate(Conv, ActingDC, Initializer, DestType,
2730 CandidateSet);
2731 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00002732 }
2733 }
2734 }
2735
Douglas Gregor4a520a22009-12-14 17:27:33 +00002736 // Perform overload resolution. If it fails, return the failed result.
2737 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00002738 if (OverloadingResult Result
Douglas Gregor4a520a22009-12-14 17:27:33 +00002739 = S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2740 Sequence.SetOverloadFailure(
2741 InitializationSequence::FK_UserConversionOverloadFailed,
2742 Result);
2743 return;
2744 }
John McCall1d318332010-01-12 00:44:57 +00002745
Douglas Gregor4a520a22009-12-14 17:27:33 +00002746 FunctionDecl *Function = Best->Function;
2747
2748 if (isa<CXXConstructorDecl>(Function)) {
2749 // Add the user-defined conversion step. Any cv-qualification conversion is
2750 // subsumed by the initialization.
2751 Sequence.AddUserConversionStep(Function, DestType);
2752 return;
2753 }
2754
2755 // Add the user-defined conversion step that calls the conversion function.
2756 QualType ConvType = Function->getResultType().getNonReferenceType();
2757 Sequence.AddUserConversionStep(Function, ConvType);
2758
2759 // If the conversion following the call to the conversion function is
2760 // interesting, add it as a separate step.
2761 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
2762 Best->FinalConversion.Third) {
2763 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00002764 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00002765 ICS.Standard = Best->FinalConversion;
2766 Sequence.AddConversionSequenceStep(ICS, DestType);
2767 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002768}
2769
2770/// \brief Attempt an implicit conversion (C++ [conv]) converting from one
2771/// non-class type to another.
2772static void TryImplicitConversion(Sema &S,
2773 const InitializedEntity &Entity,
2774 const InitializationKind &Kind,
2775 Expr *Initializer,
2776 InitializationSequence &Sequence) {
2777 ImplicitConversionSequence ICS
Douglas Gregord6542d82009-12-22 15:35:07 +00002778 = S.TryImplicitConversion(Initializer, Entity.getType(),
Douglas Gregor20093b42009-12-09 23:02:17 +00002779 /*SuppressUserConversions=*/true,
2780 /*AllowExplicit=*/false,
2781 /*ForceRValue=*/false,
2782 /*FIXME:InOverloadResolution=*/false,
2783 /*UserCast=*/Kind.isExplicitCast());
2784
John McCall1d318332010-01-12 00:44:57 +00002785 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002786 Sequence.SetFailed(InitializationSequence::FK_ConversionFailed);
2787 return;
2788 }
2789
Douglas Gregord6542d82009-12-22 15:35:07 +00002790 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00002791}
2792
2793InitializationSequence::InitializationSequence(Sema &S,
2794 const InitializedEntity &Entity,
2795 const InitializationKind &Kind,
2796 Expr **Args,
2797 unsigned NumArgs) {
2798 ASTContext &Context = S.Context;
2799
2800 // C++0x [dcl.init]p16:
2801 // The semantics of initializers are as follows. The destination type is
2802 // the type of the object or reference being initialized and the source
2803 // type is the type of the initializer expression. The source type is not
2804 // defined when the initializer is a braced-init-list or when it is a
2805 // parenthesized list of expressions.
Douglas Gregord6542d82009-12-22 15:35:07 +00002806 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002807
2808 if (DestType->isDependentType() ||
2809 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2810 SequenceKind = DependentSequence;
2811 return;
2812 }
2813
2814 QualType SourceType;
2815 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00002816 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002817 Initializer = Args[0];
2818 if (!isa<InitListExpr>(Initializer))
2819 SourceType = Initializer->getType();
2820 }
2821
2822 // - If the initializer is a braced-init-list, the object is
2823 // list-initialized (8.5.4).
2824 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
2825 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00002826 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00002827 }
2828
2829 // - If the destination type is a reference type, see 8.5.3.
2830 if (DestType->isReferenceType()) {
2831 // C++0x [dcl.init.ref]p1:
2832 // A variable declared to be a T& or T&&, that is, "reference to type T"
2833 // (8.3.2), shall be initialized by an object, or function, of type T or
2834 // by an object that can be converted into a T.
2835 // (Therefore, multiple arguments are not permitted.)
2836 if (NumArgs != 1)
2837 SetFailed(FK_TooManyInitsForReference);
2838 else
2839 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
2840 return;
2841 }
2842
2843 // - If the destination type is an array of characters, an array of
2844 // char16_t, an array of char32_t, or an array of wchar_t, and the
2845 // initializer is a string literal, see 8.5.2.
2846 if (Initializer && IsStringInit(Initializer, DestType, Context)) {
2847 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
2848 return;
2849 }
2850
2851 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002852 if (Kind.getKind() == InitializationKind::IK_Value ||
2853 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002854 TryValueInitialization(S, Entity, Kind, *this);
2855 return;
2856 }
2857
Douglas Gregor99a2e602009-12-16 01:38:02 +00002858 // Handle default initialization.
2859 if (Kind.getKind() == InitializationKind::IK_Default){
2860 TryDefaultInitialization(S, Entity, Kind, *this);
2861 return;
2862 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002863
Douglas Gregor20093b42009-12-09 23:02:17 +00002864 // - Otherwise, if the destination type is an array, the program is
2865 // ill-formed.
2866 if (const ArrayType *AT = Context.getAsArrayType(DestType)) {
2867 if (AT->getElementType()->isAnyCharacterType())
2868 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
2869 else
2870 SetFailed(FK_ArrayNeedsInitList);
2871
2872 return;
2873 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002874
2875 // Handle initialization in C
2876 if (!S.getLangOptions().CPlusPlus) {
2877 setSequenceKind(CAssignment);
2878 AddCAssignmentStep(DestType);
2879 return;
2880 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002881
2882 // - If the destination type is a (possibly cv-qualified) class type:
2883 if (DestType->isRecordType()) {
2884 // - If the initialization is direct-initialization, or if it is
2885 // copy-initialization where the cv-unqualified version of the
2886 // source type is the same class as, or a derived class of, the
2887 // class of the destination, constructors are considered. [...]
2888 if (Kind.getKind() == InitializationKind::IK_Direct ||
2889 (Kind.getKind() == InitializationKind::IK_Copy &&
2890 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
2891 S.IsDerivedFrom(SourceType, DestType))))
Douglas Gregor71d17402009-12-15 00:01:57 +00002892 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Douglas Gregord6542d82009-12-22 15:35:07 +00002893 Entity.getType(), *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00002894 // - Otherwise (i.e., for the remaining copy-initialization cases),
2895 // user-defined conversion sequences that can convert from the source
2896 // type to the destination type or (when a conversion function is
2897 // used) to a derived class thereof are enumerated as described in
2898 // 13.3.1.4, and the best one is chosen through overload resolution
2899 // (13.3).
2900 else
2901 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2902 return;
2903 }
2904
Douglas Gregor99a2e602009-12-16 01:38:02 +00002905 if (NumArgs > 1) {
2906 SetFailed(FK_TooManyInitsForScalar);
2907 return;
2908 }
2909 assert(NumArgs == 1 && "Zero-argument case handled above");
2910
Douglas Gregor20093b42009-12-09 23:02:17 +00002911 // - Otherwise, if the source type is a (possibly cv-qualified) class
2912 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002913 if (!SourceType.isNull() && SourceType->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002914 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
2915 return;
2916 }
2917
2918 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00002919 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00002920 // conversions (Clause 4) will be used, if necessary, to convert the
2921 // initializer expression to the cv-unqualified version of the
2922 // destination type; no user-defined conversions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00002923 setSequenceKind(StandardConversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00002924 TryImplicitConversion(S, Entity, Kind, Initializer, *this);
2925}
2926
2927InitializationSequence::~InitializationSequence() {
2928 for (llvm::SmallVectorImpl<Step>::iterator Step = Steps.begin(),
2929 StepEnd = Steps.end();
2930 Step != StepEnd; ++Step)
2931 Step->Destroy();
2932}
2933
2934//===----------------------------------------------------------------------===//
2935// Perform initialization
2936//===----------------------------------------------------------------------===//
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002937static Sema::AssignmentAction
2938getAssignmentAction(const InitializedEntity &Entity) {
2939 switch(Entity.getKind()) {
2940 case InitializedEntity::EK_Variable:
2941 case InitializedEntity::EK_New:
2942 return Sema::AA_Initializing;
2943
2944 case InitializedEntity::EK_Parameter:
2945 // FIXME: Can we tell when we're sending vs. passing?
2946 return Sema::AA_Passing;
2947
2948 case InitializedEntity::EK_Result:
2949 return Sema::AA_Returning;
2950
2951 case InitializedEntity::EK_Exception:
2952 case InitializedEntity::EK_Base:
2953 llvm_unreachable("No assignment action for C++-specific initialization");
2954 break;
2955
2956 case InitializedEntity::EK_Temporary:
2957 // FIXME: Can we tell apart casting vs. converting?
2958 return Sema::AA_Casting;
2959
2960 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002961 case InitializedEntity::EK_ArrayElement:
2962 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002963 return Sema::AA_Initializing;
2964 }
2965
2966 return Sema::AA_Converting;
2967}
2968
2969static bool shouldBindAsTemporary(const InitializedEntity &Entity,
2970 bool IsCopy) {
2971 switch (Entity.getKind()) {
2972 case InitializedEntity::EK_Result:
2973 case InitializedEntity::EK_Exception:
2974 return !IsCopy;
2975
2976 case InitializedEntity::EK_New:
2977 case InitializedEntity::EK_Variable:
2978 case InitializedEntity::EK_Base:
2979 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002980 case InitializedEntity::EK_ArrayElement:
2981 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002982 return false;
2983
2984 case InitializedEntity::EK_Parameter:
2985 case InitializedEntity::EK_Temporary:
2986 return true;
2987 }
2988
2989 llvm_unreachable("missed an InitializedEntity kind?");
2990}
2991
2992/// \brief If we need to perform an additional copy of the initialized object
2993/// for this kind of entity (e.g., the result of a function or an object being
2994/// thrown), make the copy.
2995static Sema::OwningExprResult CopyIfRequiredForEntity(Sema &S,
2996 const InitializedEntity &Entity,
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002997 const InitializationKind &Kind,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002998 Sema::OwningExprResult CurInit) {
2999 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003000
3001 switch (Entity.getKind()) {
3002 case InitializedEntity::EK_Result:
Douglas Gregord6542d82009-12-22 15:35:07 +00003003 if (Entity.getType()->isReferenceType())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003004 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003005 Loc = Entity.getReturnLoc();
3006 break;
3007
3008 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003009 Loc = Entity.getThrowLoc();
3010 break;
3011
3012 case InitializedEntity::EK_Variable:
Douglas Gregord6542d82009-12-22 15:35:07 +00003013 if (Entity.getType()->isReferenceType() ||
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003014 Kind.getKind() != InitializationKind::IK_Copy)
3015 return move(CurInit);
3016 Loc = Entity.getDecl()->getLocation();
3017 break;
3018
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003019 case InitializedEntity::EK_Parameter:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003020 // FIXME: Do we need this initialization for a parameter?
3021 return move(CurInit);
3022
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003023 case InitializedEntity::EK_New:
3024 case InitializedEntity::EK_Temporary:
3025 case InitializedEntity::EK_Base:
3026 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003027 case InitializedEntity::EK_ArrayElement:
3028 case InitializedEntity::EK_VectorElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003029 // We don't need to copy for any of these initialized entities.
3030 return move(CurInit);
3031 }
3032
3033 Expr *CurInitExpr = (Expr *)CurInit.get();
3034 CXXRecordDecl *Class = 0;
3035 if (const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>())
3036 Class = cast<CXXRecordDecl>(Record->getDecl());
3037 if (!Class)
3038 return move(CurInit);
3039
3040 // Perform overload resolution using the class's copy constructors.
3041 DeclarationName ConstructorName
3042 = S.Context.DeclarationNames.getCXXConstructorName(
3043 S.Context.getCanonicalType(S.Context.getTypeDeclType(Class)));
3044 DeclContext::lookup_iterator Con, ConEnd;
3045 OverloadCandidateSet CandidateSet;
3046 for (llvm::tie(Con, ConEnd) = Class->lookup(ConstructorName);
3047 Con != ConEnd; ++Con) {
3048 // Find the constructor (which may be a template).
3049 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(*Con);
3050 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregor9e9199d2009-12-22 00:34:07 +00003051 !Constructor->isCopyConstructor())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003052 continue;
3053
3054 S.AddOverloadCandidate(Constructor, &CurInitExpr, 1, CandidateSet);
3055 }
3056
3057 OverloadCandidateSet::iterator Best;
3058 switch (S.BestViableFunction(CandidateSet, Loc, Best)) {
3059 case OR_Success:
3060 break;
3061
3062 case OR_No_Viable_Function:
3063 S.Diag(Loc, diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003064 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003065 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003066 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_AllCandidates,
3067 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003068 return S.ExprError();
3069
3070 case OR_Ambiguous:
3071 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003072 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003073 << CurInitExpr->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003074 S.PrintOverloadCandidates(CandidateSet, Sema::OCD_ViableCandidates,
3075 &CurInitExpr, 1);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003076 return S.ExprError();
3077
3078 case OR_Deleted:
3079 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003080 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003081 << CurInitExpr->getSourceRange();
3082 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3083 << Best->Function->isDeleted();
3084 return S.ExprError();
3085 }
3086
3087 CurInit.release();
3088 return S.BuildCXXConstructExpr(Loc, CurInitExpr->getType(),
3089 cast<CXXConstructorDecl>(Best->Function),
3090 /*Elidable=*/true,
3091 Sema::MultiExprArg(S,
3092 (void**)&CurInitExpr, 1));
3093}
Douglas Gregor20093b42009-12-09 23:02:17 +00003094
3095Action::OwningExprResult
3096InitializationSequence::Perform(Sema &S,
3097 const InitializedEntity &Entity,
3098 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +00003099 Action::MultiExprArg Args,
3100 QualType *ResultType) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003101 if (SequenceKind == FailedSequence) {
3102 unsigned NumArgs = Args.size();
3103 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
3104 return S.ExprError();
3105 }
3106
3107 if (SequenceKind == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00003108 // If the declaration is a non-dependent, incomplete array type
3109 // that has an initializer, then its type will be completed once
3110 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00003111 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00003112 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003113 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003114 if (const IncompleteArrayType *ArrayT
3115 = S.Context.getAsIncompleteArrayType(DeclType)) {
3116 // FIXME: We don't currently have the ability to accurately
3117 // compute the length of an initializer list without
3118 // performing full type-checking of the initializer list
3119 // (since we have to determine where braces are implicitly
3120 // introduced and such). So, we fall back to making the array
3121 // type a dependently-sized array type with no specified
3122 // bound.
3123 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
3124 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00003125
Douglas Gregord87b61f2009-12-10 17:56:55 +00003126 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00003127 if (DeclaratorDecl *DD = Entity.getDecl()) {
3128 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
3129 TypeLoc TL = TInfo->getTypeLoc();
3130 if (IncompleteArrayTypeLoc *ArrayLoc
3131 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
3132 Brackets = ArrayLoc->getBracketsRange();
3133 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00003134 }
3135
3136 *ResultType
3137 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
3138 /*NumElts=*/0,
3139 ArrayT->getSizeModifier(),
3140 ArrayT->getIndexTypeCVRQualifiers(),
3141 Brackets);
3142 }
3143
3144 }
3145 }
3146
Eli Friedman08544622009-12-22 02:35:53 +00003147 if (Kind.getKind() == InitializationKind::IK_Copy || Kind.isExplicitCast())
Douglas Gregor20093b42009-12-09 23:02:17 +00003148 return Sema::OwningExprResult(S, Args.release()[0]);
3149
3150 unsigned NumArgs = Args.size();
3151 return S.Owned(new (S.Context) ParenListExpr(S.Context,
3152 SourceLocation(),
3153 (Expr **)Args.release(),
3154 NumArgs,
3155 SourceLocation()));
3156 }
3157
Douglas Gregor99a2e602009-12-16 01:38:02 +00003158 if (SequenceKind == NoInitialization)
3159 return S.Owned((Expr *)0);
3160
Douglas Gregord6542d82009-12-22 15:35:07 +00003161 QualType DestType = Entity.getType().getNonReferenceType();
3162 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00003163 // the same as Entity.getDecl()->getType() in cases involving type merging,
3164 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00003165 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00003166 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00003167 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003168
Douglas Gregor99a2e602009-12-16 01:38:02 +00003169 Sema::OwningExprResult CurInit = S.Owned((Expr *)0);
3170
3171 assert(!Steps.empty() && "Cannot have an empty initialization sequence");
3172
3173 // For initialization steps that start with a single initializer,
3174 // grab the only argument out the Args and place it into the "current"
3175 // initializer.
3176 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003177 case SK_ResolveAddressOfOverloadedFunction:
3178 case SK_CastDerivedToBaseRValue:
3179 case SK_CastDerivedToBaseLValue:
3180 case SK_BindReference:
3181 case SK_BindReferenceToTemporary:
3182 case SK_UserConversion:
3183 case SK_QualificationConversionLValue:
3184 case SK_QualificationConversionRValue:
3185 case SK_ConversionSequence:
3186 case SK_ListInitialization:
3187 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003188 case SK_StringInit:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003189 assert(Args.size() == 1);
3190 CurInit = Sema::OwningExprResult(S, ((Expr **)(Args.get()))[0]->Retain());
3191 if (CurInit.isInvalid())
3192 return S.ExprError();
3193 break;
3194
3195 case SK_ConstructorInitialization:
3196 case SK_ZeroInitialization:
3197 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003198 }
3199
3200 // Walk through the computed steps for the initialization sequence,
3201 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00003202 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003203 for (step_iterator Step = step_begin(), StepEnd = step_end();
3204 Step != StepEnd; ++Step) {
3205 if (CurInit.isInvalid())
3206 return S.ExprError();
3207
3208 Expr *CurInitExpr = (Expr *)CurInit.get();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003209 QualType SourceType = CurInitExpr? CurInitExpr->getType() : QualType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003210
3211 switch (Step->Kind) {
3212 case SK_ResolveAddressOfOverloadedFunction:
3213 // Overload resolution determined which function invoke; update the
3214 // initializer to reflect that choice.
3215 CurInit = S.FixOverloadedFunctionReference(move(CurInit), Step->Function);
3216 break;
3217
3218 case SK_CastDerivedToBaseRValue:
3219 case SK_CastDerivedToBaseLValue: {
3220 // We have a derived-to-base cast that produces either an rvalue or an
3221 // lvalue. Perform that cast.
3222
3223 // Casts to inaccessible base classes are allowed with C-style casts.
3224 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
3225 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
3226 CurInitExpr->getLocStart(),
3227 CurInitExpr->getSourceRange(),
3228 IgnoreBaseAccess))
3229 return S.ExprError();
3230
3231 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(Step->Type,
3232 CastExpr::CK_DerivedToBase,
3233 (Expr*)CurInit.release(),
3234 Step->Kind == SK_CastDerivedToBaseLValue));
3235 break;
3236 }
3237
3238 case SK_BindReference:
3239 if (FieldDecl *BitField = CurInitExpr->getBitField()) {
3240 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
3241 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00003242 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00003243 << BitField->getDeclName()
3244 << CurInitExpr->getSourceRange();
3245 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
3246 return S.ExprError();
3247 }
3248
3249 // Reference binding does not have any corresponding ASTs.
3250
3251 // Check exception specifications
3252 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3253 return S.ExprError();
3254 break;
3255
3256 case SK_BindReferenceToTemporary:
3257 // Check exception specifications
3258 if (S.CheckExceptionSpecCompatibility(CurInitExpr, DestType))
3259 return S.ExprError();
3260
3261 // FIXME: At present, we have no AST to describe when we need to make a
3262 // temporary to bind a reference to. We should.
3263 break;
3264
3265 case SK_UserConversion: {
3266 // We have a user-defined conversion that invokes either a constructor
3267 // or a conversion function.
3268 CastExpr::CastKind CastKind = CastExpr::CK_Unknown;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003269 bool IsCopy = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003270 if (CXXConstructorDecl *Constructor
3271 = dyn_cast<CXXConstructorDecl>(Step->Function)) {
3272 // Build a call to the selected constructor.
3273 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3274 SourceLocation Loc = CurInitExpr->getLocStart();
3275 CurInit.release(); // Ownership transferred into MultiExprArg, below.
3276
3277 // Determine the arguments required to actually perform the constructor
3278 // call.
3279 if (S.CompleteConstructorCall(Constructor,
3280 Sema::MultiExprArg(S,
3281 (void **)&CurInitExpr,
3282 1),
3283 Loc, ConstructorArgs))
3284 return S.ExprError();
3285
3286 // Build the an expression that constructs a temporary.
3287 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
3288 move_arg(ConstructorArgs));
3289 if (CurInit.isInvalid())
3290 return S.ExprError();
3291
3292 CastKind = CastExpr::CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003293 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
3294 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
3295 S.IsDerivedFrom(SourceType, Class))
3296 IsCopy = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00003297 } else {
3298 // Build a call to the conversion function.
3299 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Step->Function);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003300
Douglas Gregor20093b42009-12-09 23:02:17 +00003301 // FIXME: Should we move this initialization into a separate
3302 // derived-to-base conversion? I believe the answer is "no", because
3303 // we don't want to turn off access control here for c-style casts.
3304 if (S.PerformObjectArgumentInitialization(CurInitExpr, Conversion))
3305 return S.ExprError();
3306
3307 // Do a little dance to make sure that CurInit has the proper
3308 // pointer.
3309 CurInit.release();
3310
3311 // Build the actual call to the conversion function.
3312 CurInit = S.Owned(S.BuildCXXMemberCallExpr(CurInitExpr, Conversion));
3313 if (CurInit.isInvalid() || !CurInit.get())
3314 return S.ExprError();
3315
3316 CastKind = CastExpr::CK_UserDefinedConversion;
3317 }
3318
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003319 if (shouldBindAsTemporary(Entity, IsCopy))
3320 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3321
Douglas Gregor20093b42009-12-09 23:02:17 +00003322 CurInitExpr = CurInit.takeAs<Expr>();
3323 CurInit = S.Owned(new (S.Context) ImplicitCastExpr(CurInitExpr->getType(),
3324 CastKind,
3325 CurInitExpr,
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003326 false));
3327
3328 if (!IsCopy)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003329 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor20093b42009-12-09 23:02:17 +00003330 break;
3331 }
3332
3333 case SK_QualificationConversionLValue:
3334 case SK_QualificationConversionRValue:
3335 // Perform a qualification conversion; these can never go wrong.
3336 S.ImpCastExprToType(CurInitExpr, Step->Type,
3337 CastExpr::CK_NoOp,
3338 Step->Kind == SK_QualificationConversionLValue);
3339 CurInit.release();
3340 CurInit = S.Owned(CurInitExpr);
3341 break;
3342
3343 case SK_ConversionSequence:
Douglas Gregor68647482009-12-16 03:45:30 +00003344 if (S.PerformImplicitConversion(CurInitExpr, Step->Type, Sema::AA_Converting,
Douglas Gregor20093b42009-12-09 23:02:17 +00003345 false, false, *Step->ICS))
3346 return S.ExprError();
3347
3348 CurInit.release();
3349 CurInit = S.Owned(CurInitExpr);
3350 break;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003351
3352 case SK_ListInitialization: {
3353 InitListExpr *InitList = cast<InitListExpr>(CurInitExpr);
3354 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00003355 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
Douglas Gregord87b61f2009-12-10 17:56:55 +00003356 return S.ExprError();
3357
3358 CurInit.release();
3359 CurInit = S.Owned(InitList);
3360 break;
3361 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00003362
3363 case SK_ConstructorInitialization: {
3364 CXXConstructorDecl *Constructor
3365 = cast<CXXConstructorDecl>(Step->Function);
3366
3367 // Build a call to the selected constructor.
3368 ASTOwningVector<&ActionBase::DeleteExpr> ConstructorArgs(S);
3369 SourceLocation Loc = Kind.getLocation();
3370
3371 // Determine the arguments required to actually perform the constructor
3372 // call.
3373 if (S.CompleteConstructorCall(Constructor, move(Args),
3374 Loc, ConstructorArgs))
3375 return S.ExprError();
3376
3377 // Build the an expression that constructs a temporary.
Douglas Gregord6542d82009-12-22 15:35:07 +00003378 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
Douglas Gregor745880f2009-12-20 22:01:25 +00003379 Constructor,
Douglas Gregor16006c92009-12-16 18:50:27 +00003380 move_arg(ConstructorArgs),
3381 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003382 if (CurInit.isInvalid())
3383 return S.ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003384
3385 bool Elidable
3386 = cast<CXXConstructExpr>((Expr *)CurInit.get())->isElidable();
3387 if (shouldBindAsTemporary(Entity, Elidable))
3388 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
3389
3390 if (!Elidable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003391 CurInit = CopyIfRequiredForEntity(S, Entity, Kind, move(CurInit));
Douglas Gregor51c56d62009-12-14 20:49:26 +00003392 break;
3393 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003394
3395 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00003396 step_iterator NextStep = Step;
3397 ++NextStep;
3398 if (NextStep != StepEnd &&
3399 NextStep->Kind == SK_ConstructorInitialization) {
3400 // The need for zero-initialization is recorded directly into
3401 // the call to the object's constructor within the next step.
3402 ConstructorInitRequiresZeroInit = true;
3403 } else if (Kind.getKind() == InitializationKind::IK_Value &&
3404 S.getLangOptions().CPlusPlus &&
3405 !Kind.isImplicitValueInit()) {
Douglas Gregor71d17402009-12-15 00:01:57 +00003406 CurInit = S.Owned(new (S.Context) CXXZeroInitValueExpr(Step->Type,
3407 Kind.getRange().getBegin(),
3408 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00003409 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00003410 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00003411 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003412 break;
3413 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003414
3415 case SK_CAssignment: {
3416 QualType SourceType = CurInitExpr->getType();
3417 Sema::AssignConvertType ConvTy =
3418 S.CheckSingleAssignmentConstraints(Step->Type, CurInitExpr);
Douglas Gregoraa037312009-12-22 07:24:36 +00003419
3420 // If this is a call, allow conversion to a transparent union.
3421 if (ConvTy != Sema::Compatible &&
3422 Entity.getKind() == InitializedEntity::EK_Parameter &&
3423 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExpr)
3424 == Sema::Compatible)
3425 ConvTy = Sema::Compatible;
3426
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003427 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
3428 Step->Type, SourceType,
3429 CurInitExpr, getAssignmentAction(Entity)))
3430 return S.ExprError();
3431
3432 CurInit.release();
3433 CurInit = S.Owned(CurInitExpr);
3434 break;
3435 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003436
3437 case SK_StringInit: {
3438 QualType Ty = Step->Type;
3439 CheckStringInit(CurInitExpr, ResultType ? *ResultType : Ty, S);
3440 break;
3441 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003442 }
3443 }
3444
3445 return move(CurInit);
3446}
3447
3448//===----------------------------------------------------------------------===//
3449// Diagnose initialization failures
3450//===----------------------------------------------------------------------===//
3451bool InitializationSequence::Diagnose(Sema &S,
3452 const InitializedEntity &Entity,
3453 const InitializationKind &Kind,
3454 Expr **Args, unsigned NumArgs) {
3455 if (SequenceKind != FailedSequence)
3456 return false;
3457
Douglas Gregord6542d82009-12-22 15:35:07 +00003458 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003459 switch (Failure) {
3460 case FK_TooManyInitsForReference:
3461 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
3462 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
3463 break;
3464
3465 case FK_ArrayNeedsInitList:
3466 case FK_ArrayNeedsInitListOrStringLiteral:
3467 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
3468 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
3469 break;
3470
3471 case FK_AddressOfOverloadFailed:
3472 S.ResolveAddressOfOverloadedFunction(Args[0],
3473 DestType.getNonReferenceType(),
3474 true);
3475 break;
3476
3477 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00003478 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00003479 switch (FailedOverloadResult) {
3480 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003481 if (Failure == FK_UserConversionOverloadFailed)
3482 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
3483 << Args[0]->getType() << DestType
3484 << Args[0]->getSourceRange();
3485 else
3486 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
3487 << DestType << Args[0]->getType()
3488 << Args[0]->getSourceRange();
3489
John McCallcbce6062010-01-12 07:18:19 +00003490 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_ViableCandidates,
3491 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003492 break;
3493
3494 case OR_No_Viable_Function:
3495 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
3496 << Args[0]->getType() << DestType.getNonReferenceType()
3497 << Args[0]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00003498 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3499 Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00003500 break;
3501
3502 case OR_Deleted: {
3503 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
3504 << Args[0]->getType() << DestType.getNonReferenceType()
3505 << Args[0]->getSourceRange();
3506 OverloadCandidateSet::iterator Best;
3507 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3508 Kind.getLocation(),
3509 Best);
3510 if (Ovl == OR_Deleted) {
3511 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3512 << Best->Function->isDeleted();
3513 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003514 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00003515 }
3516 break;
3517 }
3518
3519 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00003520 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00003521 break;
3522 }
3523 break;
3524
3525 case FK_NonConstLValueReferenceBindingToTemporary:
3526 case FK_NonConstLValueReferenceBindingToUnrelated:
3527 S.Diag(Kind.getLocation(),
3528 Failure == FK_NonConstLValueReferenceBindingToTemporary
3529 ? diag::err_lvalue_reference_bind_to_temporary
3530 : diag::err_lvalue_reference_bind_to_unrelated)
3531 << DestType.getNonReferenceType()
3532 << Args[0]->getType()
3533 << Args[0]->getSourceRange();
3534 break;
3535
3536 case FK_RValueReferenceBindingToLValue:
3537 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
3538 << Args[0]->getSourceRange();
3539 break;
3540
3541 case FK_ReferenceInitDropsQualifiers:
3542 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
3543 << DestType.getNonReferenceType()
3544 << Args[0]->getType()
3545 << Args[0]->getSourceRange();
3546 break;
3547
3548 case FK_ReferenceInitFailed:
3549 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
3550 << DestType.getNonReferenceType()
3551 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3552 << Args[0]->getType()
3553 << Args[0]->getSourceRange();
3554 break;
3555
3556 case FK_ConversionFailed:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003557 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
3558 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00003559 << DestType
3560 << (Args[0]->isLvalue(S.Context) == Expr::LV_Valid)
3561 << Args[0]->getType()
3562 << Args[0]->getSourceRange();
Douglas Gregord87b61f2009-12-10 17:56:55 +00003563 break;
3564
3565 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003566 SourceRange R;
3567
3568 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
3569 R = SourceRange(InitList->getInit(1)->getLocStart(),
3570 InitList->getLocEnd());
3571 else
3572 R = SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00003573
3574 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
Douglas Gregor99a2e602009-12-16 01:38:02 +00003575 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00003576 break;
3577 }
3578
3579 case FK_ReferenceBindingToInitList:
3580 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
3581 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
3582 break;
3583
3584 case FK_InitListBadDestinationType:
3585 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
3586 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
3587 break;
Douglas Gregor51c56d62009-12-14 20:49:26 +00003588
3589 case FK_ConstructorOverloadFailed: {
3590 SourceRange ArgsRange;
3591 if (NumArgs)
3592 ArgsRange = SourceRange(Args[0]->getLocStart(),
3593 Args[NumArgs - 1]->getLocEnd());
3594
3595 // FIXME: Using "DestType" for the entity we're printing is probably
3596 // bad.
3597 switch (FailedOverloadResult) {
3598 case OR_Ambiguous:
3599 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
3600 << DestType << ArgsRange;
John McCall81201622010-01-08 04:41:39 +00003601 S.PrintOverloadCandidates(FailedCandidateSet,
John McCallcbce6062010-01-12 07:18:19 +00003602 Sema::OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003603 break;
3604
3605 case OR_No_Viable_Function:
3606 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
3607 << DestType << ArgsRange;
John McCallcbce6062010-01-12 07:18:19 +00003608 S.PrintOverloadCandidates(FailedCandidateSet, Sema::OCD_AllCandidates,
3609 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003610 break;
3611
3612 case OR_Deleted: {
3613 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
3614 << true << DestType << ArgsRange;
3615 OverloadCandidateSet::iterator Best;
3616 OverloadingResult Ovl = S.BestViableFunction(FailedCandidateSet,
3617 Kind.getLocation(),
3618 Best);
3619 if (Ovl == OR_Deleted) {
3620 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
3621 << Best->Function->isDeleted();
3622 } else {
3623 llvm_unreachable("Inconsistent overload resolution?");
3624 }
3625 break;
3626 }
3627
3628 case OR_Success:
3629 llvm_unreachable("Conversion did not fail!");
3630 break;
3631 }
3632 break;
3633 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003634
3635 case FK_DefaultInitOfConst:
3636 S.Diag(Kind.getLocation(), diag::err_default_init_const)
3637 << DestType;
3638 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00003639 }
3640
3641 return true;
3642}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003643
3644//===----------------------------------------------------------------------===//
3645// Initialization helper functions
3646//===----------------------------------------------------------------------===//
3647Sema::OwningExprResult
3648Sema::PerformCopyInitialization(const InitializedEntity &Entity,
3649 SourceLocation EqualLoc,
3650 OwningExprResult Init) {
3651 if (Init.isInvalid())
3652 return ExprError();
3653
3654 Expr *InitE = (Expr *)Init.get();
3655 assert(InitE && "No initialization expression?");
3656
3657 if (EqualLoc.isInvalid())
3658 EqualLoc = InitE->getLocStart();
3659
3660 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
3661 EqualLoc);
3662 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
3663 Init.release();
3664 return Seq.Perform(*this, Entity, Kind,
3665 MultiExprArg(*this, (void**)&InitE, 1));
3666}