blob: f710380720d00d1530723cd608935ea4807605ec [file] [log] [blame]
Steve Narofff8ecff22008-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//
Rafael Espindola699fc4d2011-07-14 22:58:04 +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.
Chris Lattner0cb78032009-02-24 22:27:37 +000013//
Steve Narofff8ecff22008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall8b0666c2010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall83024632010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner5029d562010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Narofff8ecff22008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson98cee2f2009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattnerd8b741c82009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregor1b303932009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskina6667812011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregor85df8d82009-01-29 00:45:39 +000028#include <map>
Douglas Gregore4a0bb72009-01-22 00:58:24 +000029using namespace clang;
Steve Narofff8ecff22008-05-01 22:18:59 +000030
Chris Lattner0cb78032009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCall66884dd2011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman893abe42009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattnera9196812009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump11289f42009-09-09 15:08:12 +000042
Chris Lattnera9196812009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner012b3392009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedman42a84652009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregorfb65e592011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedman42a84652009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregorfb65e592011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattnera9196812009-02-26 23:26:43 +000071
Douglas Gregorfb65e592011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump11289f42009-09-09 15:08:12 +000074
Douglas Gregorfb65e592011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattner0cb78032009-02-24 22:27:37 +000076}
77
John McCall66884dd2011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCall5decec92011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattnerd8b741c82009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump11289f42009-09-09 15:08:12 +000091
Chris Lattner0cb78032009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump11289f42009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattner0cb78032009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner94e6c4b2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattner0cb78032009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCallc5b82252009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner94e6c4b2009-02-24 23:01:39 +0000101 return;
Chris Lattner0cb78032009-02-24 22:27:37 +0000102 }
Mike Stump11289f42009-09-09 15:08:12 +0000103
Eli Friedman893abe42009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump11289f42009-09-09 15:08:12 +0000105
Eli Friedman554eba92011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman893abe42009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedman554eba92011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssond162fb82011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedman554eba92011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump11289f42009-09-09 15:08:12 +0000131
Eli Friedman893abe42009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattner0cb78032009-02-24 22:27:37 +0000137}
138
Chris Lattner0cb78032009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregorcde232f2009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara92141d22011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregorcde232f2009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner9ececce2009-02-24 22:48:58 +0000170namespace {
Douglas Gregor85df8d82009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregor85df8d82009-01-29 00:45:39 +0000173 bool hadError;
174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump11289f42009-09-09 15:08:12 +0000176
Anders Carlsson6cabf312010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000180 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000181 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType &T,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000183 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000186 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000188 bool SubobjectIsDesignatorContext,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000189 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000191 unsigned &StructuredIndex,
192 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000193 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000194 InitListExpr *IList, QualType ElemType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000198 void CheckComplexType(const InitializedEntity &Entity,
199 InitListExpr *IList, QualType DeclType,
200 unsigned &Index,
201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000203 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000204 InitListExpr *IList, QualType DeclType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000205 unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000206 InitListExpr *StructuredList,
207 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000208 void CheckReferenceType(const InitializedEntity &Entity,
209 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000210 unsigned &Index,
211 InitListExpr *StructuredList,
212 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000213 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000214 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000215 InitListExpr *StructuredList,
216 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000217 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000218 InitListExpr *IList, QualType DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000219 RecordDecl::field_iterator Field,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000220 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000221 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000222 unsigned &StructuredIndex,
223 bool TopLevelObject = false);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000224 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000225 InitListExpr *IList, QualType &DeclType,
Mike Stump11289f42009-09-09 15:08:12 +0000226 llvm::APSInt elementIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000227 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregorcde232f2009-01-29 01:05:33 +0000228 InitListExpr *StructuredList,
229 unsigned &StructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +0000230 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +0000231 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +0000232 unsigned DesigIdx,
Mike Stump11289f42009-09-09 15:08:12 +0000233 QualType &CurrentObjectType,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000234 RecordDecl::field_iterator *NextField,
235 llvm::APSInt *NextElementIndex,
236 unsigned &Index,
237 InitListExpr *StructuredList,
238 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000239 bool FinishSubobjectInit,
240 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000241 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
242 QualType CurrentObjectType,
243 InitListExpr *StructuredList,
244 unsigned StructuredIndex,
245 SourceRange InitRange);
Douglas Gregorcde232f2009-01-29 01:05:33 +0000246 void UpdateStructuredListElement(InitListExpr *StructuredList,
247 unsigned &StructuredIndex,
Douglas Gregor85df8d82009-01-29 00:45:39 +0000248 Expr *expr);
249 int numArrayElements(QualType DeclType);
250 int numStructUnionElements(QualType DeclType);
Douglas Gregord14247a2009-01-30 22:09:00 +0000251
Douglas Gregor2bb07652009-12-22 00:05:34 +0000252 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
253 const InitializedEntity &ParentEntity,
254 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregor723796a2009-12-16 06:35:08 +0000255 void FillInValueInitializations(const InitializedEntity &Entity,
256 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedman3fa64df2011-08-23 22:24:57 +0000257 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
258 Expr *InitExpr, FieldDecl *Field,
259 bool TopLevelObject);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000260public:
Douglas Gregor723796a2009-12-16 06:35:08 +0000261 InitListChecker(Sema &S, const InitializedEntity &Entity,
262 InitListExpr *IL, QualType &T);
Douglas Gregor85df8d82009-01-29 00:45:39 +0000263 bool HadError() { return hadError; }
264
265 // @brief Retrieves the fully-structured initializer list used for
266 // semantic analysis and code generation.
267 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
268};
Chris Lattner9ececce2009-02-24 22:48:58 +0000269} // end anonymous namespace
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000270
Douglas Gregor2bb07652009-12-22 00:05:34 +0000271void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
272 const InitializedEntity &ParentEntity,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000273 InitListExpr *ILE,
Douglas Gregor2bb07652009-12-22 00:05:34 +0000274 bool &RequiresSecondPass) {
275 SourceLocation Loc = ILE->getSourceRange().getBegin();
276 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277 InitializedEntity MemberEntity
Douglas Gregor2bb07652009-12-22 00:05:34 +0000278 = InitializedEntity::InitializeMember(Field, &ParentEntity);
279 if (Init >= NumInits || !ILE->getInit(Init)) {
280 // FIXME: We probably don't need to handle references
281 // specially here, since value-initialization of references is
282 // handled in InitializationSequence.
283 if (Field->getType()->isReferenceType()) {
284 // C++ [dcl.init.aggr]p9:
285 // If an incomplete or empty initializer-list leaves a
286 // member of reference type uninitialized, the program is
287 // ill-formed.
288 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
289 << Field->getType()
290 << ILE->getSyntacticForm()->getSourceRange();
291 SemaRef.Diag(Field->getLocation(),
292 diag::note_uninit_reference_member);
293 hadError = true;
294 return;
295 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000296
Douglas Gregor2bb07652009-12-22 00:05:34 +0000297 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
298 true);
299 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
300 if (!InitSeq) {
301 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
302 hadError = true;
303 return;
304 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000305
John McCalldadc5752010-08-24 06:29:42 +0000306 ExprResult MemberInit
John McCallfaf5fb42010-08-26 23:41:50 +0000307 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000308 if (MemberInit.isInvalid()) {
309 hadError = true;
310 return;
311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000312
Douglas Gregor2bb07652009-12-22 00:05:34 +0000313 if (hadError) {
314 // Do nothing
315 } else if (Init < NumInits) {
316 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redld201edf2011-06-05 13:59:11 +0000317 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000318 // Value-initialization requires a constructor call, so
319 // extend the initializer list to include the constructor
320 // call and make a note that we'll need to take another pass
321 // through the initializer list.
Ted Kremenekac034612010-04-13 23:39:13 +0000322 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregor2bb07652009-12-22 00:05:34 +0000323 RequiresSecondPass = true;
324 }
325 } else if (InitListExpr *InnerILE
326 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000327 FillInValueInitializations(MemberEntity, InnerILE,
328 RequiresSecondPass);
Douglas Gregor2bb07652009-12-22 00:05:34 +0000329}
330
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000331/// Recursively replaces NULL values within the given initializer list
332/// with expressions that perform value-initialization of the
333/// appropriate type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000334void
Douglas Gregor723796a2009-12-16 06:35:08 +0000335InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
336 InitListExpr *ILE,
337 bool &RequiresSecondPass) {
Mike Stump11289f42009-09-09 15:08:12 +0000338 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregord14247a2009-01-30 22:09:00 +0000339 "Should not have void type");
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000340 SourceLocation Loc = ILE->getSourceRange().getBegin();
341 if (ILE->getSyntacticForm())
342 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump11289f42009-09-09 15:08:12 +0000343
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000344 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregor2bb07652009-12-22 00:05:34 +0000345 if (RType->getDecl()->isUnion() &&
346 ILE->getInitializedFieldInUnion())
347 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
348 Entity, ILE, RequiresSecondPass);
349 else {
350 unsigned Init = 0;
351 for (RecordDecl::field_iterator
352 Field = RType->getDecl()->field_begin(),
353 FieldEnd = RType->getDecl()->field_end();
354 Field != FieldEnd; ++Field) {
355 if (Field->isUnnamedBitfield())
356 continue;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000357
Douglas Gregor2bb07652009-12-22 00:05:34 +0000358 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000359 return;
Douglas Gregor2bb07652009-12-22 00:05:34 +0000360
361 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
362 if (hadError)
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000363 return;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000364
Douglas Gregor2bb07652009-12-22 00:05:34 +0000365 ++Init;
Douglas Gregor723796a2009-12-16 06:35:08 +0000366
Douglas Gregor2bb07652009-12-22 00:05:34 +0000367 // Only look at the first initialization of a union.
368 if (RType->getDecl()->isUnion())
369 break;
370 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000371 }
372
373 return;
Mike Stump11289f42009-09-09 15:08:12 +0000374 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000375
376 QualType ElementType;
Mike Stump11289f42009-09-09 15:08:12 +0000377
Douglas Gregor723796a2009-12-16 06:35:08 +0000378 InitializedEntity ElementEntity = Entity;
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000379 unsigned NumInits = ILE->getNumInits();
380 unsigned NumElements = NumInits;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000381 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000382 ElementType = AType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000383 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
384 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000386 0, Entity);
John McCall9dd450b2009-09-21 23:43:11 +0000387 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000388 ElementType = VType->getElementType();
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000389 NumElements = VType->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregor723796a2009-12-16 06:35:08 +0000391 0, Entity);
Mike Stump11289f42009-09-09 15:08:12 +0000392 } else
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000393 ElementType = ILE->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000394
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000395
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000396 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000397 if (hadError)
398 return;
399
Anders Carlssoned8d80d2010-01-23 04:34:47 +0000400 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
401 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregor723796a2009-12-16 06:35:08 +0000402 ElementEntity.setElementIndex(Init);
403
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000404 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregor723796a2009-12-16 06:35:08 +0000405 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
406 true);
407 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
408 if (!InitSeq) {
409 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000410 hadError = true;
411 return;
412 }
413
John McCalldadc5752010-08-24 06:29:42 +0000414 ExprResult ElementInit
John McCallfaf5fb42010-08-26 23:41:50 +0000415 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregor723796a2009-12-16 06:35:08 +0000416 if (ElementInit.isInvalid()) {
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000417 hadError = true;
Douglas Gregor723796a2009-12-16 06:35:08 +0000418 return;
419 }
420
421 if (hadError) {
422 // Do nothing
423 } else if (Init < NumInits) {
Argyrios Kyrtzidis446bcf22011-04-21 20:03:38 +0000424 // For arrays, just set the expression used for value-initialization
425 // of the "holes" in the array.
426 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
427 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
428 else
429 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000430 } else {
431 // For arrays, just set the expression used for value-initialization
432 // of the rest of elements and exit.
433 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
434 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
435 return;
436 }
437
Sebastian Redld201edf2011-06-05 13:59:11 +0000438 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000439 // Value-initialization requires a constructor call, so
440 // extend the initializer list to include the constructor
441 // call and make a note that we'll need to take another pass
442 // through the initializer list.
443 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
444 RequiresSecondPass = true;
445 }
Douglas Gregor723796a2009-12-16 06:35:08 +0000446 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000447 } else if (InitListExpr *InnerILE
Douglas Gregor723796a2009-12-16 06:35:08 +0000448 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
449 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000450 }
451}
452
Chris Lattnerd9ae05b2009-01-29 05:10:57 +0000453
Douglas Gregor723796a2009-12-16 06:35:08 +0000454InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
455 InitListExpr *IL, QualType &T)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000456 : SemaRef(S) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000457 hadError = false;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000458
Eli Friedman23a9e312008-05-19 19:16:24 +0000459 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000460 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000461 FullyStructuredList
Douglas Gregor5741efb2009-03-01 17:12:46 +0000462 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000463 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlssond0849252010-01-23 19:55:29 +0000464 FullyStructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000465 /*TopLevelObject=*/true);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000466
Douglas Gregor723796a2009-12-16 06:35:08 +0000467 if (!hadError) {
468 bool RequiresSecondPass = false;
469 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor4f4b1862009-12-16 18:50:27 +0000470 if (RequiresSecondPass && !hadError)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000471 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregor723796a2009-12-16 06:35:08 +0000472 RequiresSecondPass);
473 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000474}
475
476int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman85f54972008-05-25 13:22:35 +0000477 // FIXME: use a proper constant
478 int maxElements = 0x7FFFFFFF;
Chris Lattner7adf0762008-08-04 07:31:14 +0000479 if (const ConstantArrayType *CAT =
Chris Lattnerb0912a52009-02-24 22:50:46 +0000480 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Narofff8ecff22008-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 Kremenekc23c7e62009-07-29 21:53:49 +0000487 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000488 int InitializableMembers = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000489 for (RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000490 Field = structDecl->field_begin(),
491 FieldEnd = structDecl->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000492 Field != FieldEnd; ++Field) {
493 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
494 ++InitializableMembers;
495 }
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +0000496 if (structDecl->isUnion())
Eli Friedman0e56c822008-05-25 14:03:31 +0000497 return std::min(InitializableMembers, 1);
498 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Narofff8ecff22008-05-01 22:18:59 +0000499}
500
Anders Carlsson6cabf312010-01-23 23:23:01 +0000501void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000502 InitListExpr *ParentIList,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000503 QualType T, unsigned &Index,
504 InitListExpr *StructuredList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000505 unsigned &StructuredIndex) {
Steve Narofff8ecff22008-05-01 22:18:59 +0000506 int maxElements = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Steve Narofff8ecff22008-05-01 22:18:59 +0000508 if (T->isArrayType())
509 maxElements = numArrayElements(T);
Douglas Gregor8385a062010-04-26 21:31:17 +0000510 else if (T->isRecordType())
Steve Narofff8ecff22008-05-01 22:18:59 +0000511 maxElements = numStructUnionElements(T);
Eli Friedman23a9e312008-05-19 19:16:24 +0000512 else if (T->isVectorType())
John McCall9dd450b2009-09-21 23:43:11 +0000513 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Narofff8ecff22008-05-01 22:18:59 +0000514 else
David Blaikie83d382b2011-09-23 05:06:16 +0000515 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedman23a9e312008-05-19 19:16:24 +0000516
Eli Friedmane0f832b2008-05-25 13:49:22 +0000517 if (maxElements == 0) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000518 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedmane0f832b2008-05-25 13:49:22 +0000519 diag::err_implicit_empty_initializer);
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000520 ++Index;
Eli Friedmane0f832b2008-05-25 13:49:22 +0000521 hadError = true;
522 return;
523 }
524
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000525 // Build a structured initializer list corresponding to this subobject.
526 InitListExpr *StructuredSubobjectInitList
Mike Stump11289f42009-09-09 15:08:12 +0000527 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
528 StructuredIndex,
Douglas Gregor5741efb2009-03-01 17:12:46 +0000529 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
530 ParentIList->getSourceRange().getEnd()));
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000531 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedman23a9e312008-05-19 19:16:24 +0000532
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000533 // Check the element types and build the structural subobject.
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000534 unsigned StartIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000535 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlssondbb25a32010-01-23 20:47:59 +0000536 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump11289f42009-09-09 15:08:12 +0000537 StructuredSubobjectInitList,
Eli Friedmanc616c5f2011-08-23 20:17:13 +0000538 StructuredSubobjectInitIndex);
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000539 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregor07d8e3a2009-03-20 00:32:56 +0000540 StructuredSubobjectInitList->setType(T);
541
Douglas Gregor5741efb2009-03-01 17:12:46 +0000542 // Update the structured sub-object initializer so that it's ending
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000543 // range corresponds with the end of the last initializer it used.
544 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump11289f42009-09-09 15:08:12 +0000545 SourceLocation EndLoc
Douglas Gregora5c9e1a2009-02-02 17:43:21 +0000546 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
547 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000549
Tanya Lattner5029d562010-03-07 04:17:15 +0000550 // Warn about missing braces.
551 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner5cbff482010-03-07 04:40:06 +0000552 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
553 diag::warn_missing_braces)
Tanya Lattner5029d562010-03-07 04:17:15 +0000554 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregora771f462010-03-31 17:46:05 +0000556 "{")
557 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregora771f462010-03-31 17:46:05 +0000559 "}");
Tanya Lattner5029d562010-03-07 04:17:15 +0000560 }
Steve Narofff8ecff22008-05-01 22:18:59 +0000561}
562
Anders Carlsson6cabf312010-01-23 23:23:01 +0000563void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000564 InitListExpr *IList, QualType &T,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000565 unsigned &Index,
566 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000567 unsigned &StructuredIndex,
568 bool TopLevelObject) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000569 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000570 SyntacticToSemantic[IList] = StructuredList;
571 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlssond0849252010-01-23 19:55:29 +0000573 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregora8a089b2010-07-13 18:40:04 +0000574 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
575 IList->setType(ExprTy);
576 StructuredList->setType(ExprTy);
Eli Friedman85f54972008-05-25 13:22:35 +0000577 if (hadError)
578 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000579
Eli Friedman85f54972008-05-25 13:22:35 +0000580 if (Index < IList->getNumInits()) {
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000581 // We have leftover initializers
Eli Friedmanbd327452009-05-29 20:20:05 +0000582 if (StructuredIndex == 1 &&
583 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000584 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000585 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000586 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmanbd327452009-05-29 20:20:05 +0000587 hadError = true;
588 }
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000589 // Special-case
Chris Lattnerb0912a52009-02-24 22:50:46 +0000590 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerf490e152008-11-19 05:27:50 +0000591 << IList->getInit(Index)->getSourceRange();
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000592 } else if (!T->isIncompleteType()) {
Douglas Gregord42a0fb2009-01-30 22:26:29 +0000593 // Don't complain for incomplete types, since we'll get an error
594 // elsewhere
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000595 QualType CurrentObjectType = StructuredList->getType();
Mike Stump11289f42009-09-09 15:08:12 +0000596 int initKind =
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000597 CurrentObjectType->isArrayType()? 0 :
598 CurrentObjectType->isVectorType()? 1 :
599 CurrentObjectType->isScalarType()? 2 :
600 CurrentObjectType->isUnionType()? 3 :
601 4;
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000602
603 unsigned DK = diag::warn_excess_initializers;
Eli Friedmanbd327452009-05-29 20:20:05 +0000604 if (SemaRef.getLangOptions().CPlusPlus) {
605 DK = diag::err_excess_initializers;
606 hadError = true;
607 }
Nate Begeman425038c2009-07-07 21:53:06 +0000608 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
609 DK = diag::err_excess_initializers;
610 hadError = true;
611 }
Douglas Gregor1cba5fe2009-02-18 22:23:55 +0000612
Chris Lattnerb0912a52009-02-24 22:50:46 +0000613 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000614 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000615 }
616 }
Eli Friedman6fcdec22008-05-19 20:20:43 +0000617
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000618 if (T->isScalarType() && IList->getNumInits() == 1 && !TopLevelObject)
Chris Lattnerb0912a52009-02-24 22:50:46 +0000619 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregor170512f2009-04-01 23:51:29 +0000620 << IList->getSourceRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000621 << FixItHint::CreateRemoval(IList->getLocStart())
622 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Narofff8ecff22008-05-01 22:18:59 +0000623}
624
Anders Carlsson6cabf312010-01-23 23:23:01 +0000625void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000626 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000627 QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000628 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000629 unsigned &Index,
630 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000631 unsigned &StructuredIndex,
632 bool TopLevelObject) {
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000633 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
634 // Explicitly braced initializer for complex type can be real+imaginary
635 // parts.
636 CheckComplexType(Entity, IList, DeclType, Index,
637 StructuredList, StructuredIndex);
638 } else if (DeclType->isScalarType()) {
Anders Carlssond0849252010-01-23 19:55:29 +0000639 CheckScalarType(Entity, IList, DeclType, Index,
640 StructuredList, StructuredIndex);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000641 } else if (DeclType->isVectorType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlssond0849252010-01-23 19:55:29 +0000643 StructuredList, StructuredIndex);
Douglas Gregorddb24852009-01-30 17:31:00 +0000644 } else if (DeclType->isAggregateType()) {
645 if (DeclType->isRecordType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000646 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson73eb7cd2010-01-23 20:20:40 +0000647 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000648 SubobjectIsDesignatorContext, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +0000649 StructuredList, StructuredIndex,
650 TopLevelObject);
Douglas Gregord7fb85e2009-01-22 23:26:18 +0000651 } else if (DeclType->isArrayType()) {
Douglas Gregor033d1252009-01-23 16:54:12 +0000652 llvm::APSInt Zero(
Chris Lattnerb0912a52009-02-24 22:50:46 +0000653 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregor033d1252009-01-23 16:54:12 +0000654 false);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000655 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson0cf999b2010-01-23 20:13:41 +0000656 SubobjectIsDesignatorContext, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000657 StructuredList, StructuredIndex);
Mike Stump12b8ce12009-08-04 21:02:39 +0000658 } else
David Blaikie83d382b2011-09-23 05:06:16 +0000659 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroffeaf58532008-08-10 16:05:48 +0000660 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
661 // This type is invalid, issue a diagnostic.
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000662 ++Index;
Chris Lattnerb0912a52009-02-24 22:50:46 +0000663 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000664 << DeclType;
Eli Friedmand0e48ea2008-05-20 05:25:56 +0000665 hadError = true;
Douglas Gregord14247a2009-01-30 22:09:00 +0000666 } else if (DeclType->isRecordType()) {
667 // C++ [dcl.init]p14:
668 // [...] If the class is an aggregate (8.5.1), and the initializer
669 // is a brace-enclosed list, see 8.5.1.
670 //
671 // Note: 8.5.1 is handled below; here, we diagnose the case where
672 // we have an initializer list and a destination type that is not
673 // an aggregate.
674 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattnerb0912a52009-02-24 22:50:46 +0000675 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000676 << DeclType << IList->getSourceRange();
677 hadError = true;
678 } else if (DeclType->isReferenceType()) {
Anders Carlsson6cabf312010-01-23 23:23:01 +0000679 CheckReferenceType(Entity, IList, DeclType, Index,
680 StructuredList, StructuredIndex);
John McCall8b07ec22010-05-15 11:32:37 +0000681 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000682 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
683 << DeclType;
684 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000685 } else {
Douglas Gregor50ec46d2010-05-03 18:24:37 +0000686 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
687 << DeclType;
688 hadError = true;
Steve Narofff8ecff22008-05-01 22:18:59 +0000689 }
690}
691
Anders Carlsson6cabf312010-01-23 23:23:01 +0000692void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000693 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +0000694 QualType ElemType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000695 unsigned &Index,
696 InitListExpr *StructuredList,
697 unsigned &StructuredIndex) {
Douglas Gregorf6d27522009-01-29 00:39:20 +0000698 Expr *expr = IList->getInit(Index);
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000699 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
700 unsigned newIndex = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000701 unsigned newStructuredIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000702 InitListExpr *newStructuredList
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000703 = getStructuredSubobjectInit(IList, Index, ElemType,
704 StructuredList, StructuredIndex,
705 SubInitList->getSourceRange());
Anders Carlssond0849252010-01-23 19:55:29 +0000706 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000707 newStructuredList, newStructuredIndex);
708 ++StructuredIndex;
709 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000710 return;
Eli Friedman5a36d3f2008-05-19 20:00:43 +0000711 } else if (ElemType->isScalarType()) {
John McCall5decec92011-02-21 07:57:55 +0000712 return CheckScalarType(Entity, IList, ElemType, Index,
713 StructuredList, StructuredIndex);
Douglas Gregord14247a2009-01-30 22:09:00 +0000714 } else if (ElemType->isReferenceType()) {
John McCall5decec92011-02-21 07:57:55 +0000715 return CheckReferenceType(Entity, IList, ElemType, Index,
716 StructuredList, StructuredIndex);
717 }
Anders Carlsson03068aa2009-08-27 17:18:13 +0000718
John McCall5decec92011-02-21 07:57:55 +0000719 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
720 // arrayType can be incomplete if we're initializing a flexible
721 // array member. There's nothing we can do with the completed
722 // type here, though.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723
John McCall5decec92011-02-21 07:57:55 +0000724 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
725 CheckStringInit(Str, ElemType, arrayType, SemaRef);
726 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregord14247a2009-01-30 22:09:00 +0000727 ++Index;
John McCall5decec92011-02-21 07:57:55 +0000728 return;
Douglas Gregord14247a2009-01-30 22:09:00 +0000729 }
John McCall5decec92011-02-21 07:57:55 +0000730
731 // Fall through for subaggregate initialization.
732
733 } else if (SemaRef.getLangOptions().CPlusPlus) {
734 // C++ [dcl.init.aggr]p12:
735 // All implicit type conversions (clause 4) are considered when
Rafael Espindola699fc4d2011-07-14 22:58:04 +0000736 // initializing the aggregate member with an ini- tializer from
John McCall5decec92011-02-21 07:57:55 +0000737 // an initializer-list. If the initializer can initialize a
738 // member, the member is initialized. [...]
739
740 // FIXME: Better EqualLoc?
741 InitializationKind Kind =
742 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
743 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
744
745 if (Seq) {
746 ExprResult Result =
747 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
748 if (Result.isInvalid())
749 hadError = true;
750
751 UpdateStructuredListElement(StructuredList, StructuredIndex,
752 Result.takeAs<Expr>());
753 ++Index;
754 return;
755 }
756
757 // Fall through for subaggregate initialization
758 } else {
759 // C99 6.7.8p13:
760 //
761 // The initializer for a structure or union object that has
762 // automatic storage duration shall be either an initializer
763 // list as described below, or a single expression that has
764 // compatible structure or union type. In the latter case, the
765 // initial value of the object, including unnamed members, is
766 // that of the expression.
John Wiegley01296292011-04-08 18:41:53 +0000767 ExprResult ExprRes = SemaRef.Owned(expr);
John McCall5decec92011-02-21 07:57:55 +0000768 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley01296292011-04-08 18:41:53 +0000769 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCall5decec92011-02-21 07:57:55 +0000770 == Sema::Compatible) {
John Wiegley01296292011-04-08 18:41:53 +0000771 if (ExprRes.isInvalid())
772 hadError = true;
773 else {
774 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
775 if (ExprRes.isInvalid())
776 hadError = true;
777 }
778 UpdateStructuredListElement(StructuredList, StructuredIndex,
779 ExprRes.takeAs<Expr>());
John McCall5decec92011-02-21 07:57:55 +0000780 ++Index;
781 return;
782 }
John Wiegley01296292011-04-08 18:41:53 +0000783 ExprRes.release();
John McCall5decec92011-02-21 07:57:55 +0000784 // Fall through for subaggregate initialization
785 }
786
787 // C++ [dcl.init.aggr]p12:
788 //
789 // [...] Otherwise, if the member is itself a non-empty
790 // subaggregate, brace elision is assumed and the initializer is
791 // considered for the initialization of the first member of
792 // the subaggregate.
Tanya Lattner83559382011-07-15 23:07:01 +0000793 if (!SemaRef.getLangOptions().OpenCL &&
794 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCall5decec92011-02-21 07:57:55 +0000795 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
796 StructuredIndex);
797 ++StructuredIndex;
798 } else {
799 // We cannot initialize this element, so let
800 // PerformCopyInitialization produce the appropriate diagnostic.
801 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000802 SemaRef.Owned(expr),
803 /*TopLevelOfInitList=*/true);
John McCall5decec92011-02-21 07:57:55 +0000804 hadError = true;
805 ++Index;
806 ++StructuredIndex;
Douglas Gregord14247a2009-01-30 22:09:00 +0000807 }
Eli Friedman23a9e312008-05-19 19:16:24 +0000808}
809
Eli Friedman6b9c41e2011-09-19 23:17:44 +0000810void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
811 InitListExpr *IList, QualType DeclType,
812 unsigned &Index,
813 InitListExpr *StructuredList,
814 unsigned &StructuredIndex) {
815 assert(Index == 0 && "Index in explicit init list must be zero");
816
817 // As an extension, clang supports complex initializers, which initialize
818 // a complex number component-wise. When an explicit initializer list for
819 // a complex number contains two two initializers, this extension kicks in:
820 // it exepcts the initializer list to contain two elements convertible to
821 // the element type of the complex type. The first element initializes
822 // the real part, and the second element intitializes the imaginary part.
823
824 if (IList->getNumInits() != 2)
825 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
826 StructuredIndex);
827
828 // This is an extension in C. (The builtin _Complex type does not exist
829 // in the C++ standard.)
830 if (!SemaRef.getLangOptions().CPlusPlus)
831 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
832 << IList->getSourceRange();
833
834 // Initialize the complex number.
835 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
836 InitializedEntity ElementEntity =
837 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
838
839 for (unsigned i = 0; i < 2; ++i) {
840 ElementEntity.setElementIndex(Index);
841 CheckSubElementType(ElementEntity, IList, elementType, Index,
842 StructuredList, StructuredIndex);
843 }
844}
845
846
Anders Carlsson6cabf312010-01-23 23:23:01 +0000847void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000848 InitListExpr *IList, QualType DeclType,
Douglas Gregorf6d27522009-01-29 00:39:20 +0000849 unsigned &Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000850 InitListExpr *StructuredList,
851 unsigned &StructuredIndex) {
John McCall643169b2010-11-11 00:46:36 +0000852 if (Index >= IList->getNumInits()) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000853 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerf490e152008-11-19 05:27:50 +0000854 << IList->getSourceRange();
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000855 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000856 ++Index;
857 ++StructuredIndex;
Eli Friedmanfeb4cc12008-05-19 20:12:18 +0000858 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000859 }
John McCall643169b2010-11-11 00:46:36 +0000860
861 Expr *expr = IList->getInit(Index);
862 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
863 SemaRef.Diag(SubIList->getLocStart(),
864 diag::warn_many_braces_around_scalar_init)
865 << SubIList->getSourceRange();
866
867 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
868 StructuredIndex);
869 return;
870 } else if (isa<DesignatedInitExpr>(expr)) {
871 SemaRef.Diag(expr->getSourceRange().getBegin(),
872 diag::err_designator_for_scalar_init)
873 << DeclType << expr->getSourceRange();
874 hadError = true;
875 ++Index;
876 ++StructuredIndex;
877 return;
878 }
879
880 ExprResult Result =
881 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000882 SemaRef.Owned(expr),
883 /*TopLevelOfInitList=*/true);
John McCall643169b2010-11-11 00:46:36 +0000884
885 Expr *ResultExpr = 0;
886
887 if (Result.isInvalid())
888 hadError = true; // types weren't compatible.
889 else {
890 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000891
John McCall643169b2010-11-11 00:46:36 +0000892 if (ResultExpr != expr) {
893 // The type was promoted, update initializer list.
894 IList->setInit(Index, ResultExpr);
895 }
896 }
897 if (hadError)
898 ++StructuredIndex;
899 else
900 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
901 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +0000902}
903
Anders Carlsson6cabf312010-01-23 23:23:01 +0000904void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
905 InitListExpr *IList, QualType DeclType,
Douglas Gregord14247a2009-01-30 22:09:00 +0000906 unsigned &Index,
907 InitListExpr *StructuredList,
908 unsigned &StructuredIndex) {
909 if (Index < IList->getNumInits()) {
910 Expr *expr = IList->getInit(Index);
911 if (isa<InitListExpr>(expr)) {
Chris Lattnerb0912a52009-02-24 22:50:46 +0000912 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregord14247a2009-01-30 22:09:00 +0000913 << DeclType << IList->getSourceRange();
914 hadError = true;
915 ++Index;
916 ++StructuredIndex;
917 return;
Mike Stump11289f42009-09-09 15:08:12 +0000918 }
Douglas Gregord14247a2009-01-30 22:09:00 +0000919
John McCalldadc5752010-08-24 06:29:42 +0000920 ExprResult Result =
Anders Carlssona91be642010-01-29 02:47:33 +0000921 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000922 SemaRef.Owned(expr),
923 /*TopLevelOfInitList=*/true);
Anders Carlssona91be642010-01-29 02:47:33 +0000924
925 if (Result.isInvalid())
Douglas Gregord14247a2009-01-30 22:09:00 +0000926 hadError = true;
Anders Carlssona91be642010-01-29 02:47:33 +0000927
928 expr = Result.takeAs<Expr>();
929 IList->setInit(Index, expr);
930
Douglas Gregord14247a2009-01-30 22:09:00 +0000931 if (hadError)
932 ++StructuredIndex;
933 else
934 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
935 ++Index;
936 } else {
Mike Stump87c57ac2009-05-16 07:39:55 +0000937 // FIXME: It would be wonderful if we could point at the actual member. In
938 // general, it would be useful to pass location information down the stack,
939 // so that we know the location (or decl) of the "current object" being
940 // initialized.
Mike Stump11289f42009-09-09 15:08:12 +0000941 SemaRef.Diag(IList->getLocStart(),
Douglas Gregord14247a2009-01-30 22:09:00 +0000942 diag::err_init_reference_member_uninitialized)
943 << DeclType
944 << IList->getSourceRange();
945 hadError = true;
946 ++Index;
947 ++StructuredIndex;
948 return;
949 }
950}
951
Anders Carlsson6cabf312010-01-23 23:23:01 +0000952void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlssond0849252010-01-23 19:55:29 +0000953 InitListExpr *IList, QualType DeclType,
Douglas Gregor347f7ea2009-01-28 21:54:33 +0000954 unsigned &Index,
955 InitListExpr *StructuredList,
956 unsigned &StructuredIndex) {
John McCall6a16b2f2010-10-30 00:11:39 +0000957 if (Index >= IList->getNumInits())
958 return;
Mike Stump11289f42009-09-09 15:08:12 +0000959
John McCall6a16b2f2010-10-30 00:11:39 +0000960 const VectorType *VT = DeclType->getAs<VectorType>();
961 unsigned maxElements = VT->getNumElements();
962 unsigned numEltsInit = 0;
963 QualType elementType = VT->getElementType();
Anders Carlssond0849252010-01-23 19:55:29 +0000964
John McCall6a16b2f2010-10-30 00:11:39 +0000965 if (!SemaRef.getLangOptions().OpenCL) {
966 // If the initializing element is a vector, try to copy-initialize
967 // instead of breaking it apart (which is doomed to failure anyway).
968 Expr *Init = IList->getInit(Index);
969 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
970 ExprResult Result =
971 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskina6667812011-07-26 23:20:30 +0000972 SemaRef.Owned(Init),
973 /*TopLevelOfInitList=*/true);
John McCall6a16b2f2010-10-30 00:11:39 +0000974
975 Expr *ResultExpr = 0;
976 if (Result.isInvalid())
977 hadError = true; // types weren't compatible.
978 else {
979 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000980
John McCall6a16b2f2010-10-30 00:11:39 +0000981 if (ResultExpr != Init) {
982 // The type was promoted, update initializer list.
983 IList->setInit(Index, ResultExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +0000984 }
985 }
John McCall6a16b2f2010-10-30 00:11:39 +0000986 if (hadError)
987 ++StructuredIndex;
988 else
989 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
990 ++Index;
991 return;
Steve Narofff8ecff22008-05-01 22:18:59 +0000992 }
Mike Stump11289f42009-09-09 15:08:12 +0000993
John McCall6a16b2f2010-10-30 00:11:39 +0000994 InitializedEntity ElementEntity =
995 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
John McCall6a16b2f2010-10-30 00:11:39 +0000997 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
998 // Don't attempt to go past the end of the init list
999 if (Index >= IList->getNumInits())
1000 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001001
John McCall6a16b2f2010-10-30 00:11:39 +00001002 ElementEntity.setElementIndex(Index);
1003 CheckSubElementType(ElementEntity, IList, elementType, Index,
1004 StructuredList, StructuredIndex);
1005 }
1006 return;
Steve Narofff8ecff22008-05-01 22:18:59 +00001007 }
John McCall6a16b2f2010-10-30 00:11:39 +00001008
1009 InitializedEntity ElementEntity =
1010 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001011
John McCall6a16b2f2010-10-30 00:11:39 +00001012 // OpenCL initializers allows vectors to be constructed from vectors.
1013 for (unsigned i = 0; i < maxElements; ++i) {
1014 // Don't attempt to go past the end of the init list
1015 if (Index >= IList->getNumInits())
1016 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001017
John McCall6a16b2f2010-10-30 00:11:39 +00001018 ElementEntity.setElementIndex(Index);
1019
1020 QualType IType = IList->getInit(Index)->getType();
1021 if (!IType->isVectorType()) {
1022 CheckSubElementType(ElementEntity, IList, elementType, Index,
1023 StructuredList, StructuredIndex);
1024 ++numEltsInit;
1025 } else {
1026 QualType VecType;
1027 const VectorType *IVT = IType->getAs<VectorType>();
1028 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001029
John McCall6a16b2f2010-10-30 00:11:39 +00001030 if (IType->isExtVectorType())
1031 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1032 else
1033 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001034 IVT->getVectorKind());
John McCall6a16b2f2010-10-30 00:11:39 +00001035 CheckSubElementType(ElementEntity, IList, VecType, Index,
1036 StructuredList, StructuredIndex);
1037 numEltsInit += numIElts;
1038 }
1039 }
1040
1041 // OpenCL requires all elements to be initialized.
1042 if (numEltsInit != maxElements)
1043 if (SemaRef.getLangOptions().OpenCL)
1044 SemaRef.Diag(IList->getSourceRange().getBegin(),
1045 diag::err_vector_incorrect_num_initializers)
1046 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Narofff8ecff22008-05-01 22:18:59 +00001047}
1048
Anders Carlsson6cabf312010-01-23 23:23:01 +00001049void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001050 InitListExpr *IList, QualType &DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001051 llvm::APSInt elementIndex,
Mike Stump11289f42009-09-09 15:08:12 +00001052 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001053 unsigned &Index,
1054 InitListExpr *StructuredList,
1055 unsigned &StructuredIndex) {
John McCall66884dd2011-02-21 07:22:22 +00001056 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1057
Steve Narofff8ecff22008-05-01 22:18:59 +00001058 // Check for the special-case of initializing an array with a string.
1059 if (Index < IList->getNumInits()) {
John McCall66884dd2011-02-21 07:22:22 +00001060 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattnerd8b741c82009-02-24 23:10:27 +00001061 SemaRef.Context)) {
John McCall5decec92011-02-21 07:57:55 +00001062 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001063 // We place the string literal directly into the resulting
1064 // initializer list. This is the only place where the structure
1065 // of the structured initializer list doesn't match exactly,
1066 // because doing so would involve allocating one character
1067 // constant for each string.
Chris Lattneredbf3ba2009-02-24 22:41:04 +00001068 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattnerb0912a52009-02-24 22:50:46 +00001069 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001070 ++Index;
Steve Narofff8ecff22008-05-01 22:18:59 +00001071 return;
1072 }
1073 }
John McCall66884dd2011-02-21 07:22:22 +00001074 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman85f54972008-05-25 13:22:35 +00001075 // Check for VLAs; in standard C it would be possible to check this
1076 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1077 // them in all sorts of strange places).
Chris Lattnerb0912a52009-02-24 22:50:46 +00001078 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001079 diag::err_variable_object_no_init)
1080 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman85f54972008-05-25 13:22:35 +00001081 hadError = true;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001082 ++Index;
1083 ++StructuredIndex;
Eli Friedman85f54972008-05-25 13:22:35 +00001084 return;
1085 }
1086
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001087 // We might know the maximum number of elements in advance.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001088 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1089 elementIndex.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001090 bool maxElementsKnown = false;
John McCall66884dd2011-02-21 07:22:22 +00001091 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001092 maxElements = CAT->getSize();
Jay Foad6d4db0c2010-12-07 08:25:34 +00001093 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001094 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001095 maxElementsKnown = true;
1096 }
1097
John McCall66884dd2011-02-21 07:22:22 +00001098 QualType elementType = arrayType->getElementType();
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001099 while (Index < IList->getNumInits()) {
1100 Expr *Init = IList->getInit(Index);
1101 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001102 // If we're not the subobject that matches up with the '{' for
1103 // the designator, we shouldn't be handling the
1104 // designator. Return immediately.
1105 if (!SubobjectIsDesignatorContext)
1106 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001107
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001108 // Handle this designated initializer. elementIndex will be
1109 // updated to be the next array element we'll initialize.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001110 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001111 DeclType, 0, &elementIndex, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001112 StructuredList, StructuredIndex, true,
1113 false)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001114 hadError = true;
1115 continue;
1116 }
1117
Douglas Gregor033d1252009-01-23 16:54:12 +00001118 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001119 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregor033d1252009-01-23 16:54:12 +00001120 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001121 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001122 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor033d1252009-01-23 16:54:12 +00001123
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001124 // If the array is of incomplete type, keep track of the number of
1125 // elements in the initializer.
1126 if (!maxElementsKnown && elementIndex > maxElements)
1127 maxElements = elementIndex;
1128
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001129 continue;
1130 }
1131
1132 // If we know the maximum number of elements, and we've already
1133 // hit it, stop consuming elements in the initializer list.
1134 if (maxElementsKnown && elementIndex == maxElements)
Steve Narofff8ecff22008-05-01 22:18:59 +00001135 break;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001136
Anders Carlsson6cabf312010-01-23 23:23:01 +00001137 InitializedEntity ElementEntity =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001138 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001139 Entity);
1140 // Check this element.
1141 CheckSubElementType(ElementEntity, IList, elementType, Index,
1142 StructuredList, StructuredIndex);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001143 ++elementIndex;
1144
1145 // If the array is of incomplete type, keep track of the number of
1146 // elements in the initializer.
1147 if (!maxElementsKnown && elementIndex > maxElements)
1148 maxElements = elementIndex;
Steve Narofff8ecff22008-05-01 22:18:59 +00001149 }
Eli Friedmanbe7e42b2009-05-29 20:17:55 +00001150 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Narofff8ecff22008-05-01 22:18:59 +00001151 // If this is an incomplete array type, the actual type needs to
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001152 // be calculated here.
Douglas Gregor583cf0a2009-01-23 18:58:42 +00001153 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001154 if (maxElements == Zero) {
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001155 // Sizing an array implicitly to zero is not allowed by ISO C,
1156 // but is supported by GNU.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001157 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001158 diag::ext_typecheck_zero_array_size);
Steve Narofff8ecff22008-05-01 22:18:59 +00001159 }
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001160
Mike Stump11289f42009-09-09 15:08:12 +00001161 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbaraa64b7e2008-08-18 20:28:46 +00001162 ArrayType::Normal, 0);
Steve Narofff8ecff22008-05-01 22:18:59 +00001163 }
1164}
1165
Eli Friedman3fa64df2011-08-23 22:24:57 +00001166bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1167 Expr *InitExpr,
1168 FieldDecl *Field,
1169 bool TopLevelObject) {
1170 // Handle GNU flexible array initializers.
1171 unsigned FlexArrayDiag;
1172 if (isa<InitListExpr>(InitExpr) &&
1173 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1174 // Empty flexible array init always allowed as an extension
1175 FlexArrayDiag = diag::ext_flexible_array_init;
1176 } else if (SemaRef.getLangOptions().CPlusPlus) {
1177 // Disallow flexible array init in C++; it is not required for gcc
1178 // compatibility, and it needs work to IRGen correctly in general.
1179 FlexArrayDiag = diag::err_flexible_array_init;
1180 } else if (!TopLevelObject) {
1181 // Disallow flexible array init on non-top-level object
1182 FlexArrayDiag = diag::err_flexible_array_init;
1183 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1184 // Disallow flexible array init on anything which is not a variable.
1185 FlexArrayDiag = diag::err_flexible_array_init;
1186 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1187 // Disallow flexible array init on local variables.
1188 FlexArrayDiag = diag::err_flexible_array_init;
1189 } else {
1190 // Allow other cases.
1191 FlexArrayDiag = diag::ext_flexible_array_init;
1192 }
1193
1194 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1195 FlexArrayDiag)
1196 << InitExpr->getSourceRange().getBegin();
1197 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1198 << Field;
1199
1200 return FlexArrayDiag != diag::ext_flexible_array_init;
1201}
1202
Anders Carlsson6cabf312010-01-23 23:23:01 +00001203void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson73eb7cd2010-01-23 20:20:40 +00001204 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001205 QualType DeclType,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001206 RecordDecl::field_iterator Field,
Mike Stump11289f42009-09-09 15:08:12 +00001207 bool SubobjectIsDesignatorContext,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001208 unsigned &Index,
1209 InitListExpr *StructuredList,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001210 unsigned &StructuredIndex,
1211 bool TopLevelObject) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001212 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001213
Eli Friedman23a9e312008-05-19 19:16:24 +00001214 // If the record is invalid, some of it's members are invalid. To avoid
1215 // confusion, we forgo checking the intializer for the entire record.
1216 if (structDecl->isInvalidDecl()) {
1217 hadError = true;
1218 return;
Mike Stump11289f42009-09-09 15:08:12 +00001219 }
Douglas Gregor0202cb42009-01-29 17:44:32 +00001220
1221 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1222 // Value-initialize the first named member of the union.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001223 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001224 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor0202cb42009-01-29 17:44:32 +00001225 Field != FieldEnd; ++Field) {
1226 if (Field->getDeclName()) {
1227 StructuredList->setInitializedFieldInUnion(*Field);
1228 break;
1229 }
1230 }
1231 return;
1232 }
1233
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001234 // If structDecl is a forward declaration, this loop won't do
1235 // anything except look at designated initializers; That's okay,
1236 // because an error should get printed out elsewhere. It might be
1237 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001238 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001239 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregora9add4e2009-02-12 19:00:39 +00001240 bool InitializedSomething = false;
John McCalle40b58e2010-03-11 19:32:38 +00001241 bool CheckForMissingFields = true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001242 while (Index < IList->getNumInits()) {
1243 Expr *Init = IList->getInit(Index);
1244
1245 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001246 // If we're not the subobject that matches up with the '{' for
1247 // the designator, we shouldn't be handling the
1248 // designator. Return immediately.
1249 if (!SubobjectIsDesignatorContext)
1250 return;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001251
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001252 // Handle this designated initializer. Field will be updated to
1253 // the next field that we'll be initializing.
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001254 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001255 DeclType, &Field, 0, Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001256 StructuredList, StructuredIndex,
1257 true, TopLevelObject))
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001258 hadError = true;
1259
Douglas Gregora9add4e2009-02-12 19:00:39 +00001260 InitializedSomething = true;
John McCalle40b58e2010-03-11 19:32:38 +00001261
1262 // Disable check for missing fields when designators are used.
1263 // This matches gcc behaviour.
1264 CheckForMissingFields = false;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001265 continue;
1266 }
1267
1268 if (Field == FieldEnd) {
1269 // We've run out of fields. We're done.
1270 break;
1271 }
1272
Douglas Gregora9add4e2009-02-12 19:00:39 +00001273 // We've already initialized a member of a union. We're done.
1274 if (InitializedSomething && DeclType->isUnionType())
1275 break;
1276
Douglas Gregor91f84212008-12-11 16:49:14 +00001277 // If we've hit the flexible array member at the end, we're done.
1278 if (Field->getType()->isIncompleteArrayType())
1279 break;
1280
Douglas Gregor51695702009-01-29 16:53:55 +00001281 if (Field->isUnnamedBitfield()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001282 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001283 ++Field;
Eli Friedman23a9e312008-05-19 19:16:24 +00001284 continue;
Steve Narofff8ecff22008-05-01 22:18:59 +00001285 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001286
Douglas Gregora82064c2011-06-29 21:51:31 +00001287 // Make sure we can use this declaration.
1288 if (SemaRef.DiagnoseUseOfDecl(*Field,
1289 IList->getInit(Index)->getLocStart())) {
1290 ++Index;
1291 ++Field;
1292 hadError = true;
1293 continue;
1294 }
1295
Anders Carlsson6cabf312010-01-23 23:23:01 +00001296 InitializedEntity MemberEntity =
1297 InitializedEntity::InitializeMember(*Field, &Entity);
1298 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1299 StructuredList, StructuredIndex);
Douglas Gregora9add4e2009-02-12 19:00:39 +00001300 InitializedSomething = true;
Douglas Gregor51695702009-01-29 16:53:55 +00001301
1302 if (DeclType->isUnionType()) {
1303 // Initialize the first field within the union.
1304 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor51695702009-01-29 16:53:55 +00001305 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001306
1307 ++Field;
Steve Narofff8ecff22008-05-01 22:18:59 +00001308 }
Douglas Gregor91f84212008-12-11 16:49:14 +00001309
John McCalle40b58e2010-03-11 19:32:38 +00001310 // Emit warnings for missing struct field initializers.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001311 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCalle40b58e2010-03-11 19:32:38 +00001312 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1313 // It is possible we have one or more unnamed bitfields remaining.
1314 // Find first (if any) named field and emit warning.
1315 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1316 it != end; ++it) {
1317 if (!it->isUnnamedBitfield()) {
1318 SemaRef.Diag(IList->getSourceRange().getEnd(),
1319 diag::warn_missing_field_initializers) << it->getName();
1320 break;
1321 }
1322 }
1323 }
1324
Mike Stump11289f42009-09-09 15:08:12 +00001325 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001326 Index >= IList->getNumInits())
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001327 return;
1328
Eli Friedman3fa64df2011-08-23 22:24:57 +00001329 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1330 TopLevelObject)) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001331 hadError = true;
Douglas Gregor07d8e3a2009-03-20 00:32:56 +00001332 ++Index;
1333 return;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001334 }
1335
Anders Carlsson6cabf312010-01-23 23:23:01 +00001336 InitializedEntity MemberEntity =
1337 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001338
Anders Carlsson6cabf312010-01-23 23:23:01 +00001339 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson6cabf312010-01-23 23:23:01 +00001341 StructuredList, StructuredIndex);
1342 else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlssondbb25a32010-01-23 20:47:59 +00001344 StructuredList, StructuredIndex);
Steve Narofff8ecff22008-05-01 22:18:59 +00001345}
Steve Narofff8ecff22008-05-01 22:18:59 +00001346
Douglas Gregord5846a12009-04-15 06:41:24 +00001347/// \brief Expand a field designator that refers to a member of an
1348/// anonymous struct or union into a series of field designators that
1349/// refers to the field within the appropriate subobject.
1350///
Douglas Gregord5846a12009-04-15 06:41:24 +00001351static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump11289f42009-09-09 15:08:12 +00001352 DesignatedInitExpr *DIE,
1353 unsigned DesigIdx,
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001354 IndirectFieldDecl *IndirectField) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001355 typedef DesignatedInitExpr::Designator Designator;
1356
Douglas Gregord5846a12009-04-15 06:41:24 +00001357 // Build the replacement designators.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001358 SmallVector<Designator, 4> Replacements;
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001359 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1360 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1361 if (PI + 1 == PE)
Mike Stump11289f42009-09-09 15:08:12 +00001362 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregord5846a12009-04-15 06:41:24 +00001363 DIE->getDesignator(DesigIdx)->getDotLoc(),
1364 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1365 else
1366 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1367 SourceLocation()));
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001368 assert(isa<FieldDecl>(*PI));
1369 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregord5846a12009-04-15 06:41:24 +00001370 }
1371
1372 // Expand the current designator into the set of replacement
1373 // designators, so we have a full subobject path down to where the
1374 // member of the anonymous struct/union is actually stored.
Douglas Gregor03e8bdc2010-01-06 23:17:19 +00001375 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregord5846a12009-04-15 06:41:24 +00001376 &Replacements[0] + Replacements.size());
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001377}
Mike Stump11289f42009-09-09 15:08:12 +00001378
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001379/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001380/// corresponds to FieldName.
1381static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1382 IdentifierInfo *FieldName) {
1383 assert(AnonField->isAnonymousStructOrUnion());
1384 Decl *NextDecl = AnonField->getNextDeclInContext();
1385 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1386 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1387 return IF;
1388 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregord5846a12009-04-15 06:41:24 +00001389 }
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001390 return 0;
Douglas Gregord5846a12009-04-15 06:41:24 +00001391}
1392
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001393/// @brief Check the well-formedness of a C99 designated initializer.
1394///
1395/// Determines whether the designated initializer @p DIE, which
1396/// resides at the given @p Index within the initializer list @p
1397/// IList, is well-formed for a current object of type @p DeclType
1398/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump11289f42009-09-09 15:08:12 +00001399/// within the current subobject is returned in either
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001400/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001401///
1402/// @param IList The initializer list in which this designated
1403/// initializer occurs.
1404///
Douglas Gregora5324162009-04-15 04:56:10 +00001405/// @param DIE The designated initializer expression.
1406///
1407/// @param DesigIdx The index of the current designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001408///
1409/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1410/// into which the designation in @p DIE should refer.
1411///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001412/// @param NextField If non-NULL and the first designator in @p DIE is
1413/// a field, this will be set to the field declaration corresponding
1414/// to the field named by the designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001415///
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001416/// @param NextElementIndex If non-NULL and the first designator in @p
1417/// DIE is an array designator or GNU array-range designator, this
1418/// will be set to the last index initialized by this designator.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001419///
1420/// @param Index Index into @p IList where the designated initializer
1421/// @p DIE occurs.
1422///
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001423/// @param StructuredList The initializer list expression that
1424/// describes all of the subobject initializers in the order they'll
1425/// actually be initialized.
1426///
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001427/// @returns true if there was an error, false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001428bool
Anders Carlsson6cabf312010-01-23 23:23:01 +00001429InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001430 InitListExpr *IList,
Mike Stump11289f42009-09-09 15:08:12 +00001431 DesignatedInitExpr *DIE,
Douglas Gregora5324162009-04-15 04:56:10 +00001432 unsigned DesigIdx,
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001433 QualType &CurrentObjectType,
1434 RecordDecl::field_iterator *NextField,
1435 llvm::APSInt *NextElementIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001436 unsigned &Index,
1437 InitListExpr *StructuredList,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001438 unsigned &StructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001439 bool FinishSubobjectInit,
1440 bool TopLevelObject) {
Douglas Gregora5324162009-04-15 04:56:10 +00001441 if (DesigIdx == DIE->size()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001442 // Check the actual initialization for the designated object type.
1443 bool prevHadError = hadError;
Douglas Gregorf6d27522009-01-29 00:39:20 +00001444
1445 // Temporarily remove the designator expression from the
1446 // initializer list that the child calls see, so that we don't try
1447 // to re-process the designator.
1448 unsigned OldIndex = Index;
1449 IList->setInit(OldIndex, DIE->getInit());
1450
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001451 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001452 StructuredList, StructuredIndex);
Douglas Gregorf6d27522009-01-29 00:39:20 +00001453
1454 // Restore the designated initializer expression in the syntactic
1455 // form of the initializer list.
1456 if (IList->getInit(OldIndex) != DIE->getInit())
1457 DIE->setInit(IList->getInit(OldIndex));
1458 IList->setInit(OldIndex, DIE);
1459
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001460 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001461 }
1462
Douglas Gregora5324162009-04-15 04:56:10 +00001463 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump11289f42009-09-09 15:08:12 +00001464 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001465 "Need a non-designated initializer list to start from");
1466
Douglas Gregora5324162009-04-15 04:56:10 +00001467 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001468 // Determine the structural initializer list that corresponds to the
1469 // current subobject.
1470 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump11289f42009-09-09 15:08:12 +00001471 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregor5741efb2009-03-01 17:12:46 +00001472 StructuredList, StructuredIndex,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001473 SourceRange(D->getStartLocation(),
1474 DIE->getSourceRange().getEnd()));
1475 assert(StructuredList && "Expected a structured initializer list");
1476
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001477 if (D->isFieldDesignator()) {
1478 // C99 6.7.8p7:
1479 //
1480 // If a designator has the form
1481 //
1482 // . identifier
1483 //
1484 // then the current object (defined below) shall have
1485 // structure or union type and the identifier shall be the
Mike Stump11289f42009-09-09 15:08:12 +00001486 // name of a member of that type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001487 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001488 if (!RT) {
1489 SourceLocation Loc = D->getDotLoc();
1490 if (Loc.isInvalid())
1491 Loc = D->getFieldLoc();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001492 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1493 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001494 ++Index;
1495 return true;
1496 }
1497
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001498 // Note: we perform a linear search of the fields here, despite
1499 // the fact that we have a faster lookup method, because we always
1500 // need to compute the field's index.
Douglas Gregord5846a12009-04-15 06:41:24 +00001501 FieldDecl *KnownField = D->getField();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001502 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001503 unsigned FieldIndex = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001504 RecordDecl::field_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001505 Field = RT->getDecl()->field_begin(),
1506 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001507 for (; Field != FieldEnd; ++Field) {
1508 if (Field->isUnnamedBitfield())
1509 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001510
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001511 // If we find a field representing an anonymous field, look in the
1512 // IndirectFieldDecl that follow for the designated initializer.
1513 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1514 if (IndirectFieldDecl *IF =
1515 FindIndirectFieldDesignator(*Field, FieldName)) {
1516 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1517 D = DIE->getDesignator(DesigIdx);
1518 break;
1519 }
1520 }
Douglas Gregor559c9fb2010-10-08 20:44:28 +00001521 if (KnownField && KnownField == *Field)
1522 break;
1523 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001524 break;
1525
1526 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001527 }
1528
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001529 if (Field == FieldEnd) {
Douglas Gregord5846a12009-04-15 06:41:24 +00001530 // There was no normal field in the struct with the designated
1531 // name. Perform another lookup for this name, which may find
1532 // something that we can't designate (e.g., a member function),
1533 // may find nothing, or may find a member of an anonymous
Mike Stump11289f42009-09-09 15:08:12 +00001534 // struct/union.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001535 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001536 FieldDecl *ReplacementField = 0;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001537 if (Lookup.first == Lookup.second) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001538 // Name lookup didn't find anything. Determine whether this
1539 // was a typo for another field name.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001540 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001541 Sema::LookupMemberName);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001542 TypoCorrection Corrected = SemaRef.CorrectTypo(
1543 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1544 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1545 RT->getDecl(), false, Sema::CTC_NoKeywords);
1546 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl50c68252010-08-31 00:36:30 +00001547 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001548 ->Equals(RT->getDecl())) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001549 std::string CorrectedStr(
1550 Corrected.getAsString(SemaRef.getLangOptions()));
1551 std::string CorrectedQuotedStr(
1552 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001554 diag::err_field_designator_unknown_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001555 << FieldName << CurrentObjectType << CorrectedQuotedStr
1556 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001557 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001558 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001559 } else {
1560 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1561 << FieldName << CurrentObjectType;
1562 ++Index;
1563 return true;
1564 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001566
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001567 if (!ReplacementField) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001568 // Name lookup found something, but it wasn't a field.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001569 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001570 << FieldName;
Mike Stump11289f42009-09-09 15:08:12 +00001571 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001572 diag::note_field_designator_found);
Eli Friedman8d25b092009-04-16 17:49:48 +00001573 ++Index;
1574 return true;
Douglas Gregord5846a12009-04-15 06:41:24 +00001575 }
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001576
Francois Pichetf3e5b4e2010-12-22 03:46:10 +00001577 if (!KnownField) {
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001578 // The replacement field comes from typo correction; find it
1579 // in the list of fields.
1580 FieldIndex = 0;
1581 Field = RT->getDecl()->field_begin();
1582 for (; Field != FieldEnd; ++Field) {
1583 if (Field->isUnnamedBitfield())
1584 continue;
1585
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001586 if (ReplacementField == *Field ||
Douglas Gregor4e0299b2010-01-01 00:03:05 +00001587 Field->getIdentifier() == ReplacementField->getIdentifier())
1588 break;
1589
1590 ++FieldIndex;
1591 }
1592 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001593 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001594
1595 // All of the fields of a union are located at the same place in
1596 // the initializer list.
Douglas Gregor51695702009-01-29 16:53:55 +00001597 if (RT->getDecl()->isUnion()) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001598 FieldIndex = 0;
Douglas Gregor51695702009-01-29 16:53:55 +00001599 StructuredList->setInitializedFieldInUnion(*Field);
1600 }
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001601
Douglas Gregora82064c2011-06-29 21:51:31 +00001602 // Make sure we can use this declaration.
1603 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1604 ++Index;
1605 return true;
1606 }
1607
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001608 // Update the designator with the field declaration.
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001609 D->setField(*Field);
Mike Stump11289f42009-09-09 15:08:12 +00001610
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001611 // Make sure that our non-designated initializer list has space
1612 // for a subobject corresponding to this field.
1613 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattnerb0912a52009-02-24 22:50:46 +00001614 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001615
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001616 // This designator names a flexible array member.
1617 if (Field->getType()->isIncompleteArrayType()) {
1618 bool Invalid = false;
Douglas Gregora5324162009-04-15 04:56:10 +00001619 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001620 // We can't designate an object within the flexible array
1621 // member (because GCC doesn't allow it).
Mike Stump11289f42009-09-09 15:08:12 +00001622 DesignatedInitExpr::Designator *NextD
Douglas Gregora5324162009-04-15 04:56:10 +00001623 = DIE->getDesignator(DesigIdx + 1);
Mike Stump11289f42009-09-09 15:08:12 +00001624 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001625 diag::err_designator_into_flexible_array_member)
Mike Stump11289f42009-09-09 15:08:12 +00001626 << SourceRange(NextD->getStartLocation(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001627 DIE->getSourceRange().getEnd());
Chris Lattnerb0912a52009-02-24 22:50:46 +00001628 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001629 << *Field;
1630 Invalid = true;
1631 }
1632
Chris Lattner001b29c2010-10-10 17:49:49 +00001633 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1634 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001635 // The initializer is not an initializer list.
Chris Lattnerb0912a52009-02-24 22:50:46 +00001636 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001637 diag::err_flexible_array_init_needs_braces)
1638 << DIE->getInit()->getSourceRange();
Chris Lattnerb0912a52009-02-24 22:50:46 +00001639 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001640 << *Field;
1641 Invalid = true;
1642 }
1643
Eli Friedman3fa64df2011-08-23 22:24:57 +00001644 // Check GNU flexible array initializer.
1645 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1646 TopLevelObject))
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001647 Invalid = true;
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001648
1649 if (Invalid) {
1650 ++Index;
1651 return true;
1652 }
1653
1654 // Initialize the array.
1655 bool prevHadError = hadError;
1656 unsigned newStructuredIndex = FieldIndex;
1657 unsigned OldIndex = Index;
1658 IList->setInit(Index, DIE->getInit());
Anders Carlsson6cabf312010-01-23 23:23:01 +00001659
1660 InitializedEntity MemberEntity =
1661 InitializedEntity::InitializeMember(*Field, &Entity);
1662 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001663 StructuredList, newStructuredIndex);
Anders Carlsson6cabf312010-01-23 23:23:01 +00001664
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001665 IList->setInit(OldIndex, DIE);
1666 if (hadError && !prevHadError) {
1667 ++Field;
1668 ++FieldIndex;
1669 if (NextField)
1670 *NextField = Field;
1671 StructuredIndex = FieldIndex;
1672 return true;
1673 }
1674 } else {
1675 // Recurse to check later designated subobjects.
1676 QualType FieldType = (*Field)->getType();
1677 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001678
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001679 InitializedEntity MemberEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001680 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001681 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1682 FieldType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001683 StructuredList, newStructuredIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001684 true, false))
1685 return true;
1686 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001687
1688 // Find the position of the next field to be initialized in this
1689 // subobject.
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001690 ++Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001691 ++FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001692
1693 // If this the first designator, our caller will continue checking
1694 // the rest of this struct/class/union subobject.
1695 if (IsFirstDesignator) {
1696 if (NextField)
1697 *NextField = Field;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001698 StructuredIndex = FieldIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001699 return false;
1700 }
1701
Douglas Gregor17bd0942009-01-28 23:36:17 +00001702 if (!FinishSubobjectInit)
1703 return false;
1704
Douglas Gregord5846a12009-04-15 06:41:24 +00001705 // We've already initialized something in the union; we're done.
1706 if (RT->getDecl()->isUnion())
1707 return hadError;
1708
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001709 // Check the remaining fields within this class/struct/union subobject.
1710 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001711
Anders Carlsson6cabf312010-01-23 23:23:01 +00001712 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001713 StructuredList, FieldIndex);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001714 return hadError && !prevHadError;
1715 }
1716
1717 // C99 6.7.8p6:
1718 //
1719 // If a designator has the form
1720 //
1721 // [ constant-expression ]
1722 //
1723 // then the current object (defined below) shall have array
1724 // type and the expression shall be an integer constant
1725 // expression. If the array is of unknown size, any
1726 // nonnegative value is valid.
1727 //
1728 // Additionally, cope with the GNU extension that permits
1729 // designators of the form
1730 //
1731 // [ constant-expression ... constant-expression ]
Chris Lattnerb0912a52009-02-24 22:50:46 +00001732 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001733 if (!AT) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001734 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001735 << CurrentObjectType;
1736 ++Index;
1737 return true;
1738 }
1739
1740 Expr *IndexExpr = 0;
Douglas Gregor17bd0942009-01-28 23:36:17 +00001741 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1742 if (D->isArrayDesignator()) {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001743 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001744 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001745 DesignatedEndIndex = DesignatedStartIndex;
1746 } else {
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001747 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor17bd0942009-01-28 23:36:17 +00001748
Mike Stump11289f42009-09-09 15:08:12 +00001749 DesignatedStartIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001750 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001751 DesignatedEndIndex =
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001752 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001753 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor17bd0942009-01-28 23:36:17 +00001754
Chris Lattnerb0ed51d2011-02-19 22:28:58 +00001755 // Codegen can't handle evaluating array range designators that have side
1756 // effects, because we replicate the AST value for each initialized element.
1757 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1758 // elements with something that has a side effect, so codegen can emit an
1759 // "error unsupported" error instead of miscompiling the app.
1760 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1761 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregorbf7207a2009-01-29 19:42:23 +00001762 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001763 }
1764
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001765 if (isa<ConstantArrayType>(AT)) {
1766 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad6d4db0c2010-12-07 08:25:34 +00001767 DesignatedStartIndex
1768 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001769 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad6d4db0c2010-12-07 08:25:34 +00001770 DesignatedEndIndex
1771 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001772 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1773 if (DesignatedEndIndex >= MaxElements) {
Chris Lattnerb0912a52009-02-24 22:50:46 +00001774 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001775 diag::err_array_designator_too_large)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001776 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001777 << IndexExpr->getSourceRange();
1778 ++Index;
1779 return true;
1780 }
Douglas Gregor17bd0942009-01-28 23:36:17 +00001781 } else {
1782 // Make sure the bit-widths and signedness match.
1783 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001784 DesignatedEndIndex
1785 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001786 else if (DesignatedStartIndex.getBitWidth() <
1787 DesignatedEndIndex.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00001788 DesignatedStartIndex
1789 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor17bd0942009-01-28 23:36:17 +00001790 DesignatedStartIndex.setIsUnsigned(true);
1791 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001792 }
Mike Stump11289f42009-09-09 15:08:12 +00001793
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001794 // Make sure that our non-designated initializer list has space
1795 // for a subobject corresponding to this array element.
Douglas Gregor17bd0942009-01-28 23:36:17 +00001796 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump11289f42009-09-09 15:08:12 +00001797 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor17bd0942009-01-28 23:36:17 +00001798 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001799
Douglas Gregor17bd0942009-01-28 23:36:17 +00001800 // Repeatedly perform subobject initializations in the range
1801 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001802
Douglas Gregor17bd0942009-01-28 23:36:17 +00001803 // Move to the next designator
1804 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1805 unsigned OldIndex = Index;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001806
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001807 InitializedEntity ElementEntity =
Anders Carlsson6cabf312010-01-23 23:23:01 +00001808 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001809
Douglas Gregor17bd0942009-01-28 23:36:17 +00001810 while (DesignatedStartIndex <= DesignatedEndIndex) {
1811 // Recurse to check later designated subobjects.
1812 QualType ElementType = AT->getElementType();
1813 Index = OldIndex;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001815 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001816 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1817 ElementType, 0, 0, Index,
Anders Carlsson3fa93b72010-01-23 22:49:02 +00001818 StructuredList, ElementIndex,
Douglas Gregorfc4f8a12009-02-04 22:46:25 +00001819 (DesignatedStartIndex == DesignatedEndIndex),
1820 false))
Douglas Gregor17bd0942009-01-28 23:36:17 +00001821 return true;
1822
1823 // Move to the next index in the array that we'll be initializing.
1824 ++DesignatedStartIndex;
1825 ElementIndex = DesignatedStartIndex.getZExtValue();
1826 }
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001827
1828 // If this the first designator, our caller will continue checking
1829 // the rest of this array subobject.
1830 if (IsFirstDesignator) {
1831 if (NextElementIndex)
Douglas Gregor17bd0942009-01-28 23:36:17 +00001832 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001833 StructuredIndex = ElementIndex;
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001834 return false;
1835 }
Mike Stump11289f42009-09-09 15:08:12 +00001836
Douglas Gregor17bd0942009-01-28 23:36:17 +00001837 if (!FinishSubobjectInit)
1838 return false;
1839
Douglas Gregord7fb85e2009-01-22 23:26:18 +00001840 // Check the remaining elements within this array subobject.
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001841 bool prevHadError = hadError;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001842 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson0cf999b2010-01-23 20:13:41 +00001843 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001844 StructuredList, ElementIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001845 return hadError && !prevHadError;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001846}
1847
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001848// Get the structured initializer list for a subobject of type
1849// @p CurrentObjectType.
1850InitListExpr *
1851InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1852 QualType CurrentObjectType,
1853 InitListExpr *StructuredList,
1854 unsigned StructuredIndex,
1855 SourceRange InitRange) {
1856 Expr *ExistingInit = 0;
1857 if (!StructuredList)
1858 ExistingInit = SyntacticToSemantic[IList];
1859 else if (StructuredIndex < StructuredList->getNumInits())
1860 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001862 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1863 return Result;
1864
1865 if (ExistingInit) {
1866 // We are creating an initializer list that initializes the
1867 // subobjects of the current object, but there was already an
1868 // initialization that completely initialized the current
1869 // subobject, e.g., by a compound literal:
Mike Stump11289f42009-09-09 15:08:12 +00001870 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001871 // struct X { int a, b; };
1872 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump11289f42009-09-09 15:08:12 +00001873 //
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001874 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1875 // designated initializer re-initializes the whole
1876 // subobject [0], overwriting previous initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001877 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregor5741efb2009-03-01 17:12:46 +00001878 diag::warn_subobject_initializer_overrides)
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001879 << InitRange;
Mike Stump11289f42009-09-09 15:08:12 +00001880 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001881 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001882 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001883 << ExistingInit->getSourceRange();
1884 }
1885
Mike Stump11289f42009-09-09 15:08:12 +00001886 InitListExpr *Result
Ted Kremenekac034612010-04-13 23:39:13 +00001887 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1888 InitRange.getBegin(), 0, 0,
Ted Kremenek013041e2010-02-19 01:50:18 +00001889 InitRange.getEnd());
Douglas Gregor5741efb2009-03-01 17:12:46 +00001890
Douglas Gregora8a089b2010-07-13 18:40:04 +00001891 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001892
Douglas Gregor6d00c992009-03-20 23:58:33 +00001893 // Pre-allocate storage for the structured initializer list.
1894 unsigned NumElements = 0;
Douglas Gregor221c9a52009-03-21 18:13:52 +00001895 unsigned NumInits = 0;
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001896 bool GotNumInits = false;
1897 if (!StructuredList) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001898 NumInits = IList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001899 GotNumInits = true;
1900 } else if (Index < IList->getNumInits()) {
1901 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor221c9a52009-03-21 18:13:52 +00001902 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001903 GotNumInits = true;
1904 }
Douglas Gregor221c9a52009-03-21 18:13:52 +00001905 }
1906
Mike Stump11289f42009-09-09 15:08:12 +00001907 if (const ArrayType *AType
Douglas Gregor6d00c992009-03-20 23:58:33 +00001908 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1909 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1910 NumElements = CAType->getSize().getZExtValue();
1911 // Simple heuristic so that we don't allocate a very large
1912 // initializer with many empty entries at the end.
Argyrios Kyrtzidisfddbcfb2011-04-28 18:53:55 +00001913 if (GotNumInits && NumElements > NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001914 NumElements = 0;
1915 }
John McCall9dd450b2009-09-21 23:43:11 +00001916 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregor6d00c992009-03-20 23:58:33 +00001917 NumElements = VType->getNumElements();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001918 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregor6d00c992009-03-20 23:58:33 +00001919 RecordDecl *RDecl = RType->getDecl();
1920 if (RDecl->isUnion())
1921 NumElements = 1;
1922 else
Mike Stump11289f42009-09-09 15:08:12 +00001923 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001924 RDecl->field_end());
Douglas Gregor6d00c992009-03-20 23:58:33 +00001925 }
1926
Douglas Gregor221c9a52009-03-21 18:13:52 +00001927 if (NumElements < NumInits)
Douglas Gregor6d00c992009-03-20 23:58:33 +00001928 NumElements = IList->getNumInits();
1929
Ted Kremenekac034612010-04-13 23:39:13 +00001930 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregor6d00c992009-03-20 23:58:33 +00001931
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001932 // Link this new initializer list into the structured initializer
1933 // lists.
1934 if (StructuredList)
Ted Kremenekac034612010-04-13 23:39:13 +00001935 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001936 else {
1937 Result->setSyntacticForm(IList);
1938 SyntacticToSemantic[IList] = Result;
1939 }
1940
1941 return Result;
1942}
1943
1944/// Update the initializer at index @p StructuredIndex within the
1945/// structured initializer list to the value @p expr.
1946void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1947 unsigned &StructuredIndex,
1948 Expr *expr) {
1949 // No structured initializer list to update
1950 if (!StructuredList)
1951 return;
1952
Ted Kremenekac034612010-04-13 23:39:13 +00001953 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1954 StructuredIndex, expr)) {
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001955 // This initializer overwrites a previous initializer. Warn.
Mike Stump11289f42009-09-09 15:08:12 +00001956 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001957 diag::warn_initializer_overrides)
1958 << expr->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001959 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001960 diag::note_previous_initializer)
Douglas Gregore6af7a02009-01-28 23:43:32 +00001961 << /*FIXME:has side effects=*/0
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001962 << PrevInit->getSourceRange();
1963 }
Mike Stump11289f42009-09-09 15:08:12 +00001964
Douglas Gregor347f7ea2009-01-28 21:54:33 +00001965 ++StructuredIndex;
1966}
1967
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001968/// Check that the given Index expression is a valid array designator
1969/// value. This is essentailly just a wrapper around
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001970/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001971/// and produces a reasonable diagnostic if there is a
1972/// failure. Returns true if there was an error, false otherwise. If
1973/// everything went okay, Value will receive the value of the constant
1974/// expression.
Mike Stump11289f42009-09-09 15:08:12 +00001975static bool
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001976CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001977 SourceLocation Loc = Index->getSourceRange().getBegin();
1978
1979 // Make sure this is an integer constant expression.
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001980 if (S.VerifyIntegerConstantExpression(Index, &Value))
1981 return true;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001982
Chris Lattnerc71d08b2009-04-25 21:59:05 +00001983 if (Value.isSigned() && Value.isNegative())
1984 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001985 << Value.toString(10) << Index->getSourceRange();
1986
Douglas Gregor51650d32009-01-23 21:04:18 +00001987 Value.setIsUnsigned(true);
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001988 return false;
1989}
1990
John McCalldadc5752010-08-24 06:29:42 +00001991ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky9331ed82010-11-20 01:29:55 +00001992 SourceLocation Loc,
1993 bool GNUSyntax,
1994 ExprResult Init) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00001995 typedef DesignatedInitExpr::Designator ASTDesignator;
1996
1997 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001998 SmallVector<ASTDesignator, 32> Designators;
1999 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002000
2001 // Build designators and check array designator expressions.
2002 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2003 const Designator &D = Desig.getDesignator(Idx);
2004 switch (D.getKind()) {
2005 case Designator::FieldDesignator:
Mike Stump11289f42009-09-09 15:08:12 +00002006 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002007 D.getFieldLoc()));
2008 break;
2009
2010 case Designator::ArrayDesignator: {
2011 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2012 llvm::APSInt IndexValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002013 if (!Index->isTypeDependent() &&
2014 !Index->isValueDependent() &&
2015 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002016 Invalid = true;
2017 else {
2018 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002019 D.getLBracketLoc(),
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002020 D.getRBracketLoc()));
2021 InitExpressions.push_back(Index);
2022 }
2023 break;
2024 }
2025
2026 case Designator::ArrayRangeDesignator: {
2027 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2028 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2029 llvm::APSInt StartValue;
2030 llvm::APSInt EndValue;
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002031 bool StartDependent = StartIndex->isTypeDependent() ||
2032 StartIndex->isValueDependent();
2033 bool EndDependent = EndIndex->isTypeDependent() ||
2034 EndIndex->isValueDependent();
2035 if ((!StartDependent &&
2036 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2037 (!EndDependent &&
2038 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002039 Invalid = true;
Douglas Gregor7a95b082009-01-23 22:22:29 +00002040 else {
2041 // Make sure we're comparing values with the same bit width.
Douglas Gregorca1aeec2009-05-21 23:17:49 +00002042 if (StartDependent || EndDependent) {
2043 // Nothing to compute.
2044 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002045 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002046 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002047 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregor7a95b082009-01-23 22:22:29 +00002048
Douglas Gregor0f9d4002009-05-21 23:30:39 +00002049 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregor7a95b082009-01-23 22:22:29 +00002050 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump11289f42009-09-09 15:08:12 +00002051 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregor7a95b082009-01-23 22:22:29 +00002052 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2053 Invalid = true;
2054 } else {
2055 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump11289f42009-09-09 15:08:12 +00002056 D.getLBracketLoc(),
Douglas Gregor7a95b082009-01-23 22:22:29 +00002057 D.getEllipsisLoc(),
2058 D.getRBracketLoc()));
2059 InitExpressions.push_back(StartIndex);
2060 InitExpressions.push_back(EndIndex);
2061 }
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002062 }
2063 break;
2064 }
2065 }
2066 }
2067
2068 if (Invalid || Init.isInvalid())
2069 return ExprError();
2070
2071 // Clear out the expressions within the designation.
2072 Desig.ClearExprs(*this);
2073
2074 DesignatedInitExpr *DIE
Jay Foad7d0479f2009-05-21 09:52:38 +00002075 = DesignatedInitExpr::Create(Context,
2076 Designators.data(), Designators.size(),
2077 InitExpressions.data(), InitExpressions.size(),
Anders Carlssonb781bcd2009-05-01 19:49:17 +00002078 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002079
Douglas Gregorc124e592011-01-16 16:13:16 +00002080 if (getLangOptions().CPlusPlus)
Eli Friedmanea7b85b2011-04-24 22:14:22 +00002081 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2082 << DIE->getSourceRange();
2083 else if (!getLangOptions().C99)
Douglas Gregorc124e592011-01-16 16:13:16 +00002084 Diag(DIE->getLocStart(), diag::ext_designated_init)
2085 << DIE->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002087 return Owned(DIE);
2088}
Douglas Gregor85df8d82009-01-29 00:45:39 +00002089
Douglas Gregor723796a2009-12-16 06:35:08 +00002090bool Sema::CheckInitList(const InitializedEntity &Entity,
2091 InitListExpr *&InitList, QualType &DeclType) {
2092 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregor85df8d82009-01-29 00:45:39 +00002093 if (!CheckInitList.HadError())
2094 InitList = CheckInitList.getFullyStructuredList();
2095
2096 return CheckInitList.HadError();
2097}
Douglas Gregora5c9e1a2009-02-02 17:43:21 +00002098
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002099//===----------------------------------------------------------------------===//
2100// Initialization entity
2101//===----------------------------------------------------------------------===//
2102
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregor723796a2009-12-16 06:35:08 +00002104 const InitializedEntity &Parent)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002105 : Parent(&Parent), Index(Index)
Douglas Gregor723796a2009-12-16 06:35:08 +00002106{
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002107 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2108 Kind = EK_ArrayElement;
Douglas Gregor1b303932009-12-22 15:35:07 +00002109 Type = AT->getElementType();
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002110 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002111 Kind = EK_VectorElement;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002112 Type = VT->getElementType();
2113 } else {
2114 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2115 assert(CT && "Unexpected type");
2116 Kind = EK_ComplexElement;
2117 Type = CT->getElementType();
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002118 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002119}
2120
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002121InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002122 CXXBaseSpecifier *Base,
2123 bool IsInheritedVirtualBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002124{
2125 InitializedEntity Result;
2126 Result.Kind = EK_Base;
Anders Carlsson43c64af2010-04-21 19:52:01 +00002127 Result.Base = reinterpret_cast<uintptr_t>(Base);
2128 if (IsInheritedVirtualBase)
2129 Result.Base |= 0x01;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002130
Douglas Gregor1b303932009-12-22 15:35:07 +00002131 Result.Type = Base->getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002132 return Result;
2133}
2134
Douglas Gregor85dabae2009-12-16 01:38:02 +00002135DeclarationName InitializedEntity::getName() const {
2136 switch (getKind()) {
John McCall31168b02011-06-15 23:02:42 +00002137 case EK_Parameter: {
2138 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2139 return (D ? D->getDeclName() : DeclarationName());
2140 }
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00002141
2142 case EK_Variable:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002143 case EK_Member:
2144 return VariableOrMember->getDeclName();
2145
2146 case EK_Result:
2147 case EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00002148 case EK_New:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002149 case EK_Temporary:
2150 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002151 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002152 case EK_ArrayElement:
2153 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002154 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002155 case EK_BlockElement:
Douglas Gregor85dabae2009-12-16 01:38:02 +00002156 return DeclarationName();
2157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002158
Douglas Gregor85dabae2009-12-16 01:38:02 +00002159 // Silence GCC warning
2160 return DeclarationName();
2161}
2162
Douglas Gregora4b592a2009-12-19 03:01:41 +00002163DeclaratorDecl *InitializedEntity::getDecl() const {
2164 switch (getKind()) {
2165 case EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002166 case EK_Member:
2167 return VariableOrMember;
2168
John McCall31168b02011-06-15 23:02:42 +00002169 case EK_Parameter:
2170 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2171
Douglas Gregora4b592a2009-12-19 03:01:41 +00002172 case EK_Result:
2173 case EK_Exception:
2174 case EK_New:
2175 case EK_Temporary:
2176 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002177 case EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00002178 case EK_ArrayElement:
2179 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002180 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002181 case EK_BlockElement:
Douglas Gregora4b592a2009-12-19 03:01:41 +00002182 return 0;
2183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002184
Douglas Gregora4b592a2009-12-19 03:01:41 +00002185 // Silence GCC warning
2186 return 0;
2187}
2188
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002189bool InitializedEntity::allowsNRVO() const {
2190 switch (getKind()) {
2191 case EK_Result:
2192 case EK_Exception:
2193 return LocAndNRVO.NRVO;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002194
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002195 case EK_Variable:
2196 case EK_Parameter:
2197 case EK_Member:
2198 case EK_New:
2199 case EK_Temporary:
2200 case EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00002201 case EK_Delegating:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002202 case EK_ArrayElement:
2203 case EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002204 case EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00002205 case EK_BlockElement:
Douglas Gregor222cf0e2010-05-15 00:13:29 +00002206 break;
2207 }
2208
2209 return false;
2210}
2211
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002212//===----------------------------------------------------------------------===//
2213// Initialization sequence
2214//===----------------------------------------------------------------------===//
2215
2216void InitializationSequence::Step::Destroy() {
2217 switch (Kind) {
2218 case SK_ResolveAddressOfOverloadedFunction:
2219 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002220 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002221 case SK_CastDerivedToBaseLValue:
2222 case SK_BindReference:
2223 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002224 case SK_ExtraneousCopyToTemporary:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002225 case SK_UserConversion:
2226 case SK_QualificationConversionRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002227 case SK_QualificationConversionXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002228 case SK_QualificationConversionLValue:
Douglas Gregor51e77d52009-12-10 17:56:55 +00002229 case SK_ListInitialization:
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002230 case SK_ConstructorInitialization:
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002231 case SK_ZeroInitialization:
Douglas Gregore1314a62009-12-18 05:02:21 +00002232 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00002233 case SK_StringInit:
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002234 case SK_ObjCObjectConversion:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002235 case SK_ArrayInit:
John McCall31168b02011-06-15 23:02:42 +00002236 case SK_PassByIndirectCopyRestore:
2237 case SK_PassByIndirectRestore:
2238 case SK_ProduceObjCObject:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002239 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002241 case SK_ConversionSequence:
2242 delete ICS;
2243 }
2244}
2245
Douglas Gregor838fcc32010-03-26 20:14:36 +00002246bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl112aa822011-07-14 19:07:55 +00002247 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregor838fcc32010-03-26 20:14:36 +00002248}
2249
2250bool InitializationSequence::isAmbiguous() const {
Sebastian Redl724bfe12011-06-05 13:59:05 +00002251 if (!Failed())
Douglas Gregor838fcc32010-03-26 20:14:36 +00002252 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002253
Douglas Gregor838fcc32010-03-26 20:14:36 +00002254 switch (getFailureKind()) {
2255 case FK_TooManyInitsForReference:
2256 case FK_ArrayNeedsInitList:
2257 case FK_ArrayNeedsInitListOrStringLiteral:
2258 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2259 case FK_NonConstLValueReferenceBindingToTemporary:
2260 case FK_NonConstLValueReferenceBindingToUnrelated:
2261 case FK_RValueReferenceBindingToLValue:
2262 case FK_ReferenceInitDropsQualifiers:
2263 case FK_ReferenceInitFailed:
2264 case FK_ConversionFailed:
John Wiegley01296292011-04-08 18:41:53 +00002265 case FK_ConversionFromPropertyFailed:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002266 case FK_TooManyInitsForScalar:
2267 case FK_ReferenceBindingToInitList:
2268 case FK_InitListBadDestinationType:
2269 case FK_DefaultInitOfConst:
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002270 case FK_Incomplete:
Douglas Gregore2f943b2011-02-22 18:29:51 +00002271 case FK_ArrayTypeMismatch:
2272 case FK_NonConstantArrayInit:
Douglas Gregor838fcc32010-03-26 20:14:36 +00002273 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002274
Douglas Gregor838fcc32010-03-26 20:14:36 +00002275 case FK_ReferenceInitOverloadFailed:
2276 case FK_UserConversionOverloadFailed:
2277 case FK_ConstructorOverloadFailed:
2278 return FailedOverloadResult == OR_Ambiguous;
2279 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002280
Douglas Gregor838fcc32010-03-26 20:14:36 +00002281 return false;
2282}
2283
Douglas Gregorb33eed02010-04-16 22:09:46 +00002284bool InitializationSequence::isConstructorInitialization() const {
2285 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2286}
2287
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002288bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2289 const Expr *Initializer,
2290 bool *isInitializerConstant,
2291 APValue *ConstantValue) const {
2292 if (Steps.empty() || Initializer->isValueDependent())
2293 return false;
2294
2295 const Step &LastStep = Steps.back();
2296 if (LastStep.Kind != SK_ConversionSequence)
2297 return false;
2298
2299 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2300 const StandardConversionSequence *SCS = NULL;
2301 switch (ICS.getKind()) {
2302 case ImplicitConversionSequence::StandardConversion:
2303 SCS = &ICS.Standard;
2304 break;
2305 case ImplicitConversionSequence::UserDefinedConversion:
2306 SCS = &ICS.UserDefined.After;
2307 break;
2308 case ImplicitConversionSequence::AmbiguousConversion:
2309 case ImplicitConversionSequence::EllipsisConversion:
2310 case ImplicitConversionSequence::BadConversion:
2311 return false;
2312 }
2313
2314 // Check if SCS represents a narrowing conversion, according to C++0x
2315 // [dcl.init.list]p7:
2316 //
2317 // A narrowing conversion is an implicit conversion ...
2318 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2319 QualType FromType = SCS->getToType(0);
2320 QualType ToType = SCS->getToType(1);
2321 switch (PossibleNarrowing) {
2322 // * from a floating-point type to an integer type, or
2323 //
2324 // * from an integer type or unscoped enumeration type to a floating-point
2325 // type, except where the source is a constant expression and the actual
2326 // value after conversion will fit into the target type and will produce
2327 // the original value when converted back to the original type, or
2328 case ICK_Floating_Integral:
2329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2330 *isInitializerConstant = false;
2331 return true;
2332 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2333 llvm::APSInt IntConstantValue;
2334 if (Initializer &&
2335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2336 // Convert the integer to the floating type.
2337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2339 llvm::APFloat::rmNearestTiesToEven);
2340 // And back.
2341 llvm::APSInt ConvertedValue = IntConstantValue;
2342 bool ignored;
2343 Result.convertToInteger(ConvertedValue,
2344 llvm::APFloat::rmTowardZero, &ignored);
2345 // If the resulting value is different, this was a narrowing conversion.
2346 if (IntConstantValue != ConvertedValue) {
2347 *isInitializerConstant = true;
2348 *ConstantValue = APValue(IntConstantValue);
2349 return true;
2350 }
2351 } else {
2352 // Variables are always narrowings.
2353 *isInitializerConstant = false;
2354 return true;
2355 }
2356 }
2357 return false;
2358
2359 // * from long double to double or float, or from double to float, except
2360 // where the source is a constant expression and the actual value after
2361 // conversion is within the range of values that can be represented (even
2362 // if it cannot be represented exactly), or
2363 case ICK_Floating_Conversion:
2364 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2365 // FromType is larger than ToType.
2366 Expr::EvalResult InitializerValue;
2367 // FIXME: Check whether Initializer is a constant expression according
2368 // to C++0x [expr.const], rather than just whether it can be folded.
2369 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2370 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2371 // Constant! (Except for FIXME above.)
2372 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2373 // Convert the source value into the target type.
2374 bool ignored;
2375 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2376 Ctx.getFloatTypeSemantics(ToType),
2377 llvm::APFloat::rmNearestTiesToEven, &ignored);
2378 // If there was no overflow, the source value is within the range of
2379 // values that can be represented.
2380 if (ConvertStatus & llvm::APFloat::opOverflow) {
2381 *isInitializerConstant = true;
2382 *ConstantValue = InitializerValue.Val;
2383 return true;
2384 }
2385 } else {
2386 *isInitializerConstant = false;
2387 return true;
2388 }
2389 }
2390 return false;
2391
2392 // * from an integer type or unscoped enumeration type to an integer type
2393 // that cannot represent all the values of the original type, except where
2394 // the source is a constant expression and the actual value after
2395 // conversion will fit into the target type and will produce the original
2396 // value when converted back to the original type.
Jeffrey Yasskin94f8c772011-08-12 20:56:43 +00002397 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskin92425582011-08-30 22:25:41 +00002398 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2399 // Boolean conversions can be from pointers and pointers to members
2400 // [conv.bool], and those aren't considered narrowing conversions.
2401 return false;
2402 } // Otherwise, fall through to the integral case.
Jeffrey Yasskina6667812011-07-26 23:20:30 +00002403 case ICK_Integral_Conversion: {
2404 assert(FromType->isIntegralOrUnscopedEnumerationType());
2405 assert(ToType->isIntegralOrUnscopedEnumerationType());
2406 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2407 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2408 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2409 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2410
2411 if (FromWidth > ToWidth ||
2412 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2413 // Not all values of FromType can be represented in ToType.
2414 llvm::APSInt InitializerValue;
2415 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2416 *isInitializerConstant = true;
2417 *ConstantValue = APValue(InitializerValue);
2418
2419 // Add a bit to the InitializerValue so we don't have to worry about
2420 // signed vs. unsigned comparisons.
2421 InitializerValue = InitializerValue.extend(
2422 InitializerValue.getBitWidth() + 1);
2423 // Convert the initializer to and from the target width and signed-ness.
2424 llvm::APSInt ConvertedValue = InitializerValue;
2425 ConvertedValue = ConvertedValue.trunc(ToWidth);
2426 ConvertedValue.setIsSigned(ToSigned);
2427 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2428 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2429 // If the result is different, this was a narrowing conversion.
2430 return ConvertedValue != InitializerValue;
2431 } else {
2432 // Variables are always narrowings.
2433 *isInitializerConstant = false;
2434 return true;
2435 }
2436 }
2437 return false;
2438 }
2439
2440 default:
2441 // Other kinds of conversions are not narrowings.
2442 return false;
2443 }
2444}
2445
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002446void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall16df1e52010-03-30 21:47:33 +00002447 FunctionDecl *Function,
2448 DeclAccessPair Found) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002449 Step S;
2450 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2451 S.Type = Function->getType();
John McCalla0296f72010-03-19 07:35:19 +00002452 S.Function.Function = Function;
John McCall16df1e52010-03-30 21:47:33 +00002453 S.Function.FoundDecl = Found;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002454 Steps.push_back(S);
2455}
2456
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00002458 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002459 Step S;
John McCall2536c6d2010-08-25 10:28:54 +00002460 switch (VK) {
2461 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2462 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2463 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002464 default: llvm_unreachable("No such category");
2465 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002466 S.Type = BaseType;
2467 Steps.push_back(S);
2468}
2469
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002470void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002471 bool BindingTemporary) {
2472 Step S;
2473 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2474 S.Type = T;
2475 Steps.push_back(S);
2476}
2477
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00002478void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2479 Step S;
2480 S.Kind = SK_ExtraneousCopyToTemporary;
2481 S.Type = T;
2482 Steps.push_back(S);
2483}
2484
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002485void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002486 DeclAccessPair FoundDecl,
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002487 QualType T) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002488 Step S;
2489 S.Kind = SK_UserConversion;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002490 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002491 S.Function.Function = Function;
2492 S.Function.FoundDecl = FoundDecl;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002493 Steps.push_back(S);
2494}
2495
2496void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall2536c6d2010-08-25 10:28:54 +00002497 ExprValueKind VK) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002498 Step S;
John McCall7a1da892010-08-26 16:36:35 +00002499 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall2536c6d2010-08-25 10:28:54 +00002500 switch (VK) {
2501 case VK_RValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002502 S.Kind = SK_QualificationConversionRValue;
2503 break;
John McCall2536c6d2010-08-25 10:28:54 +00002504 case VK_XValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002505 S.Kind = SK_QualificationConversionXValue;
2506 break;
John McCall2536c6d2010-08-25 10:28:54 +00002507 case VK_LValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002508 S.Kind = SK_QualificationConversionLValue;
2509 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002510 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002511 S.Type = Ty;
2512 Steps.push_back(S);
2513}
2514
2515void InitializationSequence::AddConversionSequenceStep(
2516 const ImplicitConversionSequence &ICS,
2517 QualType T) {
2518 Step S;
2519 S.Kind = SK_ConversionSequence;
2520 S.Type = T;
2521 S.ICS = new ImplicitConversionSequence(ICS);
2522 Steps.push_back(S);
2523}
2524
Douglas Gregor51e77d52009-12-10 17:56:55 +00002525void InitializationSequence::AddListInitializationStep(QualType T) {
2526 Step S;
2527 S.Kind = SK_ListInitialization;
2528 S.Type = T;
2529 Steps.push_back(S);
2530}
2531
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002532void
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002533InitializationSequence::AddConstructorInitializationStep(
2534 CXXConstructorDecl *Constructor,
John McCall760af172010-02-01 03:16:54 +00002535 AccessSpecifier Access,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002536 QualType T) {
2537 Step S;
2538 S.Kind = SK_ConstructorInitialization;
2539 S.Type = T;
John McCalla0296f72010-03-19 07:35:19 +00002540 S.Function.Function = Constructor;
2541 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00002542 Steps.push_back(S);
2543}
2544
Douglas Gregor7dc42e52009-12-15 00:01:57 +00002545void InitializationSequence::AddZeroInitializationStep(QualType T) {
2546 Step S;
2547 S.Kind = SK_ZeroInitialization;
2548 S.Type = T;
2549 Steps.push_back(S);
2550}
2551
Douglas Gregore1314a62009-12-18 05:02:21 +00002552void InitializationSequence::AddCAssignmentStep(QualType T) {
2553 Step S;
2554 S.Kind = SK_CAssignment;
2555 S.Type = T;
2556 Steps.push_back(S);
2557}
2558
Eli Friedman78275202009-12-19 08:11:05 +00002559void InitializationSequence::AddStringInitStep(QualType T) {
2560 Step S;
2561 S.Kind = SK_StringInit;
2562 S.Type = T;
2563 Steps.push_back(S);
2564}
2565
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002566void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2567 Step S;
2568 S.Kind = SK_ObjCObjectConversion;
2569 S.Type = T;
2570 Steps.push_back(S);
2571}
2572
Douglas Gregore2f943b2011-02-22 18:29:51 +00002573void InitializationSequence::AddArrayInitStep(QualType T) {
2574 Step S;
2575 S.Kind = SK_ArrayInit;
2576 S.Type = T;
2577 Steps.push_back(S);
2578}
2579
John McCall31168b02011-06-15 23:02:42 +00002580void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2581 bool shouldCopy) {
2582 Step s;
2583 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2584 : SK_PassByIndirectRestore);
2585 s.Type = type;
2586 Steps.push_back(s);
2587}
2588
2589void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2590 Step S;
2591 S.Kind = SK_ProduceObjCObject;
2592 S.Type = T;
2593 Steps.push_back(S);
2594}
2595
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002596void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002597 OverloadingResult Result) {
Sebastian Redld201edf2011-06-05 13:59:11 +00002598 setSequenceKind(FailedSequence);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002599 this->Failure = Failure;
2600 this->FailedOverloadResult = Result;
2601}
2602
2603//===----------------------------------------------------------------------===//
2604// Attempt initialization
2605//===----------------------------------------------------------------------===//
2606
John McCall31168b02011-06-15 23:02:42 +00002607static void MaybeProduceObjCObject(Sema &S,
2608 InitializationSequence &Sequence,
2609 const InitializedEntity &Entity) {
2610 if (!S.getLangOptions().ObjCAutoRefCount) return;
2611
2612 /// When initializing a parameter, produce the value if it's marked
2613 /// __attribute__((ns_consumed)).
2614 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2615 if (!Entity.isParameterConsumed())
2616 return;
2617
2618 assert(Entity.getType()->isObjCRetainableType() &&
2619 "consuming an object of unretainable type?");
2620 Sequence.AddProduceObjCObjectStep(Entity.getType());
2621
2622 /// When initializing a return value, if the return type is a
2623 /// retainable type, then returns need to immediately retain the
2624 /// object. If an autorelease is required, it will be done at the
2625 /// last instant.
2626 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2627 if (!Entity.getType()->isObjCRetainableType())
2628 return;
2629
2630 Sequence.AddProduceObjCObjectStep(Entity.getType());
2631 }
2632}
2633
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002634/// \brief Attempt list initialization (C++0x [dcl.init.list])
2635static void TryListInitialization(Sema &S,
2636 const InitializedEntity &Entity,
2637 const InitializationKind &Kind,
2638 InitListExpr *InitList,
2639 InitializationSequence &Sequence) {
2640 // FIXME: We only perform rudimentary checking of list
2641 // initializations at this point, then assume that any list
2642 // initialization of an array, aggregate, or scalar will be
2643 // well-formed. When we actually "perform" list initialization, we'll
2644 // do all of the necessary checking. C++0x initializer lists will
2645 // force us to perform more checking here.
2646
2647 QualType DestType = Entity.getType();
2648
2649 // C++ [dcl.init]p13:
2650 // If T is a scalar type, then a declaration of the form
2651 //
2652 // T x = { a };
2653 //
2654 // is equivalent to
2655 //
2656 // T x = a;
Eli Friedman6b9c41e2011-09-19 23:17:44 +00002657 if (DestType->isAnyComplexType()) {
2658 // We allow more than 1 init for complex types in some cases, even though
2659 // they are scalar.
2660 } else if (DestType->isScalarType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00002661 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2662 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2663 return;
2664 }
2665
2666 // Assume scalar initialization from a single value works.
2667 } else if (DestType->isAggregateType()) {
2668 // Assume aggregate initialization works.
2669 } else if (DestType->isVectorType()) {
2670 // Assume vector initialization works.
2671 } else if (DestType->isReferenceType()) {
2672 // FIXME: C++0x defines behavior for this.
2673 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2674 return;
2675 } else if (DestType->isRecordType()) {
2676 // FIXME: C++0x defines behavior for this
2677 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2678 }
2679
2680 // Add a general "list initialization" step.
2681 Sequence.AddListInitializationStep(DestType);
2682}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002683
2684/// \brief Try a reference initialization that involves calling a conversion
2685/// function.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002686static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2687 const InitializedEntity &Entity,
2688 const InitializationKind &Kind,
2689 Expr *Initializer,
2690 bool AllowRValues,
2691 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002692 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002693 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2694 QualType T1 = cv1T1.getUnqualifiedType();
2695 QualType cv2T2 = Initializer->getType();
2696 QualType T2 = cv2T2.getUnqualifiedType();
2697
2698 bool DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002699 bool ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002700 bool ObjCLifetimeConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002701 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002702 T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002703 ObjCConversion,
2704 ObjCLifetimeConversion) &&
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002705 "Must have incompatible references when binding via conversion");
Chandler Carruth8abbc652009-12-13 01:37:04 +00002706 (void)DerivedToBase;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002707 (void)ObjCConversion;
John McCall31168b02011-06-15 23:02:42 +00002708 (void)ObjCLifetimeConversion;
2709
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002710 // Build the candidate set directly in the initialization sequence
2711 // structure, so that it will persist if we fail.
2712 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2713 CandidateSet.clear();
2714
2715 // Determine whether we are allowed to call explicit constructors or
2716 // explicit conversion operators.
2717 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002718
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002719 const RecordType *T1RecordType = 0;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002720 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2721 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002722 // The type we're converting to is a class type. Enumerate its constructors
2723 // to see if there is a suitable conversion.
2724 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall3696dcb2010-08-17 07:23:57 +00002725
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002726 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00002727 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002728 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002729 NamedDecl *D = *Con;
2730 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2731
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002732 // Find the constructor (which may be a template).
2733 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00002734 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002735 if (ConstructorTmpl)
2736 Constructor = cast<CXXConstructorDecl>(
2737 ConstructorTmpl->getTemplatedDecl());
2738 else
John McCalla0296f72010-03-19 07:35:19 +00002739 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002740
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002741 if (!Constructor->isInvalidDecl() &&
2742 Constructor->isConvertingConstructor(AllowExplicit)) {
2743 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00002744 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00002745 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002746 &Initializer, 1, CandidateSet,
2747 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002748 else
John McCalla0296f72010-03-19 07:35:19 +00002749 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisdfbdfbb2010-10-05 03:05:30 +00002750 &Initializer, 1, CandidateSet,
2751 /*SuppressUserConversions=*/true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002752 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002753 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002754 }
John McCall3696dcb2010-08-17 07:23:57 +00002755 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2756 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002757
Douglas Gregor496e8b342010-05-07 19:42:26 +00002758 const RecordType *T2RecordType = 0;
2759 if ((T2RecordType = T2->getAs<RecordType>()) &&
2760 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002761 // The type we're converting from is a class type, enumerate its conversion
2762 // functions.
2763 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2764
John McCallad371252010-01-20 00:46:10 +00002765 const UnresolvedSetImpl *Conversions
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002766 = T2RecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002767 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2768 E = Conversions->end(); I != E; ++I) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002769 NamedDecl *D = *I;
2770 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2771 if (isa<UsingShadowDecl>(D))
2772 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002773
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002774 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2775 CXXConversionDecl *Conv;
2776 if (ConvTemplate)
2777 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2778 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002779 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002781 // If the conversion function doesn't return a reference type,
2782 // it can't be considered for this conversion unless we're allowed to
2783 // consider rvalues.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784 // FIXME: Do we need to make sure that we only consider conversion
2785 // candidates with reference-compatible results? That might be needed to
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002786 // break recursion.
2787 if ((AllowExplicit || !Conv->isExplicit()) &&
2788 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2789 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00002790 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00002791 ActingDC, Initializer,
Douglas Gregord412fe52011-01-21 00:27:08 +00002792 DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002793 else
John McCalla0296f72010-03-19 07:35:19 +00002794 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregord412fe52011-01-21 00:27:08 +00002795 Initializer, DestType, CandidateSet);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002796 }
2797 }
2798 }
John McCall3696dcb2010-08-17 07:23:57 +00002799 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2800 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002802 SourceLocation DeclLoc = Initializer->getLocStart();
2803
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002804 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002805 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002806 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00002807 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002808 return Result;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002809
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002810 FunctionDecl *Function = Best->Function;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002811
Chandler Carruth30141632011-02-25 19:41:05 +00002812 // This is the overload that will actually be used for the initialization, so
2813 // mark it as used.
2814 S.MarkDeclarationReferenced(DeclLoc, Function);
2815
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002816 // Compute the returned type of the conversion.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002817 if (isa<CXXConversionDecl>(Function))
2818 T2 = Function->getResultType();
2819 else
2820 T2 = cv1T1;
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002821
2822 // Add the user-defined conversion step.
John McCalla0296f72010-03-19 07:35:19 +00002823 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002824 T2.getNonLValueExprType(S.Context));
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002825
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002826 // Determine whether we need to perform derived-to-base or
Eli Friedmanad6c2e52009-12-11 02:42:07 +00002827 // cv-qualification adjustments.
John McCall2536c6d2010-08-25 10:28:54 +00002828 ExprValueKind VK = VK_RValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002829 if (T2->isLValueReferenceType())
John McCall2536c6d2010-08-25 10:28:54 +00002830 VK = VK_LValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002831 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall2536c6d2010-08-25 10:28:54 +00002832 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002833
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002834 bool NewDerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002835 bool NewObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002836 bool NewObjCLifetimeConversion = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002837 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002838 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregora8a089b2010-07-13 18:40:04 +00002839 T2.getNonLValueExprType(S.Context),
John McCall31168b02011-06-15 23:02:42 +00002840 NewDerivedToBase, NewObjCConversion,
2841 NewObjCLifetimeConversion);
Douglas Gregor1ce52ca2010-03-07 23:17:44 +00002842 if (NewRefRelationship == Sema::Ref_Incompatible) {
2843 // If the type we've converted to is not reference-related to the
2844 // type we're looking for, then there is another conversion step
2845 // we need to perform to produce a temporary of the right type
2846 // that we'll be binding to.
2847 ImplicitConversionSequence ICS;
2848 ICS.setStandard();
2849 ICS.Standard = Best->FinalConversion;
2850 T2 = ICS.Standard.getToType(2);
2851 Sequence.AddConversionSequenceStep(ICS, T2);
2852 } else if (NewDerivedToBase)
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002853 Sequence.AddDerivedToBaseCastStep(
2854 S.Context.getQualifiedType(T1,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002855 T2.getNonReferenceType().getQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00002856 VK);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002857 else if (NewObjCConversion)
2858 Sequence.AddObjCObjectConversionStep(
2859 S.Context.getQualifiedType(T1,
2860 T2.getNonReferenceType().getQualifiers()));
2861
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002862 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall2536c6d2010-08-25 10:28:54 +00002863 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002865 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2866 return OR_Success;
2867}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002868
2869/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2870static void TryReferenceInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002871 const InitializedEntity &Entity,
2872 const InitializationKind &Kind,
2873 Expr *Initializer,
2874 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00002875 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002876 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002877 Qualifiers T1Quals;
2878 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002879 QualType cv2T2 = Initializer->getType();
Chandler Carruth04bdce62010-01-12 20:32:25 +00002880 Qualifiers T2Quals;
2881 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002882 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redld92badf2010-06-30 18:13:39 +00002883
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002884 // If the initializer is the address of an overloaded function, try
2885 // to resolve the overloaded function. If all goes well, T2 is the
2886 // type of the resulting function.
2887 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall16df1e52010-03-30 21:47:33 +00002888 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002889 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregorbcd62532010-11-08 15:20:28 +00002890 T1,
2891 false,
2892 Found)) {
2893 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2894 cv2T2 = Fn->getType();
2895 T2 = cv2T2.getUnqualifiedType();
2896 } else if (!T1->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002897 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2898 return;
2899 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002900 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002901
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002902 // Compute some basic properties of the types and the initializer.
2903 bool isLValueRef = DestType->isLValueReferenceType();
2904 bool isRValueRef = !isLValueRef;
2905 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002906 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00002907 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002908 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002909 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002910 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00002911 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redld92badf2010-06-30 18:13:39 +00002912
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002913 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002915 // "cv2 T2" as follows:
2916 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917 // - If the reference is an lvalue reference and the initializer
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002918 // expression
Sebastian Redld92badf2010-06-30 18:13:39 +00002919 // Note the analogous bullet points for rvlaue refs to functions. Because
2920 // there are no function rvalues in C++, rvalue refs to functions are treated
2921 // like lvalue refs.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002922 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redld92badf2010-06-30 18:13:39 +00002923 bool T1Function = T1->isFunctionType();
2924 if (isLValueRef || T1Function) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002925 if (InitCategory.isLValue() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002926 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00002928 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002930 // reference-compatible with "cv2 T2," or
2931 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002932 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002933 // bit-field when we're determining whether the reference initialization
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002934 // can occur. However, we do pay attention to whether it is a bit-field
2935 // to decide whether we're actually binding to a temporary created from
2936 // the bit-field.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002937 if (DerivedToBase)
2938 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939 S.Context.getQualifiedType(T1, T2Quals),
John McCall2536c6d2010-08-25 10:28:54 +00002940 VK_LValue);
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002941 else if (ObjCConversion)
2942 Sequence.AddObjCObjectConversionStep(
2943 S.Context.getQualifiedType(T1, T2Quals));
2944
Chandler Carruth04bdce62010-01-12 20:32:25 +00002945 if (T1Quals != T2Quals)
John McCall2536c6d2010-08-25 10:28:54 +00002946 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002947 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson8abde4b2010-01-31 17:18:49 +00002948 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregor65eb86e2010-01-29 19:14:02 +00002949 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002950 return;
2951 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002952
2953 // - has a class type (i.e., T2 is a class type), where T1 is not
2954 // reference-related to T2, and can be implicitly converted to an
2955 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2956 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002957 // applicable conversion functions (13.3.1.6) and choosing the best
2958 // one through overload resolution (13.3)),
Sebastian Redld92badf2010-06-30 18:13:39 +00002959 // If we have an rvalue ref to function type here, the rhs must be
2960 // an rvalue.
2961 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2962 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002964 Initializer,
Sebastian Redld92badf2010-06-30 18:13:39 +00002965 /*AllowRValues=*/isRValueRef,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002966 Sequence);
2967 if (ConvOvlResult == OR_Success)
2968 return;
John McCall0d1da222010-01-12 00:44:57 +00002969 if (ConvOvlResult != OR_No_Viable_Function) {
2970 Sequence.SetOverloadFailure(
2971 InitializationSequence::FK_ReferenceInitOverloadFailed,
2972 ConvOvlResult);
2973 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002974 }
2975 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002976
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002977 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002978 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor7a2a1162011-01-20 16:08:06 +00002979 // shall be an rvalue reference.
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002980 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregorbcd62532010-11-08 15:20:28 +00002981 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2982 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2983 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002984 Sequence.SetOverloadFailure(
2985 InitializationSequence::FK_ReferenceInitOverloadFailed,
2986 ConvOvlResult);
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00002987 else
Sebastian Redld92badf2010-06-30 18:13:39 +00002988 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002989 ? (RefRelationship == Sema::Ref_Related
2990 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2991 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2992 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redld92badf2010-06-30 18:13:39 +00002993
Douglas Gregor3e1e5272009-12-09 23:02:17 +00002994 return;
2995 }
Sebastian Redld92badf2010-06-30 18:13:39 +00002996
Douglas Gregor92e460e2011-01-20 16:44:54 +00002997 // - If the initializer expression
2998 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2999 // "cv1 T1" is reference-compatible with "cv2 T2"
3000 // Note: functions are handled below.
3001 if (!T1Function &&
Douglas Gregor58281352011-01-27 00:58:17 +00003002 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor58281352011-01-27 00:58:17 +00003004 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregor92e460e2011-01-20 16:44:54 +00003005 (InitCategory.isXValue() ||
3006 (InitCategory.isPRValue() && T2->isRecordType()) ||
3007 (InitCategory.isPRValue() && T2->isArrayType()))) {
3008 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3009 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003010 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3011 // compiler the freedom to perform a copy here or bind to the
3012 // object, while C++0x requires that we bind directly to the
3013 // object. Hence, we always bind to the object without making an
3014 // extra copy. However, in C++03 requires that we check for the
3015 // presence of a suitable copy constructor:
3016 //
3017 // The constructor that would be used to make the copy shall
3018 // be callable whether or not the copy is actually done.
Francois Pichet0706d202011-09-17 17:15:52 +00003019 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003020 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003022
Douglas Gregor92e460e2011-01-20 16:44:54 +00003023 if (DerivedToBase)
3024 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3025 ValueKind);
3026 else if (ObjCConversion)
3027 Sequence.AddObjCObjectConversionStep(
3028 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003029
Douglas Gregor92e460e2011-01-20 16:44:54 +00003030 if (T1Quals != T2Quals)
3031 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003032 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregor92e460e2011-01-20 16:44:54 +00003033 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003034 return;
Douglas Gregor92e460e2011-01-20 16:44:54 +00003035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003036
3037 // - has a class type (i.e., T2 is a class type), where T1 is not
3038 // reference-related to T2, and can be implicitly converted to an
Douglas Gregor92e460e2011-01-20 16:44:54 +00003039 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3040 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregor92e460e2011-01-20 16:44:54 +00003041 if (T2->isRecordType()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003042 if (RefRelationship == Sema::Ref_Incompatible) {
3043 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3044 Kind, Initializer,
3045 /*AllowRValues=*/true,
3046 Sequence);
3047 if (ConvOvlResult)
3048 Sequence.SetOverloadFailure(
3049 InitializationSequence::FK_ReferenceInitOverloadFailed,
3050 ConvOvlResult);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003051
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003052 return;
3053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003054
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003055 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3056 return;
3057 }
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003058
3059 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003060 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003061 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003062 // temporary. [...]
John McCallec6f4e92010-06-04 02:29:22 +00003063
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003064 // Determine whether we are allowed to call explicit constructors or
3065 // explicit conversion operators.
3066 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCallec6f4e92010-06-04 02:29:22 +00003067
3068 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3069
John McCall31168b02011-06-15 23:02:42 +00003070 ImplicitConversionSequence ICS
3071 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCallec6f4e92010-06-04 02:29:22 +00003072 /*SuppressUserConversions*/ false,
3073 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00003074 /*FIXME:InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003075 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3076 /*AllowObjCWritebackConversion=*/false);
3077
3078 if (ICS.isBad()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003079 // FIXME: Use the conversion function set stored in ICS to turn
3080 // this into an overloading ambiguity diagnostic. However, we need
3081 // to keep that set as an OverloadCandidateSet rather than as some
3082 // other kind of set.
Douglas Gregore1314a62009-12-18 05:02:21 +00003083 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3084 Sequence.SetOverloadFailure(
3085 InitializationSequence::FK_ReferenceInitOverloadFailed,
3086 ConvOvlResult);
Douglas Gregorbcd62532010-11-08 15:20:28 +00003087 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3088 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore1314a62009-12-18 05:02:21 +00003089 else
3090 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003091 return;
John McCall31168b02011-06-15 23:02:42 +00003092 } else {
3093 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003094 }
3095
3096 // [...] If T1 is reference-related to T2, cv1 must be the
3097 // same cv-qualification as, or greater cv-qualification
3098 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth04bdce62010-01-12 20:32:25 +00003099 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3100 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth04bdce62010-01-12 20:32:25 +00003102 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003103 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3104 return;
3105 }
3106
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003107 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003108 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003109 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregor24f2e8e2011-01-21 00:52:42 +00003110 InitCategory.isLValue()) {
3111 Sequence.SetFailed(
3112 InitializationSequence::FK_RValueReferenceBindingToLValue);
3113 return;
3114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003115
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003116 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3117 return;
3118}
3119
3120/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121/// (C++ [dcl.init.string], C99 6.7.8).
3122static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003123 const InitializedEntity &Entity,
3124 const InitializationKind &Kind,
3125 Expr *Initializer,
3126 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003127 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003128}
3129
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003130/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3131/// enumerates the constructors of the initialized entity and performs overload
3132/// resolution to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003133static void TryConstructorInitialization(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003134 const InitializedEntity &Entity,
3135 const InitializationKind &Kind,
3136 Expr **Args, unsigned NumArgs,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003137 QualType DestType,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003138 InitializationSequence &Sequence) {
Richard Trieua04ad1a2011-09-01 21:44:13 +00003139 // Check constructor arguments for self reference.
3140 if (DeclaratorDecl *DD = Entity.getDecl())
3141 // Parameters arguments are occassionially constructed with itself,
3142 // for instance, in recursive functions. Skip them.
3143 if (!isa<ParmVarDecl>(DD))
3144 for (unsigned i = 0; i < NumArgs; ++i)
3145 S.CheckSelfReference(DD, Args[i]);
3146
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003147 // Build the candidate set directly in the initialization sequence
3148 // structure, so that it will persist if we fail.
3149 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3150 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003152 // Determine whether we are allowed to call explicit constructors or
3153 // explicit conversion operators.
3154 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3155 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003156 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregord9848152010-04-26 14:36:57 +00003157
3158 // The type we're constructing needs to be complete.
3159 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00003160 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregord9848152010-04-26 14:36:57 +00003161 return;
3162 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003164 // The type we're converting to is a class type. Enumerate its constructors
3165 // to see if one is suitable.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003166 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003167 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003168 CXXRecordDecl *DestRecordDecl
3169 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003170
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003171 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003172 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003173 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003174 NamedDecl *D = *Con;
3175 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregorc779e992010-04-24 20:54:38 +00003176 bool SuppressUserConversions = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003177
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003178 // Find the constructor (which may be a template).
3179 CXXConstructorDecl *Constructor = 0;
John McCalla0296f72010-03-19 07:35:19 +00003180 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003181 if (ConstructorTmpl)
3182 Constructor = cast<CXXConstructorDecl>(
3183 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorc779e992010-04-24 20:54:38 +00003184 else {
John McCalla0296f72010-03-19 07:35:19 +00003185 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorc779e992010-04-24 20:54:38 +00003186
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187 // If we're performing copy initialization using a copy constructor, we
Douglas Gregorc779e992010-04-24 20:54:38 +00003188 // suppress user-defined conversions on the arguments.
3189 // FIXME: Move constructors?
3190 if (Kind.getKind() == InitializationKind::IK_Copy &&
3191 Constructor->isCopyConstructor())
3192 SuppressUserConversions = true;
3193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003194
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003195 if (!Constructor->isInvalidDecl() &&
Douglas Gregor85dabae2009-12-16 01:38:02 +00003196 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003197 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00003198 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003199 /*ExplicitArgs*/ 0,
Douglas Gregorc779e992010-04-24 20:54:38 +00003200 Args, NumArgs, CandidateSet,
3201 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003202 else
John McCalla0296f72010-03-19 07:35:19 +00003203 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregorc779e992010-04-24 20:54:38 +00003204 Args, NumArgs, CandidateSet,
3205 SuppressUserConversions);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003207 }
3208
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003209 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210
3211 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003212 OverloadCandidateSet::iterator Best;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213 if (OverloadingResult Result
John McCall5c32be02010-08-24 20:38:10 +00003214 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003215 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003216 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003217 Result);
3218 return;
3219 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003220
3221 // C++0x [dcl.init]p6:
3222 // If a program calls for the default initialization of an object
3223 // of a const-qualified type T, T shall be a class type with a
3224 // user-provided default constructor.
3225 if (Kind.getKind() == InitializationKind::IK_Default &&
3226 Entity.getType().isConstQualified() &&
3227 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3228 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3229 return;
3230 }
3231
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00003232 // Add the constructor initialization step. Any cv-qualification conversion is
3233 // subsumed by the initialization.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003234 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003235 cast<CXXConstructorDecl>(Best->Function),
John McCalla0296f72010-03-19 07:35:19 +00003236 Best->FoundDecl.getAccess(),
Douglas Gregore1314a62009-12-18 05:02:21 +00003237 DestType);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003238}
3239
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003240/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003241static void TryValueInitialization(Sema &S,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003242 const InitializedEntity &Entity,
3243 const InitializationKind &Kind,
3244 InitializationSequence &Sequence) {
3245 // C++ [dcl.init]p5:
3246 //
3247 // To value-initialize an object of type T means:
Douglas Gregor1b303932009-12-22 15:35:07 +00003248 QualType T = Entity.getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003249
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003250 // -- if T is an array type, then each element is value-initialized;
3251 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3252 T = AT->getElementType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003254 if (const RecordType *RT = T->getAs<RecordType>()) {
3255 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3256 // -- if T is a class type (clause 9) with a user-declared
3257 // constructor (12.1), then the default constructor for T is
3258 // called (and the initialization is ill-formed if T has no
3259 // accessible default constructor);
3260 //
3261 // FIXME: we really want to refer to a single subobject of the array,
3262 // but Entity doesn't have a way to capture that (yet).
3263 if (ClassDecl->hasUserDeclaredConstructor())
3264 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003266 // -- if T is a (possibly cv-qualified) non-union class type
3267 // without a user-provided constructor, then the object is
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003268 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003269 // constructor is non-trivial, that constructor is called.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003270 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregor747eb782010-07-08 06:14:04 +00003271 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003272 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor4f4b1862009-12-16 18:50:27 +00003274 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003275 }
3276 }
3277
Douglas Gregor1b303932009-12-22 15:35:07 +00003278 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor7dc42e52009-12-15 00:01:57 +00003279}
3280
Douglas Gregor85dabae2009-12-16 01:38:02 +00003281/// \brief Attempt default initialization (C++ [dcl.init]p6).
3282static void TryDefaultInitialization(Sema &S,
3283 const InitializedEntity &Entity,
3284 const InitializationKind &Kind,
3285 InitializationSequence &Sequence) {
3286 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003287
Douglas Gregor85dabae2009-12-16 01:38:02 +00003288 // C++ [dcl.init]p6:
3289 // To default-initialize an object of type T means:
3290 // - if T is an array type, each element is default-initialized;
John McCall31168b02011-06-15 23:02:42 +00003291 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3292
Douglas Gregor85dabae2009-12-16 01:38:02 +00003293 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3294 // constructor for T is called (and the initialization is ill-formed if
3295 // T has no accessible default constructor);
Douglas Gregore6565622010-02-09 07:26:29 +00003296 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruthc9262402010-08-23 07:55:51 +00003297 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3298 return;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003299 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003300
Douglas Gregor85dabae2009-12-16 01:38:02 +00003301 // - otherwise, no initialization is performed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003302
Douglas Gregor85dabae2009-12-16 01:38:02 +00003303 // If a program calls for the default initialization of an object of
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003304 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor85dabae2009-12-16 01:38:02 +00003305 // default constructor.
John McCall31168b02011-06-15 23:02:42 +00003306 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor85dabae2009-12-16 01:38:02 +00003307 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCall31168b02011-06-15 23:02:42 +00003308 return;
3309 }
3310
3311 // If the destination type has a lifetime property, zero-initialize it.
3312 if (DestType.getQualifiers().hasObjCLifetime()) {
3313 Sequence.AddZeroInitializationStep(Entity.getType());
3314 return;
3315 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00003316}
3317
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003318/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3319/// which enumerates all conversion functions and performs overload resolution
3320/// to select the best.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321static void TryUserDefinedConversion(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003322 const InitializedEntity &Entity,
3323 const InitializationKind &Kind,
3324 Expr *Initializer,
3325 InitializationSequence &Sequence) {
Douglas Gregor1b303932009-12-22 15:35:07 +00003326 QualType DestType = Entity.getType();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003327 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3328 QualType SourceType = Initializer->getType();
3329 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3330 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003331
Douglas Gregor540c3b02009-12-14 17:27:33 +00003332 // Build the candidate set directly in the initialization sequence
3333 // structure, so that it will persist if we fail.
3334 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3335 CandidateSet.clear();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
Douglas Gregor540c3b02009-12-14 17:27:33 +00003337 // Determine whether we are allowed to call explicit constructors or
3338 // explicit conversion operators.
3339 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003340
Douglas Gregor540c3b02009-12-14 17:27:33 +00003341 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3342 // The type we're converting to is a class type. Enumerate its constructors
3343 // to see if there is a suitable conversion.
3344 CXXRecordDecl *DestRecordDecl
3345 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003346
Douglas Gregord9848152010-04-26 14:36:57 +00003347 // Try to complete the type we're converting to.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregord9848152010-04-26 14:36:57 +00003349 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00003350 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregord9848152010-04-26 14:36:57 +00003351 Con != ConEnd; ++Con) {
3352 NamedDecl *D = *Con;
3353 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354
Douglas Gregord9848152010-04-26 14:36:57 +00003355 // Find the constructor (which may be a template).
3356 CXXConstructorDecl *Constructor = 0;
3357 FunctionTemplateDecl *ConstructorTmpl
3358 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003359 if (ConstructorTmpl)
Douglas Gregord9848152010-04-26 14:36:57 +00003360 Constructor = cast<CXXConstructorDecl>(
3361 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor7c426592010-07-01 03:43:00 +00003362 else
Douglas Gregord9848152010-04-26 14:36:57 +00003363 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
Douglas Gregord9848152010-04-26 14:36:57 +00003365 if (!Constructor->isInvalidDecl() &&
3366 Constructor->isConvertingConstructor(AllowExplicit)) {
3367 if (ConstructorTmpl)
3368 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3369 /*ExplicitArgs*/ 0,
3370 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003371 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003372 else
3373 S.AddOverloadCandidate(Constructor, FoundDecl,
3374 &Initializer, 1, CandidateSet,
Douglas Gregor7c426592010-07-01 03:43:00 +00003375 /*SuppressUserConversions=*/true);
Douglas Gregord9848152010-04-26 14:36:57 +00003376 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003377 }
Douglas Gregord9848152010-04-26 14:36:57 +00003378 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003379 }
Eli Friedman78275202009-12-19 08:11:05 +00003380
3381 SourceLocation DeclLoc = Initializer->getLocStart();
3382
Douglas Gregor540c3b02009-12-14 17:27:33 +00003383 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3384 // The type we're converting from is a class type, enumerate its conversion
3385 // functions.
Eli Friedman78275202009-12-19 08:11:05 +00003386
Eli Friedman4afe9a32009-12-20 22:12:03 +00003387 // We can only enumerate the conversion functions for a complete type; if
3388 // the type isn't complete, simply skip this step.
3389 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3390 CXXRecordDecl *SourceRecordDecl
3391 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392
John McCallad371252010-01-20 00:46:10 +00003393 const UnresolvedSetImpl *Conversions
Eli Friedman4afe9a32009-12-20 22:12:03 +00003394 = SourceRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003395 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003396 E = Conversions->end();
Eli Friedman4afe9a32009-12-20 22:12:03 +00003397 I != E; ++I) {
3398 NamedDecl *D = *I;
3399 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3400 if (isa<UsingShadowDecl>(D))
3401 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402
Eli Friedman4afe9a32009-12-20 22:12:03 +00003403 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3404 CXXConversionDecl *Conv;
Douglas Gregor540c3b02009-12-14 17:27:33 +00003405 if (ConvTemplate)
Eli Friedman4afe9a32009-12-20 22:12:03 +00003406 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor540c3b02009-12-14 17:27:33 +00003407 else
John McCallda4458e2010-03-31 01:36:47 +00003408 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409
Eli Friedman4afe9a32009-12-20 22:12:03 +00003410 if (AllowExplicit || !Conv->isExplicit()) {
3411 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00003412 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCallb89836b2010-01-26 01:37:31 +00003413 ActingDC, Initializer, DestType,
Eli Friedman4afe9a32009-12-20 22:12:03 +00003414 CandidateSet);
3415 else
John McCalla0296f72010-03-19 07:35:19 +00003416 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCallb89836b2010-01-26 01:37:31 +00003417 Initializer, DestType, CandidateSet);
Eli Friedman4afe9a32009-12-20 22:12:03 +00003418 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003419 }
3420 }
3421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003422
3423 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003424 OverloadCandidateSet::iterator Best;
John McCall0d1da222010-01-12 00:44:57 +00003425 if (OverloadingResult Result
Douglas Gregord5b730c92010-09-12 08:07:23 +00003426 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor540c3b02009-12-14 17:27:33 +00003427 Sequence.SetOverloadFailure(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor540c3b02009-12-14 17:27:33 +00003429 Result);
3430 return;
3431 }
John McCall0d1da222010-01-12 00:44:57 +00003432
Douglas Gregor540c3b02009-12-14 17:27:33 +00003433 FunctionDecl *Function = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00003434 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Douglas Gregor540c3b02009-12-14 17:27:33 +00003436 if (isa<CXXConstructorDecl>(Function)) {
3437 // Add the user-defined conversion step. Any cv-qualification conversion is
3438 // subsumed by the initialization.
John McCalla0296f72010-03-19 07:35:19 +00003439 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor540c3b02009-12-14 17:27:33 +00003440 return;
3441 }
3442
3443 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003444 QualType ConvType = Function->getCallResultType();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003445 if (ConvType->getAs<RecordType>()) {
3446 // If we're converting to a class type, there may be an copy if
3447 // the resulting temporary object (possible to create an object of
3448 // a base class type). That copy is not a separate conversion, so
3449 // we just make a note of the actual destination type (possibly a
3450 // base class of the type returned by the conversion function) and
3451 // let the user-defined conversion step handle the conversion.
3452 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3453 return;
3454 }
Douglas Gregor540c3b02009-12-14 17:27:33 +00003455
Douglas Gregor5ab11652010-04-17 22:01:05 +00003456 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457
Douglas Gregor5ab11652010-04-17 22:01:05 +00003458 // If the conversion following the call to the conversion function
3459 // is interesting, add it as a separate step.
Douglas Gregor540c3b02009-12-14 17:27:33 +00003460 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3461 Best->FinalConversion.Third) {
3462 ImplicitConversionSequence ICS;
John McCall0d1da222010-01-12 00:44:57 +00003463 ICS.setStandard();
Douglas Gregor540c3b02009-12-14 17:27:33 +00003464 ICS.Standard = Best->FinalConversion;
3465 Sequence.AddConversionSequenceStep(ICS, DestType);
3466 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003467}
3468
John McCall31168b02011-06-15 23:02:42 +00003469/// The non-zero enum values here are indexes into diagnostic alternatives.
3470enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3471
3472/// Determines whether this expression is an acceptable ICR source.
John McCall63f84442011-06-27 23:59:58 +00003473static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3474 bool isAddressOf) {
John McCall31168b02011-06-15 23:02:42 +00003475 // Skip parens.
3476 e = e->IgnoreParens();
3477
3478 // Skip address-of nodes.
3479 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3480 if (op->getOpcode() == UO_AddrOf)
John McCall63f84442011-06-27 23:59:58 +00003481 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCall31168b02011-06-15 23:02:42 +00003482
3483 // Skip certain casts.
John McCall63f84442011-06-27 23:59:58 +00003484 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3485 switch (ce->getCastKind()) {
John McCall31168b02011-06-15 23:02:42 +00003486 case CK_Dependent:
3487 case CK_BitCast:
3488 case CK_LValueBitCast:
John McCall31168b02011-06-15 23:02:42 +00003489 case CK_NoOp:
John McCall63f84442011-06-27 23:59:58 +00003490 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003491
3492 case CK_ArrayToPointerDecay:
3493 return IIK_nonscalar;
3494
3495 case CK_NullToPointer:
3496 return IIK_okay;
3497
3498 default:
3499 break;
3500 }
3501
3502 // If we have a declaration reference, it had better be a local variable.
John McCall63f84442011-06-27 23:59:58 +00003503 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3504 if (!isAddressOf) return IIK_nonlocal;
3505
3506 VarDecl *var;
3507 if (isa<DeclRefExpr>(e)) {
3508 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3509 if (!var) return IIK_nonlocal;
3510 } else {
3511 var = cast<BlockDeclRefExpr>(e)->getDecl();
3512 }
3513
3514 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCall31168b02011-06-15 23:02:42 +00003515
3516 // If we have a conditional operator, check both sides.
3517 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCall63f84442011-06-27 23:59:58 +00003518 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCall31168b02011-06-15 23:02:42 +00003519 return iik;
3520
John McCall63f84442011-06-27 23:59:58 +00003521 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCall31168b02011-06-15 23:02:42 +00003522
3523 // These are never scalar.
3524 } else if (isa<ArraySubscriptExpr>(e)) {
3525 return IIK_nonscalar;
3526
3527 // Otherwise, it needs to be a null pointer constant.
3528 } else {
3529 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3530 ? IIK_okay : IIK_nonlocal);
3531 }
3532
3533 return IIK_nonlocal;
3534}
3535
3536/// Check whether the given expression is a valid operand for an
3537/// indirect copy/restore.
3538static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3539 assert(src->isRValue());
3540
John McCall63f84442011-06-27 23:59:58 +00003541 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCall31168b02011-06-15 23:02:42 +00003542 if (iik == IIK_okay) return;
3543
3544 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3545 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3546 << src->getSourceRange();
3547}
3548
Douglas Gregore2f943b2011-02-22 18:29:51 +00003549/// \brief Determine whether we have compatible array types for the
3550/// purposes of GNU by-copy array initialization.
3551static bool hasCompatibleArrayTypes(ASTContext &Context,
3552 const ArrayType *Dest,
3553 const ArrayType *Source) {
3554 // If the source and destination array types are equivalent, we're
3555 // done.
3556 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3557 return true;
3558
3559 // Make sure that the element types are the same.
3560 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3561 return false;
3562
3563 // The only mismatch we allow is when the destination is an
3564 // incomplete array type and the source is a constant array type.
3565 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3566}
3567
John McCall31168b02011-06-15 23:02:42 +00003568static bool tryObjCWritebackConversion(Sema &S,
3569 InitializationSequence &Sequence,
3570 const InitializedEntity &Entity,
3571 Expr *Initializer) {
3572 bool ArrayDecay = false;
3573 QualType ArgType = Initializer->getType();
3574 QualType ArgPointee;
3575 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3576 ArrayDecay = true;
3577 ArgPointee = ArgArrayType->getElementType();
3578 ArgType = S.Context.getPointerType(ArgPointee);
3579 }
3580
3581 // Handle write-back conversion.
3582 QualType ConvertedArgType;
3583 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3584 ConvertedArgType))
3585 return false;
3586
3587 // We should copy unless we're passing to an argument explicitly
3588 // marked 'out'.
3589 bool ShouldCopy = true;
3590 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3591 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3592
3593 // Do we need an lvalue conversion?
3594 if (ArrayDecay || Initializer->isGLValue()) {
3595 ImplicitConversionSequence ICS;
3596 ICS.setStandard();
3597 ICS.Standard.setAsIdentityConversion();
3598
3599 QualType ResultType;
3600 if (ArrayDecay) {
3601 ICS.Standard.First = ICK_Array_To_Pointer;
3602 ResultType = S.Context.getPointerType(ArgPointee);
3603 } else {
3604 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3605 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3606 }
3607
3608 Sequence.AddConversionSequenceStep(ICS, ResultType);
3609 }
3610
3611 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3612 return true;
3613}
3614
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003615InitializationSequence::InitializationSequence(Sema &S,
3616 const InitializedEntity &Entity,
3617 const InitializationKind &Kind,
3618 Expr **Args,
John McCallbc077cf2010-02-08 23:07:23 +00003619 unsigned NumArgs)
3620 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003621 ASTContext &Context = S.Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003622
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003623 // C++0x [dcl.init]p16:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624 // The semantics of initializers are as follows. The destination type is
3625 // the type of the object or reference being initialized and the source
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003626 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003627 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003628 // parenthesized list of expressions.
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003629 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003630
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003631 if (DestType->isDependentType() ||
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003632 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3633 SequenceKind = DependentSequence;
3634 return;
3635 }
3636
Sebastian Redld201edf2011-06-05 13:59:11 +00003637 // Almost everything is a normal sequence.
3638 setSequenceKind(NormalSequence);
3639
John McCalled75c092010-12-07 22:54:16 +00003640 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley01296292011-04-08 18:41:53 +00003641 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3642 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3643 if (Result.isInvalid()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003644 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley01296292011-04-08 18:41:53 +00003645 return;
3646 }
3647 Args[I] = Result.take();
3648 }
John McCalled75c092010-12-07 22:54:16 +00003649
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003650 QualType SourceType;
3651 Expr *Initializer = 0;
Douglas Gregor85dabae2009-12-16 01:38:02 +00003652 if (NumArgs == 1) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003653 Initializer = Args[0];
3654 if (!isa<InitListExpr>(Initializer))
3655 SourceType = Initializer->getType();
3656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657
3658 // - If the initializer is a braced-init-list, the object is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003659 // list-initialized (8.5.4).
3660 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003661 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregor51e77d52009-12-10 17:56:55 +00003662 return;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003665 // - If the destination type is a reference type, see 8.5.3.
3666 if (DestType->isReferenceType()) {
3667 // C++0x [dcl.init.ref]p1:
3668 // A variable declared to be a T& or T&&, that is, "reference to type T"
3669 // (8.3.2), shall be initialized by an object, or function, of type T or
3670 // by an object that can be converted into a T.
3671 // (Therefore, multiple arguments are not permitted.)
3672 if (NumArgs != 1)
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003673 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003674 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003675 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003676 return;
3677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003679 // - If the initializer is (), the object is value-initialized.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003680 if (Kind.getKind() == InitializationKind::IK_Value ||
3681 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003682 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003683 return;
3684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003685
Douglas Gregor85dabae2009-12-16 01:38:02 +00003686 // Handle default initialization.
Nick Lewycky9331ed82010-11-20 01:29:55 +00003687 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003688 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003689 return;
3690 }
Douglas Gregore1314a62009-12-18 05:02:21 +00003691
John McCall66884dd2011-02-21 07:22:22 +00003692 // - If the destination type is an array of characters, an array of
3693 // char16_t, an array of char32_t, or an array of wchar_t, and the
3694 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003695 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003696 // ill-formed.
Douglas Gregore2f943b2011-02-22 18:29:51 +00003697 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3698 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003699 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCall66884dd2011-02-21 07:22:22 +00003700 return;
3701 }
3702
Douglas Gregore2f943b2011-02-22 18:29:51 +00003703 // Note: as an GNU C extension, we allow initialization of an
3704 // array from a compound literal that creates an array of the same
3705 // type, so long as the initializer has no side effects.
3706 if (!S.getLangOptions().CPlusPlus && Initializer &&
3707 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3708 Initializer->getType()->isArrayType()) {
3709 const ArrayType *SourceAT
3710 = Context.getAsArrayType(Initializer->getType());
3711 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003712 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003713 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003714 SetFailed(FK_NonConstantArrayInit);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003715 else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003716 AddArrayInitStep(DestType);
Douglas Gregore2f943b2011-02-22 18:29:51 +00003717 }
3718 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003719 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003720 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003721 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003723 return;
3724 }
Eli Friedman78275202009-12-19 08:11:05 +00003725
John McCall31168b02011-06-15 23:02:42 +00003726 // Determine whether we should consider writeback conversions for
3727 // Objective-C ARC.
3728 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3729 Entity.getKind() == InitializedEntity::EK_Parameter;
3730
3731 // We're at the end of the line for C: it's either a write-back conversion
3732 // or it's a C assignment. There's no need to check anything else.
Eli Friedman78275202009-12-19 08:11:05 +00003733 if (!S.getLangOptions().CPlusPlus) {
John McCall31168b02011-06-15 23:02:42 +00003734 // If allowed, check whether this is an Objective-C writeback conversion.
3735 if (allowObjCWritebackConversion &&
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003736 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCall31168b02011-06-15 23:02:42 +00003737 return;
3738 }
3739
3740 // Handle initialization in C
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003741 AddCAssignmentStep(DestType);
3742 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedman78275202009-12-19 08:11:05 +00003743 return;
3744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
John McCall31168b02011-06-15 23:02:42 +00003746 assert(S.getLangOptions().CPlusPlus);
3747
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003748 // - If the destination type is a (possibly cv-qualified) class type:
3749 if (DestType->isRecordType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003750 // - If the initialization is direct-initialization, or if it is
3751 // copy-initialization where the cv-unqualified version of the
3752 // source type is the same class as, or a derived class of, the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003753 // class of the destination, constructors are considered. [...]
3754 if (Kind.getKind() == InitializationKind::IK_Direct ||
3755 (Kind.getKind() == InitializationKind::IK_Copy &&
3756 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3757 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003759 Entity.getType(), *this);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003761 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762 // type to the destination type or (when a conversion function is
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003763 // used) to a derived class thereof are enumerated as described in
3764 // 13.3.1.4, and the best one is chosen through overload resolution
3765 // (13.3).
3766 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003767 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003768 return;
3769 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003770
Douglas Gregor85dabae2009-12-16 01:38:02 +00003771 if (NumArgs > 1) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003772 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003773 return;
3774 }
3775 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776
3777 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003778 // type, conversion functions are considered.
Douglas Gregor85dabae2009-12-16 01:38:02 +00003779 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003780 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3781 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003782 return;
3783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003785 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor540c3b02009-12-14 17:27:33 +00003786 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003787 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788 // initializer expression to the cv-unqualified version of the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003789 // destination type; no user-defined conversions are considered.
John McCall31168b02011-06-15 23:02:42 +00003790
3791 ImplicitConversionSequence ICS
3792 = S.TryImplicitConversion(Initializer, Entity.getType(),
3793 /*SuppressUserConversions*/true,
John McCallec6f4e92010-06-04 02:29:22 +00003794 /*AllowExplicitConversions*/ false,
Douglas Gregor58281352011-01-27 00:58:17 +00003795 /*InOverloadResolution*/ false,
John McCall31168b02011-06-15 23:02:42 +00003796 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3797 allowObjCWritebackConversion);
3798
3799 if (ICS.isStandard() &&
3800 ICS.Standard.Second == ICK_Writeback_Conversion) {
3801 // Objective-C ARC writeback conversion.
3802
3803 // We should copy unless we're passing to an argument explicitly
3804 // marked 'out'.
3805 bool ShouldCopy = true;
3806 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3807 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3808
3809 // If there was an lvalue adjustment, add it as a separate conversion.
3810 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3811 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3812 ImplicitConversionSequence LvalueICS;
3813 LvalueICS.setStandard();
3814 LvalueICS.Standard.setAsIdentityConversion();
3815 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3816 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003817 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCall31168b02011-06-15 23:02:42 +00003818 }
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003819
3820 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCall31168b02011-06-15 23:02:42 +00003821 } else if (ICS.isBad()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00003822 DeclAccessPair dap;
3823 if (Initializer->getType() == Context.OverloadTy &&
3824 !S.ResolveAddressOfOverloadedFunction(Initializer
3825 , DestType, false, dap))
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003826 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003827 else
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003828 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCall31168b02011-06-15 23:02:42 +00003829 } else {
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003830 AddConversionSequenceStep(ICS, Entity.getType());
John McCallfa272342011-06-16 23:24:51 +00003831
Rafael Espindola699fc4d2011-07-14 22:58:04 +00003832 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregore81f58e2010-11-08 03:40:48 +00003833 }
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003834}
3835
3836InitializationSequence::~InitializationSequence() {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003837 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003838 StepEnd = Steps.end();
3839 Step != StepEnd; ++Step)
3840 Step->Destroy();
3841}
3842
3843//===----------------------------------------------------------------------===//
3844// Perform initialization
3845//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846static Sema::AssignmentAction
Douglas Gregore1314a62009-12-18 05:02:21 +00003847getAssignmentAction(const InitializedEntity &Entity) {
3848 switch(Entity.getKind()) {
3849 case InitializedEntity::EK_Variable:
3850 case InitializedEntity::EK_New:
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003851 case InitializedEntity::EK_Exception:
3852 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003853 case InitializedEntity::EK_Delegating:
Douglas Gregore1314a62009-12-18 05:02:21 +00003854 return Sema::AA_Initializing;
3855
3856 case InitializedEntity::EK_Parameter:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003857 if (Entity.getDecl() &&
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00003858 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3859 return Sema::AA_Sending;
3860
Douglas Gregore1314a62009-12-18 05:02:21 +00003861 return Sema::AA_Passing;
3862
3863 case InitializedEntity::EK_Result:
3864 return Sema::AA_Returning;
3865
Douglas Gregore1314a62009-12-18 05:02:21 +00003866 case InitializedEntity::EK_Temporary:
3867 // FIXME: Can we tell apart casting vs. converting?
3868 return Sema::AA_Casting;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869
Douglas Gregore1314a62009-12-18 05:02:21 +00003870 case InitializedEntity::EK_Member:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003871 case InitializedEntity::EK_ArrayElement:
3872 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003873 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003874 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003875 return Sema::AA_Initializing;
3876 }
3877
3878 return Sema::AA_Converting;
3879}
3880
Douglas Gregor95562572010-04-24 23:45:46 +00003881/// \brief Whether we should binding a created object as a temporary when
3882/// initializing the given entity.
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003883static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregore1314a62009-12-18 05:02:21 +00003884 switch (Entity.getKind()) {
Anders Carlsson0bd52402010-01-24 00:19:41 +00003885 case InitializedEntity::EK_ArrayElement:
3886 case InitializedEntity::EK_Member:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003887 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003888 case InitializedEntity::EK_New:
3889 case InitializedEntity::EK_Variable:
3890 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003891 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00003892 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003893 case InitializedEntity::EK_ComplexElement:
Anders Carlssonfcd764a2010-02-06 23:23:06 +00003894 case InitializedEntity::EK_Exception:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003895 case InitializedEntity::EK_BlockElement:
Douglas Gregore1314a62009-12-18 05:02:21 +00003896 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897
Douglas Gregore1314a62009-12-18 05:02:21 +00003898 case InitializedEntity::EK_Parameter:
3899 case InitializedEntity::EK_Temporary:
3900 return true;
3901 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003902
Douglas Gregore1314a62009-12-18 05:02:21 +00003903 llvm_unreachable("missed an InitializedEntity kind?");
3904}
3905
Douglas Gregor95562572010-04-24 23:45:46 +00003906/// \brief Whether the given entity, when initialized with an object
3907/// created for that initialization, requires destruction.
3908static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3909 switch (Entity.getKind()) {
3910 case InitializedEntity::EK_Member:
3911 case InitializedEntity::EK_Result:
3912 case InitializedEntity::EK_New:
3913 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00003914 case InitializedEntity::EK_Delegating:
Douglas Gregor95562572010-04-24 23:45:46 +00003915 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00003916 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00003917 case InitializedEntity::EK_BlockElement:
Douglas Gregor95562572010-04-24 23:45:46 +00003918 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919
Douglas Gregor95562572010-04-24 23:45:46 +00003920 case InitializedEntity::EK_Variable:
3921 case InitializedEntity::EK_Parameter:
3922 case InitializedEntity::EK_Temporary:
3923 case InitializedEntity::EK_ArrayElement:
3924 case InitializedEntity::EK_Exception:
3925 return true;
3926 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927
3928 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor95562572010-04-24 23:45:46 +00003929}
3930
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003931/// \brief Make a (potentially elidable) temporary copy of the object
3932/// provided by the given initializer by calling the appropriate copy
3933/// constructor.
3934///
3935/// \param S The Sema object used for type-checking.
3936///
Abramo Bagnara92141d22011-01-27 19:55:10 +00003937/// \param T The type of the temporary object, which must either be
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003938/// the type of the initializer expression or a superclass thereof.
3939///
3940/// \param Enter The entity being initialized.
3941///
3942/// \param CurInit The initializer expression.
3943///
3944/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3945/// is permitted in C++03 (but not C++0x) when binding a reference to
3946/// an rvalue.
3947///
3948/// \returns An expression that copies the initializer expression into
3949/// a temporary object, or an error expression if a copy could not be
3950/// created.
John McCalldadc5752010-08-24 06:29:42 +00003951static ExprResult CopyObject(Sema &S,
Douglas Gregord5b730c92010-09-12 08:07:23 +00003952 QualType T,
3953 const InitializedEntity &Entity,
3954 ExprResult CurInit,
3955 bool IsExtraneousCopy) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003956 // Determine which class type we're copying to.
Anders Carlsson0bd52402010-01-24 00:19:41 +00003957 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003958 CXXRecordDecl *Class = 0;
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00003959 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003960 Class = cast<CXXRecordDecl>(Record->getDecl());
3961 if (!Class)
3962 return move(CurInit);
3963
Douglas Gregor5d369002011-01-21 18:05:27 +00003964 // C++0x [class.copy]p32:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003965 // When certain criteria are met, an implementation is allowed to
3966 // omit the copy/move construction of a class object, even if the
3967 // copy/move constructor and/or destructor for the object have
3968 // side effects. [...]
3969 // - when a temporary class object that has not been bound to a
3970 // reference (12.2) would be copied/moved to a class object
3971 // with the same cv-unqualified type, the copy/move operation
3972 // can be omitted by constructing the temporary object
3973 // directly into the target of the omitted copy/move
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003974 //
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003975 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003976 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor222cf0e2010-05-15 00:13:29 +00003978 // is handled by the run-time.
John McCall7a626f62010-09-15 10:14:12 +00003979 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00003980 SourceLocation Loc;
Douglas Gregore1314a62009-12-18 05:02:21 +00003981 switch (Entity.getKind()) {
3982 case InitializedEntity::EK_Result:
Douglas Gregore1314a62009-12-18 05:02:21 +00003983 Loc = Entity.getReturnLoc();
3984 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003985
Douglas Gregore1314a62009-12-18 05:02:21 +00003986 case InitializedEntity::EK_Exception:
Douglas Gregore1314a62009-12-18 05:02:21 +00003987 Loc = Entity.getThrowLoc();
3988 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003989
Douglas Gregore1314a62009-12-18 05:02:21 +00003990 case InitializedEntity::EK_Variable:
Douglas Gregora4b592a2009-12-19 03:01:41 +00003991 Loc = Entity.getDecl()->getLocation();
3992 break;
3993
Anders Carlsson0bd52402010-01-24 00:19:41 +00003994 case InitializedEntity::EK_ArrayElement:
3995 case InitializedEntity::EK_Member:
Douglas Gregore1314a62009-12-18 05:02:21 +00003996 case InitializedEntity::EK_Parameter:
Douglas Gregore1314a62009-12-18 05:02:21 +00003997 case InitializedEntity::EK_Temporary:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00003998 case InitializedEntity::EK_New:
Douglas Gregore1314a62009-12-18 05:02:21 +00003999 case InitializedEntity::EK_Base:
Alexis Hunt61bc1732011-05-01 07:04:31 +00004000 case InitializedEntity::EK_Delegating:
Anders Carlssoned8d80d2010-01-23 04:34:47 +00004001 case InitializedEntity::EK_VectorElement:
Eli Friedman6b9c41e2011-09-19 23:17:44 +00004002 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian28ed9272010-06-07 16:14:00 +00004003 case InitializedEntity::EK_BlockElement:
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004004 Loc = CurInitExpr->getLocStart();
4005 break;
Douglas Gregore1314a62009-12-18 05:02:21 +00004006 }
Douglas Gregord5c231e2010-04-24 21:09:25 +00004007
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004008 // Make sure that the type we are copying is complete.
Douglas Gregord5c231e2010-04-24 21:09:25 +00004009 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4010 return move(CurInit);
4011
Douglas Gregorf282a762011-01-21 19:38:21 +00004012 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregore1314a62009-12-18 05:02:21 +00004013 DeclContext::lookup_iterator Con, ConEnd;
John McCallbc077cf2010-02-08 23:07:23 +00004014 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregor52b72822010-07-02 23:12:18 +00004015 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregore1314a62009-12-18 05:02:21 +00004016 Con != ConEnd; ++Con) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004017 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregorcbd07102010-11-12 03:34:06 +00004018 // C++0x [dcl.init]p16, second bullet to class types, this
4019 // initialization is direct-initialization.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004020 CXXConstructorDecl *Constructor = 0;
4021
4022 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorf282a762011-01-21 19:38:21 +00004023 // Handle copy/moveconstructors, only.
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004024 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorf282a762011-01-21 19:38:21 +00004025 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregorcbd07102010-11-12 03:34:06 +00004026 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004027 continue;
4028
4029 DeclAccessPair FoundDecl
4030 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4031 S.AddOverloadCandidate(Constructor, FoundDecl,
4032 &CurInitExpr, 1, CandidateSet);
4033 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004034 }
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004035
4036 // Handle constructor templates.
4037 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4038 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregore1314a62009-12-18 05:02:21 +00004039 continue;
John McCalla0296f72010-03-19 07:35:19 +00004040
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004041 Constructor = cast<CXXConstructorDecl>(
4042 ConstructorTmpl->getTemplatedDecl());
Douglas Gregorcbd07102010-11-12 03:34:06 +00004043 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004044 continue;
4045
4046 // FIXME: Do we need to limit this to copy-constructor-like
4047 // candidates?
John McCalla0296f72010-03-19 07:35:19 +00004048 DeclAccessPair FoundDecl
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004049 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4050 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4051 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053
Douglas Gregore1314a62009-12-18 05:02:21 +00004054 OverloadCandidateSet::iterator Best;
Chandler Carruth30141632011-02-25 19:41:05 +00004055 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004056 case OR_Success:
4057 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058
Douglas Gregore1314a62009-12-18 05:02:21 +00004059 case OR_No_Viable_Function:
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004060 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4061 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4062 : diag::err_temp_copy_no_viable)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004063 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004064 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004065 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004066 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallfaf5fb42010-08-26 23:41:50 +00004067 return ExprError();
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004068 return move(CurInit);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004069
Douglas Gregore1314a62009-12-18 05:02:21 +00004070 case OR_Ambiguous:
4071 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004072 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004073 << CurInitExpr->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004074 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallfaf5fb42010-08-26 23:41:50 +00004075 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076
Douglas Gregore1314a62009-12-18 05:02:21 +00004077 case OR_Deleted:
4078 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregora4b592a2009-12-19 03:01:41 +00004079 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregore1314a62009-12-18 05:02:21 +00004080 << CurInitExpr->getSourceRange();
4081 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004082 << 1 << Best->Function->isDeleted();
John McCallfaf5fb42010-08-26 23:41:50 +00004083 return ExprError();
Douglas Gregore1314a62009-12-18 05:02:21 +00004084 }
4085
Douglas Gregor5ab11652010-04-17 22:01:05 +00004086 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCall37ad5512010-08-23 06:44:23 +00004087 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor5ab11652010-04-17 22:01:05 +00004088 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004089
Anders Carlssona01874b2010-04-21 18:47:17 +00004090 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00004091 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004092
4093 if (IsExtraneousCopy) {
4094 // If this is a totally extraneous copy for C++03 reference
4095 // binding purposes, just return the original initialization
Douglas Gregor30b52772010-04-18 07:57:34 +00004096 // expression. We don't generate an (elided) copy operation here
4097 // because doing so would require us to pass down a flag to avoid
4098 // infinite recursion, where each step adds another extraneous,
4099 // elidable copy.
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004100
Douglas Gregor30b52772010-04-18 07:57:34 +00004101 // Instantiate the default arguments of any extra parameters in
4102 // the selected copy constructor, as if we were going to create a
4103 // proper call to the copy constructor.
4104 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4105 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4106 if (S.RequireCompleteType(Loc, Parm->getType(),
4107 S.PDiag(diag::err_call_incomplete_argument)))
4108 break;
4109
4110 // Build the default argument expression; we don't actually care
4111 // if this succeeds or not, because this routine will complain
4112 // if there was a problem.
4113 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4114 }
4115
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004116 return S.Owned(CurInitExpr);
4117 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004118
Chandler Carruth30141632011-02-25 19:41:05 +00004119 S.MarkDeclarationReferenced(Loc, Constructor);
4120
Douglas Gregor5ab11652010-04-17 22:01:05 +00004121 // Determine the arguments required to actually perform the
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004122 // constructor call (we might have derived-to-base conversions, or
4123 // the copy constructor may have default arguments).
John McCallfaf5fb42010-08-26 23:41:50 +00004124 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor5ab11652010-04-17 22:01:05 +00004125 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004126 return ExprError();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004127
Douglas Gregord0ace022010-04-25 00:55:24 +00004128 // Actually perform the constructor call.
4129 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCallbfd822c2010-08-24 07:32:53 +00004130 move_arg(ConstructorArgs),
4131 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004132 CXXConstructExpr::CK_Complete,
4133 SourceRange());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134
Douglas Gregord0ace022010-04-25 00:55:24 +00004135 // If we're supposed to bind temporaries, do so.
4136 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4137 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4138 return move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004139}
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004140
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004141void InitializationSequence::PrintInitLocationNote(Sema &S,
4142 const InitializedEntity &Entity) {
4143 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4144 if (Entity.getDecl()->getLocation().isInvalid())
4145 return;
4146
4147 if (Entity.getDecl()->getDeclName())
4148 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4149 << Entity.getDecl()->getDeclName();
4150 else
4151 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4152 }
4153}
4154
Sebastian Redl112aa822011-07-14 19:07:55 +00004155static bool isReferenceBinding(const InitializationSequence::Step &s) {
4156 return s.Kind == InitializationSequence::SK_BindReference ||
4157 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4158}
4159
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160ExprResult
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004161InitializationSequence::Perform(Sema &S,
4162 const InitializedEntity &Entity,
4163 const InitializationKind &Kind,
John McCallfaf5fb42010-08-26 23:41:50 +00004164 MultiExprArg Args,
Douglas Gregor51e77d52009-12-10 17:56:55 +00004165 QualType *ResultType) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004166 if (Failed()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004167 unsigned NumArgs = Args.size();
4168 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallfaf5fb42010-08-26 23:41:50 +00004169 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004171
Sebastian Redld201edf2011-06-05 13:59:11 +00004172 if (getKind() == DependentSequence) {
Douglas Gregor51e77d52009-12-10 17:56:55 +00004173 // If the declaration is a non-dependent, incomplete array type
4174 // that has an initializer, then its type will be completed once
4175 // the initializer is instantiated.
Douglas Gregor1b303932009-12-22 15:35:07 +00004176 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregor51e77d52009-12-10 17:56:55 +00004177 Args.size() == 1) {
Douglas Gregor1b303932009-12-22 15:35:07 +00004178 QualType DeclType = Entity.getType();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004179 if (const IncompleteArrayType *ArrayT
4180 = S.Context.getAsIncompleteArrayType(DeclType)) {
4181 // FIXME: We don't currently have the ability to accurately
4182 // compute the length of an initializer list without
4183 // performing full type-checking of the initializer list
4184 // (since we have to determine where braces are implicitly
4185 // introduced and such). So, we fall back to making the array
4186 // type a dependently-sized array type with no specified
4187 // bound.
4188 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4189 SourceRange Brackets;
Douglas Gregor1b303932009-12-22 15:35:07 +00004190
Douglas Gregor51e77d52009-12-10 17:56:55 +00004191 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregor1b303932009-12-22 15:35:07 +00004192 if (DeclaratorDecl *DD = Entity.getDecl()) {
4193 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4194 TypeLoc TL = TInfo->getTypeLoc();
4195 if (IncompleteArrayTypeLoc *ArrayLoc
4196 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4197 Brackets = ArrayLoc->getBracketsRange();
4198 }
Douglas Gregor51e77d52009-12-10 17:56:55 +00004199 }
4200
4201 *ResultType
4202 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4203 /*NumElts=*/0,
4204 ArrayT->getSizeModifier(),
4205 ArrayT->getIndexTypeCVRQualifiers(),
4206 Brackets);
4207 }
4208
4209 }
4210 }
Manuel Klimekf2b4b692011-06-22 20:02:16 +00004211 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4212 Kind.isExplicitCast());
4213 return ExprResult(Args.release()[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004214 }
4215
Sebastian Redld201edf2011-06-05 13:59:11 +00004216 // No steps means no initialization.
4217 if (Steps.empty())
Douglas Gregor85dabae2009-12-16 01:38:02 +00004218 return S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219
Douglas Gregor1b303932009-12-22 15:35:07 +00004220 QualType DestType = Entity.getType().getNonReferenceType();
4221 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedman463e5232009-12-22 02:10:53 +00004222 // the same as Entity.getDecl()->getType() in cases involving type merging,
4223 // and we want latter when it makes sense.
Douglas Gregor51e77d52009-12-10 17:56:55 +00004224 if (ResultType)
Eli Friedman463e5232009-12-22 02:10:53 +00004225 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregor1b303932009-12-22 15:35:07 +00004226 Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004227
John McCalldadc5752010-08-24 06:29:42 +00004228 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230 // For initialization steps that start with a single initializer,
Douglas Gregor85dabae2009-12-16 01:38:02 +00004231 // grab the only argument out the Args and place it into the "current"
4232 // initializer.
4233 switch (Steps.front().Kind) {
Douglas Gregore1314a62009-12-18 05:02:21 +00004234 case SK_ResolveAddressOfOverloadedFunction:
4235 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004236 case SK_CastDerivedToBaseXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004237 case SK_CastDerivedToBaseLValue:
4238 case SK_BindReference:
4239 case SK_BindReferenceToTemporary:
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004240 case SK_ExtraneousCopyToTemporary:
Douglas Gregore1314a62009-12-18 05:02:21 +00004241 case SK_UserConversion:
4242 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004243 case SK_QualificationConversionXValue:
Douglas Gregore1314a62009-12-18 05:02:21 +00004244 case SK_QualificationConversionRValue:
4245 case SK_ConversionSequence:
4246 case SK_ListInitialization:
4247 case SK_CAssignment:
Eli Friedman78275202009-12-19 08:11:05 +00004248 case SK_StringInit:
Douglas Gregore2f943b2011-02-22 18:29:51 +00004249 case SK_ObjCObjectConversion:
John McCall31168b02011-06-15 23:02:42 +00004250 case SK_ArrayInit:
4251 case SK_PassByIndirectCopyRestore:
4252 case SK_PassByIndirectRestore:
4253 case SK_ProduceObjCObject: {
Douglas Gregore1314a62009-12-18 05:02:21 +00004254 assert(Args.size() == 1);
John Wiegley01296292011-04-08 18:41:53 +00004255 CurInit = Args.get()[0];
4256 if (!CurInit.get()) return ExprError();
John McCall34376a62010-12-04 03:47:34 +00004257
4258 // Read from a property when initializing something with it.
John Wiegley01296292011-04-08 18:41:53 +00004259 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4260 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4261 if (CurInit.isInvalid())
4262 return ExprError();
4263 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004264 break;
John McCall34376a62010-12-04 03:47:34 +00004265 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004266
Douglas Gregore1314a62009-12-18 05:02:21 +00004267 case SK_ConstructorInitialization:
4268 case SK_ZeroInitialization:
4269 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004270 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271
4272 // Walk through the computed steps for the initialization sequence,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004273 // performing the specified conversions along the way.
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004274 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004275 for (step_iterator Step = step_begin(), StepEnd = step_end();
4276 Step != StepEnd; ++Step) {
4277 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004278 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004279
John Wiegley01296292011-04-08 18:41:53 +00004280 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004282 switch (Step->Kind) {
4283 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284 // Overload resolution determined which function invoke; update the
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004285 // initializer to reflect that choice.
John Wiegley01296292011-04-08 18:41:53 +00004286 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00004287 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCall760af172010-02-01 03:16:54 +00004288 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall16df1e52010-03-30 21:47:33 +00004289 Step->Function.FoundDecl,
John McCalla0296f72010-03-19 07:35:19 +00004290 Step->Function.Function);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004291 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004293 case SK_CastDerivedToBaseRValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004294 case SK_CastDerivedToBaseXValue:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004295 case SK_CastDerivedToBaseLValue: {
4296 // We have a derived-to-base cast that produces either an rvalue or an
4297 // lvalue. Perform that cast.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298
John McCallcf142162010-08-07 06:22:56 +00004299 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00004300
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004301 // Casts to inaccessible base classes are allowed with C-style casts.
4302 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4303 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley01296292011-04-08 18:41:53 +00004304 CurInit.get()->getLocStart(),
4305 CurInit.get()->getSourceRange(),
Anders Carlssona70cff62010-04-24 19:06:50 +00004306 &BasePath, IgnoreBaseAccess))
John McCallfaf5fb42010-08-26 23:41:50 +00004307 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308
Douglas Gregor88d292c2010-05-13 16:44:06 +00004309 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4310 QualType T = SourceType;
4311 if (const PointerType *Pointer = T->getAs<PointerType>())
4312 T = Pointer->getPointeeType();
4313 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley01296292011-04-08 18:41:53 +00004314 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004315 cast<CXXRecordDecl>(RecordTy->getDecl()));
4316 }
4317
John McCall2536c6d2010-08-25 10:28:54 +00004318 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004319 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004320 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004321 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004322 VK_XValue :
4323 VK_RValue);
John McCallcf142162010-08-07 06:22:56 +00004324 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4325 Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004326 CK_DerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00004327 CurInit.get(),
4328 &BasePath, VK));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004329 break;
4330 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004332 case SK_BindReference:
John Wiegley01296292011-04-08 18:41:53 +00004333 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004334 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4335 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregor1b303932009-12-22 15:35:07 +00004336 << Entity.getType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004337 << BitField->getDeclName()
John Wiegley01296292011-04-08 18:41:53 +00004338 << CurInit.get()->getSourceRange();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004339 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallfaf5fb42010-08-26 23:41:50 +00004340 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004341 }
Anders Carlssona91be642010-01-29 02:47:33 +00004342
John Wiegley01296292011-04-08 18:41:53 +00004343 if (CurInit.get()->refersToVectorElement()) {
John McCallc17ae442010-02-02 19:02:38 +00004344 // References cannot bind to vector elements.
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004345 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4346 << Entity.getType().isVolatileQualified()
John Wiegley01296292011-04-08 18:41:53 +00004347 << CurInit.get()->getSourceRange();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004348 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004349 return ExprError();
Anders Carlsson8abde4b2010-01-31 17:18:49 +00004350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004352 // Reference binding does not have any corresponding ASTs.
4353
4354 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004355 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004356 return ExprError();
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004357
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004358 break;
Anders Carlssonab0ddb52010-01-31 18:34:51 +00004359
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004360 case SK_BindReferenceToTemporary:
4361 // Check exception specifications
John Wiegley01296292011-04-08 18:41:53 +00004362 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallfaf5fb42010-08-26 23:41:50 +00004363 return ExprError();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004364
Douglas Gregorfe314812011-06-21 17:03:29 +00004365 // Materialize the temporary into memory.
Douglas Gregor2fa40a32011-06-22 15:05:02 +00004366 CurInit = new (S.Context) MaterializeTemporaryExpr(
4367 Entity.getType().getNonReferenceType(),
4368 CurInit.get(),
Douglas Gregorfe314812011-06-21 17:03:29 +00004369 Entity.getType()->isLValueReferenceType());
Douglas Gregor58df5092011-06-22 16:12:01 +00004370
4371 // If we're binding to an Objective-C object that has lifetime, we
4372 // need cleanups.
4373 if (S.getLangOptions().ObjCAutoRefCount &&
4374 CurInit.get()->getType()->isObjCLifetimeType())
4375 S.ExprNeedsCleanups = true;
4376
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004377 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004378
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004379 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004380 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004381 /*IsExtraneousCopy=*/true);
4382 break;
4383
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004384 case SK_UserConversion: {
4385 // We have a user-defined conversion that invokes either a constructor
4386 // or a conversion function.
John McCall8cb679e2010-11-15 09:13:47 +00004387 CastKind CastKind;
Douglas Gregore1314a62009-12-18 05:02:21 +00004388 bool IsCopy = false;
John McCalla0296f72010-03-19 07:35:19 +00004389 FunctionDecl *Fn = Step->Function.Function;
4390 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor95562572010-04-24 23:45:46 +00004391 bool CreatedObject = false;
Douglas Gregor031296e2010-03-25 00:20:38 +00004392 bool IsLvalue = false;
John McCall760af172010-02-01 03:16:54 +00004393 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004394 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004395 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley01296292011-04-08 18:41:53 +00004396 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004397 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCall760af172010-02-01 03:16:54 +00004398
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004399 // Determine the arguments required to actually perform the constructor
4400 // call.
John Wiegley01296292011-04-08 18:41:53 +00004401 Expr *Arg = CurInit.get();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004402 if (S.CompleteConstructorCall(Constructor,
John Wiegley01296292011-04-08 18:41:53 +00004403 MultiExprArg(&Arg, 1),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004404 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004405 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004407 // Build the an expression that constructs a temporary.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00004409 move_arg(ConstructorArgs),
4410 /*ZeroInit*/ false,
Chandler Carruth01718152010-10-25 08:47:36 +00004411 CXXConstructExpr::CK_Complete,
4412 SourceRange());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004413 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004414 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004415
Anders Carlssona01874b2010-04-21 18:47:17 +00004416 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004417 FoundFn.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004418 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004419
John McCalle3027922010-08-25 11:45:40 +00004420 CastKind = CK_ConstructorConversion;
Douglas Gregore1314a62009-12-18 05:02:21 +00004421 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4422 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4423 S.IsDerivedFrom(SourceType, Class))
4424 IsCopy = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004425
Douglas Gregor95562572010-04-24 23:45:46 +00004426 CreatedObject = true;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004427 } else {
4428 // Build a call to the conversion function.
John McCall760af172010-02-01 03:16:54 +00004429 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregor031296e2010-03-25 00:20:38 +00004430 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley01296292011-04-08 18:41:53 +00004431 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCalla0296f72010-03-19 07:35:19 +00004432 FoundFn);
John McCall4fa0d5f2010-05-06 18:15:07 +00004433 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004434
4435 // FIXME: Should we move this initialization into a separate
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004436 // derived-to-base conversion? I believe the answer is "no", because
4437 // we don't want to turn off access control here for c-style casts.
John Wiegley01296292011-04-08 18:41:53 +00004438 ExprResult CurInitExprRes =
4439 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4440 FoundFn, Conversion);
4441 if(CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004442 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004443 CurInit = move(CurInitExprRes);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004445 // Build the actual call to the conversion function.
John Wiegley01296292011-04-08 18:41:53 +00004446 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004447 if (CurInit.isInvalid() || !CurInit.get())
John McCallfaf5fb42010-08-26 23:41:50 +00004448 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449
John McCalle3027922010-08-25 11:45:40 +00004450 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004451
Douglas Gregor95562572010-04-24 23:45:46 +00004452 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004454
Sebastian Redl112aa822011-07-14 19:07:55 +00004455 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004456 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004457 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor95562572010-04-24 23:45:46 +00004458 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley01296292011-04-08 18:41:53 +00004459 QualType T = CurInit.get()->getType();
Douglas Gregor95562572010-04-24 23:45:46 +00004460 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004461 CXXDestructorDecl *Destructor
Douglas Gregore71edda2010-07-01 22:47:18 +00004462 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley01296292011-04-08 18:41:53 +00004463 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor95562572010-04-24 23:45:46 +00004464 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley01296292011-04-08 18:41:53 +00004465 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4466 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor95562572010-04-24 23:45:46 +00004467 }
4468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004469
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004470 // FIXME: xvalues
John McCallcf142162010-08-07 06:22:56 +00004471 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley01296292011-04-08 18:41:53 +00004472 CurInit.get()->getType(),
4473 CastKind, CurInit.get(), 0,
John McCall2536c6d2010-08-25 10:28:54 +00004474 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004476 if (RequiresCopy)
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00004477 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4478 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004479
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004480 break;
4481 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004482
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004483 case SK_QualificationConversionLValue:
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004484 case SK_QualificationConversionXValue:
4485 case SK_QualificationConversionRValue: {
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004486 // Perform a qualification conversion; these can never go wrong.
John McCall2536c6d2010-08-25 10:28:54 +00004487 ExprValueKind VK =
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004488 Step->Kind == SK_QualificationConversionLValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004489 VK_LValue :
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004490 (Step->Kind == SK_QualificationConversionXValue ?
John McCall2536c6d2010-08-25 10:28:54 +00004491 VK_XValue :
4492 VK_RValue);
John Wiegley01296292011-04-08 18:41:53 +00004493 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004494 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004495 }
4496
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004497 case SK_ConversionSequence: {
John McCall31168b02011-06-15 23:02:42 +00004498 Sema::CheckedConversionKind CCK
4499 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4500 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4501 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4502 : Sema::CCK_ImplicitConversion;
John Wiegley01296292011-04-08 18:41:53 +00004503 ExprResult CurInitExprRes =
4504 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCall31168b02011-06-15 23:02:42 +00004505 getAssignmentAction(Entity), CCK);
John Wiegley01296292011-04-08 18:41:53 +00004506 if (CurInitExprRes.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004507 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00004508 CurInit = move(CurInitExprRes);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004509 break;
Douglas Gregor5c8ffab2010-04-16 19:30:02 +00004510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004511
Douglas Gregor51e77d52009-12-10 17:56:55 +00004512 case SK_ListInitialization: {
John Wiegley01296292011-04-08 18:41:53 +00004513 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004514 QualType Ty = Step->Type;
Douglas Gregor723796a2009-12-16 06:35:08 +00004515 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallfaf5fb42010-08-26 23:41:50 +00004516 return ExprError();
Douglas Gregor51e77d52009-12-10 17:56:55 +00004517
4518 CurInit.release();
4519 CurInit = S.Owned(InitList);
4520 break;
4521 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004522
4523 case SK_ConstructorInitialization: {
Douglas Gregorb33eed02010-04-16 22:09:46 +00004524 unsigned NumArgs = Args.size();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004525 CXXConstructorDecl *Constructor
John McCalla0296f72010-03-19 07:35:19 +00004526 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004528 // Build a call to the selected constructor.
John McCall37ad5512010-08-23 06:44:23 +00004529 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanianda2da9c2010-07-21 18:40:47 +00004530 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4531 ? Kind.getEqualLoc()
4532 : Kind.getLocation();
Chandler Carruthc9262402010-08-23 07:55:51 +00004533
4534 if (Kind.getKind() == InitializationKind::IK_Default) {
4535 // Force even a trivial, implicit default constructor to be
4536 // semantically checked. We do this explicitly because we don't build
4537 // the definition for completely trivial constructors.
4538 CXXRecordDecl *ClassDecl = Constructor->getParent();
4539 assert(ClassDecl && "No parent class for constructor.");
Alexis Huntf92197c2011-05-12 03:51:51 +00004540 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Huntf479f1b2011-05-09 18:22:59 +00004541 ClassDecl->hasTrivialDefaultConstructor() &&
4542 !Constructor->isUsed(false))
Chandler Carruthc9262402010-08-23 07:55:51 +00004543 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4544 }
4545
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004546 // Determine the arguments required to actually perform the constructor
4547 // call.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004548 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004549 Loc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00004550 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551
4552
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004553 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregorb33eed02010-04-16 22:09:46 +00004554 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004555 (Kind.getKind() == InitializationKind::IK_Direct ||
4556 Kind.getKind() == InitializationKind::IK_Value)) {
4557 // An explicitly-constructed temporary, e.g., X(1, 2).
4558 unsigned NumExprs = ConstructorArgs.size();
4559 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian3fd2a552010-07-21 18:31:47 +00004560 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00004561 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562
Douglas Gregor2b88c112010-09-08 00:15:04 +00004563 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4564 if (!TSInfo)
4565 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004567 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4568 Constructor,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004569 TSInfo,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570 Exprs,
Douglas Gregor9bc6b7f2010-03-02 17:18:33 +00004571 NumExprs,
Chandler Carruth01718152010-10-25 08:47:36 +00004572 Kind.getParenRange(),
Douglas Gregor199db362010-04-27 20:36:09 +00004573 ConstructorInitRequiresZeroInit));
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004574 } else {
4575 CXXConstructExpr::ConstructionKind ConstructKind =
4576 CXXConstructExpr::CK_Complete;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004578 if (Entity.getKind() == InitializedEntity::EK_Base) {
4579 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580 CXXConstructExpr::CK_VirtualBase :
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004581 CXXConstructExpr::CK_NonVirtualBase;
Alexis Hunt271c3682011-05-03 20:19:28 +00004582 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00004583 ConstructKind = CXXConstructExpr::CK_Delegating;
4584 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004585
Chandler Carruth01718152010-10-25 08:47:36 +00004586 // Only get the parenthesis range if it is a direct construction.
4587 SourceRange parenRange =
4588 Kind.getKind() == InitializationKind::IK_Direct ?
4589 Kind.getParenRange() : SourceRange();
4590
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004591 // If the entity allows NRVO, mark the construction as elidable
4592 // unconditionally.
4593 if (Entity.allowsNRVO())
4594 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4595 Constructor, /*Elidable=*/true,
4596 move_arg(ConstructorArgs),
4597 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004598 ConstructKind,
4599 parenRange);
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004600 else
4601 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004602 Constructor,
Douglas Gregor222cf0e2010-05-15 00:13:29 +00004603 move_arg(ConstructorArgs),
4604 ConstructorInitRequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00004605 ConstructKind,
4606 parenRange);
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004607 }
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004608 if (CurInit.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004609 return ExprError();
John McCall760af172010-02-01 03:16:54 +00004610
4611 // Only check access if all of that succeeded.
Anders Carlssona01874b2010-04-21 18:47:17 +00004612 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCalla0296f72010-03-19 07:35:19 +00004613 Step->Function.FoundDecl.getAccess());
John McCall4fa0d5f2010-05-06 18:15:07 +00004614 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004615
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004616 if (shouldBindAsTemporary(Entity))
Douglas Gregore1314a62009-12-18 05:02:21 +00004617 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004618
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004619 break;
4620 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004622 case SK_ZeroInitialization: {
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004623 step_iterator NextStep = Step;
4624 ++NextStep;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004625 if (NextStep != StepEnd &&
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004626 NextStep->Kind == SK_ConstructorInitialization) {
4627 // The need for zero-initialization is recorded directly into
4628 // the call to the object's constructor within the next step.
4629 ConstructorInitRequiresZeroInit = true;
4630 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4631 S.getLangOptions().CPlusPlus &&
4632 !Kind.isImplicitValueInit()) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00004633 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4634 if (!TSInfo)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregor2b88c112010-09-08 00:15:04 +00004636 Kind.getRange().getBegin());
4637
4638 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4639 TSInfo->getType().getNonLValueExprType(S.Context),
4640 TSInfo,
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004641 Kind.getRange().getEnd()));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004642 } else {
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004643 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004644 }
Douglas Gregor7dc42e52009-12-15 00:01:57 +00004645 break;
4646 }
Douglas Gregore1314a62009-12-18 05:02:21 +00004647
4648 case SK_CAssignment: {
John Wiegley01296292011-04-08 18:41:53 +00004649 QualType SourceType = CurInit.get()->getType();
4650 ExprResult Result = move(CurInit);
Douglas Gregore1314a62009-12-18 05:02:21 +00004651 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004652 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4653 if (Result.isInvalid())
4654 return ExprError();
4655 CurInit = move(Result);
Douglas Gregor96596c92009-12-22 07:24:36 +00004656
4657 // If this is a call, allow conversion to a transparent union.
John Wiegley01296292011-04-08 18:41:53 +00004658 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregor96596c92009-12-22 07:24:36 +00004659 if (ConvTy != Sema::Compatible &&
4660 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley01296292011-04-08 18:41:53 +00004661 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregor96596c92009-12-22 07:24:36 +00004662 == Sema::Compatible)
4663 ConvTy = Sema::Compatible;
John Wiegley01296292011-04-08 18:41:53 +00004664 if (CurInitExprRes.isInvalid())
4665 return ExprError();
4666 CurInit = move(CurInitExprRes);
Douglas Gregor96596c92009-12-22 07:24:36 +00004667
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004668 bool Complained;
Douglas Gregore1314a62009-12-18 05:02:21 +00004669 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4670 Step->Type, SourceType,
John Wiegley01296292011-04-08 18:41:53 +00004671 CurInit.get(),
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004672 getAssignmentAction(Entity),
4673 &Complained)) {
4674 PrintInitLocationNote(S, Entity);
John McCallfaf5fb42010-08-26 23:41:50 +00004675 return ExprError();
Douglas Gregor4f4946a2010-04-22 00:20:18 +00004676 } else if (Complained)
4677 PrintInitLocationNote(S, Entity);
Douglas Gregore1314a62009-12-18 05:02:21 +00004678 break;
4679 }
Eli Friedman78275202009-12-19 08:11:05 +00004680
4681 case SK_StringInit: {
4682 QualType Ty = Step->Type;
John Wiegley01296292011-04-08 18:41:53 +00004683 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCall5decec92011-02-21 07:57:55 +00004684 S.Context.getAsArrayType(Ty), S);
Eli Friedman78275202009-12-19 08:11:05 +00004685 break;
4686 }
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004687
4688 case SK_ObjCObjectConversion:
John Wiegley01296292011-04-08 18:41:53 +00004689 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCalle3027922010-08-25 11:45:40 +00004690 CK_ObjCObjectLValueCast,
John Wiegley01296292011-04-08 18:41:53 +00004691 S.CastCategory(CurInit.get()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004692 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004693
4694 case SK_ArrayInit:
4695 // Okay: we checked everything before creating this step. Note that
4696 // this is a GNU extension.
4697 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley01296292011-04-08 18:41:53 +00004698 << Step->Type << CurInit.get()->getType()
4699 << CurInit.get()->getSourceRange();
Douglas Gregore2f943b2011-02-22 18:29:51 +00004700
4701 // If the destination type is an incomplete array type, update the
4702 // type accordingly.
4703 if (ResultType) {
4704 if (const IncompleteArrayType *IncompleteDest
4705 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4706 if (const ConstantArrayType *ConstantSource
John Wiegley01296292011-04-08 18:41:53 +00004707 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregore2f943b2011-02-22 18:29:51 +00004708 *ResultType = S.Context.getConstantArrayType(
4709 IncompleteDest->getElementType(),
4710 ConstantSource->getSize(),
4711 ArrayType::Normal, 0);
4712 }
4713 }
4714 }
John McCall31168b02011-06-15 23:02:42 +00004715 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00004716
John McCall31168b02011-06-15 23:02:42 +00004717 case SK_PassByIndirectCopyRestore:
4718 case SK_PassByIndirectRestore:
4719 checkIndirectCopyRestoreSource(S, CurInit.get());
4720 CurInit = S.Owned(new (S.Context)
4721 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4722 Step->Kind == SK_PassByIndirectCopyRestore));
4723 break;
4724
4725 case SK_ProduceObjCObject:
4726 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall2d637d22011-09-10 06:18:15 +00004727 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00004728 CurInit.take(), 0, VK_RValue));
Douglas Gregore2f943b2011-02-22 18:29:51 +00004729 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004730 }
4731 }
John McCall1f425642010-11-11 03:21:53 +00004732
4733 // Diagnose non-fatal problems with the completed initialization.
4734 if (Entity.getKind() == InitializedEntity::EK_Member &&
4735 cast<FieldDecl>(Entity.getDecl())->isBitField())
4736 S.CheckBitFieldInitialization(Kind.getLocation(),
4737 cast<FieldDecl>(Entity.getDecl()),
4738 CurInit.get());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004740 return move(CurInit);
4741}
4742
4743//===----------------------------------------------------------------------===//
4744// Diagnose initialization failures
4745//===----------------------------------------------------------------------===//
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004746bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004747 const InitializedEntity &Entity,
4748 const InitializationKind &Kind,
4749 Expr **Args, unsigned NumArgs) {
Sebastian Redl724bfe12011-06-05 13:59:05 +00004750 if (!Failed())
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004751 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752
Douglas Gregor1b303932009-12-22 15:35:07 +00004753 QualType DestType = Entity.getType();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004754 switch (Failure) {
4755 case FK_TooManyInitsForReference:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004756 // FIXME: Customize for the initialized entity?
4757 if (NumArgs == 0)
4758 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4759 << DestType.getNonReferenceType();
4760 else // FIXME: diagnostic below could be better!
4761 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4762 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004763 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004765 case FK_ArrayNeedsInitList:
4766 case FK_ArrayNeedsInitListOrStringLiteral:
4767 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4768 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4769 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004770
Douglas Gregore2f943b2011-02-22 18:29:51 +00004771 case FK_ArrayTypeMismatch:
4772 case FK_NonConstantArrayInit:
4773 S.Diag(Kind.getLocation(),
4774 (Failure == FK_ArrayTypeMismatch
4775 ? diag::err_array_init_different_type
4776 : diag::err_array_init_non_constant_array))
4777 << DestType.getNonReferenceType()
4778 << Args[0]->getType()
4779 << Args[0]->getSourceRange();
4780 break;
4781
John McCall16df1e52010-03-30 21:47:33 +00004782 case FK_AddressOfOverloadFailed: {
4783 DeclAccessPair Found;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004785 DestType.getNonReferenceType(),
John McCall16df1e52010-03-30 21:47:33 +00004786 true,
4787 Found);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004788 break;
John McCall16df1e52010-03-30 21:47:33 +00004789 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004790
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004791 case FK_ReferenceInitOverloadFailed:
Douglas Gregor540c3b02009-12-14 17:27:33 +00004792 case FK_UserConversionOverloadFailed:
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004793 switch (FailedOverloadResult) {
4794 case OR_Ambiguous:
Douglas Gregore1314a62009-12-18 05:02:21 +00004795 if (Failure == FK_UserConversionOverloadFailed)
4796 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4797 << Args[0]->getType() << DestType
4798 << Args[0]->getSourceRange();
4799 else
4800 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4801 << DestType << Args[0]->getType()
4802 << Args[0]->getSourceRange();
4803
John McCall5c32be02010-08-24 20:38:10 +00004804 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004805 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004807 case OR_No_Viable_Function:
4808 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4809 << Args[0]->getType() << DestType.getNonReferenceType()
4810 << Args[0]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00004811 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004812 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004814 case OR_Deleted: {
4815 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4816 << Args[0]->getType() << DestType.getNonReferenceType()
4817 << Args[0]->getSourceRange();
4818 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004819 OverloadingResult Ovl
Douglas Gregord5b730c92010-09-12 08:07:23 +00004820 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4821 true);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004822 if (Ovl == OR_Deleted) {
4823 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004824 << 1 << Best->Function->isDeleted();
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004825 } else {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004826 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004827 }
4828 break;
4829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004831 case OR_Success:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00004832 llvm_unreachable("Conversion did not fail!");
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004833 break;
4834 }
4835 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004837 case FK_NonConstLValueReferenceBindingToTemporary:
4838 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839 S.Diag(Kind.getLocation(),
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004840 Failure == FK_NonConstLValueReferenceBindingToTemporary
4841 ? diag::err_lvalue_reference_bind_to_temporary
4842 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregord1e08642010-01-29 19:39:15 +00004843 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004844 << DestType.getNonReferenceType()
4845 << Args[0]->getType()
4846 << Args[0]->getSourceRange();
4847 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004848
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004849 case FK_RValueReferenceBindingToLValue:
4850 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorbed28f72011-01-21 01:04:33 +00004851 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004852 << Args[0]->getSourceRange();
4853 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004854
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004855 case FK_ReferenceInitDropsQualifiers:
4856 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4857 << DestType.getNonReferenceType()
4858 << Args[0]->getType()
4859 << Args[0]->getSourceRange();
4860 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004861
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004862 case FK_ReferenceInitFailed:
4863 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4864 << DestType.getNonReferenceType()
John McCall086a4642010-11-24 05:12:34 +00004865 << Args[0]->isLValue()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004866 << Args[0]->getType()
4867 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004868 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4869 Args[0]->getType()->isObjCObjectPointerType())
4870 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004871 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872
Douglas Gregorb491ed32011-02-19 21:32:49 +00004873 case FK_ConversionFailed: {
4874 QualType FromType = Args[0]->getType();
Douglas Gregore1314a62009-12-18 05:02:21 +00004875 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4876 << (int)Entity.getKind()
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004877 << DestType
John McCall086a4642010-11-24 05:12:34 +00004878 << Args[0]->isLValue()
Douglas Gregorb491ed32011-02-19 21:32:49 +00004879 << FromType
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004880 << Args[0]->getSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +00004881 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4882 Args[0]->getType()->isObjCObjectPointerType())
4883 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor51e77d52009-12-10 17:56:55 +00004884 break;
Douglas Gregorb491ed32011-02-19 21:32:49 +00004885 }
John Wiegley01296292011-04-08 18:41:53 +00004886
4887 case FK_ConversionFromPropertyFailed:
4888 // No-op. This error has already been reported.
4889 break;
4890
Douglas Gregor51e77d52009-12-10 17:56:55 +00004891 case FK_TooManyInitsForScalar: {
Douglas Gregor85dabae2009-12-16 01:38:02 +00004892 SourceRange R;
4893
4894 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor8ec51732010-09-08 21:40:08 +00004895 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor85dabae2009-12-16 01:38:02 +00004896 InitList->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004897 else
Douglas Gregor8ec51732010-09-08 21:40:08 +00004898 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor51e77d52009-12-10 17:56:55 +00004899
Douglas Gregor8ec51732010-09-08 21:40:08 +00004900 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4901 if (Kind.isCStyleOrFunctionalCast())
4902 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4903 << R;
4904 else
4905 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4906 << /*scalar=*/2 << R;
Douglas Gregor51e77d52009-12-10 17:56:55 +00004907 break;
4908 }
4909
4910 case FK_ReferenceBindingToInitList:
4911 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4912 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4913 break;
4914
4915 case FK_InitListBadDestinationType:
4916 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4917 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4918 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004919
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004920 case FK_ConstructorOverloadFailed: {
4921 SourceRange ArgsRange;
4922 if (NumArgs)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004923 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004924 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004926 // FIXME: Using "DestType" for the entity we're printing is probably
4927 // bad.
4928 switch (FailedOverloadResult) {
4929 case OR_Ambiguous:
4930 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4931 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004932 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4933 Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004934 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004936 case OR_No_Viable_Function:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004937 if (Kind.getKind() == InitializationKind::IK_Default &&
4938 (Entity.getKind() == InitializedEntity::EK_Base ||
4939 Entity.getKind() == InitializedEntity::EK_Member) &&
4940 isa<CXXConstructorDecl>(S.CurContext)) {
4941 // This is implicit default initialization of a member or
4942 // base within a constructor. If no viable function was
4943 // found, notify the user that she needs to explicitly
4944 // initialize this base/member.
4945 CXXConstructorDecl *Constructor
4946 = cast<CXXConstructorDecl>(S.CurContext);
4947 if (Entity.getKind() == InitializedEntity::EK_Base) {
4948 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4949 << Constructor->isImplicit()
4950 << S.Context.getTypeDeclType(Constructor->getParent())
4951 << /*base=*/0
4952 << Entity.getType();
4953
4954 RecordDecl *BaseDecl
4955 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4956 ->getDecl();
4957 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4958 << S.Context.getTagDeclType(BaseDecl);
4959 } else {
4960 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4961 << Constructor->isImplicit()
4962 << S.Context.getTypeDeclType(Constructor->getParent())
4963 << /*member=*/1
4964 << Entity.getName();
4965 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4966
4967 if (const RecordType *Record
4968 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004969 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004970 diag::note_previous_decl)
4971 << S.Context.getTagDeclType(Record->getDecl());
4972 }
4973 break;
4974 }
4975
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004976 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4977 << DestType << ArgsRange;
John McCall5c32be02010-08-24 20:38:10 +00004978 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004979 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004980
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004981 case OR_Deleted: {
4982 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4983 << true << DestType << ArgsRange;
4984 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00004985 OverloadingResult Ovl
4986 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004987 if (Ovl == OR_Deleted) {
4988 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCall31168b02011-06-15 23:02:42 +00004989 << 1 << Best->Function->isDeleted();
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004990 } else {
4991 llvm_unreachable("Inconsistent overload resolution?");
4992 }
4993 break;
4994 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004995
Douglas Gregor1e7ffa72009-12-14 20:49:26 +00004996 case OR_Success:
4997 llvm_unreachable("Conversion did not fail!");
4998 break;
4999 }
5000 break;
5001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005002
Douglas Gregor85dabae2009-12-16 01:38:02 +00005003 case FK_DefaultInitOfConst:
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005004 if (Entity.getKind() == InitializedEntity::EK_Member &&
5005 isa<CXXConstructorDecl>(S.CurContext)) {
5006 // This is implicit default-initialization of a const member in
5007 // a constructor. Complain that it needs to be explicitly
5008 // initialized.
5009 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5010 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5011 << Constructor->isImplicit()
5012 << S.Context.getTypeDeclType(Constructor->getParent())
5013 << /*const=*/1
5014 << Entity.getName();
5015 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5016 << Entity.getName();
5017 } else {
5018 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5019 << DestType << (bool)DestType->getAs<RecordType>();
5020 }
Douglas Gregor85dabae2009-12-16 01:38:02 +00005021 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005023 case FK_Incomplete:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005024 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005025 diag::err_init_incomplete_type);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005026 break;
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028
Douglas Gregor4f4946a2010-04-22 00:20:18 +00005029 PrintInitLocationNote(S, Entity);
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005030 return true;
5031}
Douglas Gregore1314a62009-12-18 05:02:21 +00005032
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005033void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005034 switch (SequenceKind) {
5035 case FailedSequence: {
5036 OS << "Failed sequence: ";
5037 switch (Failure) {
5038 case FK_TooManyInitsForReference:
5039 OS << "too many initializers for reference";
5040 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005042 case FK_ArrayNeedsInitList:
5043 OS << "array requires initializer list";
5044 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005046 case FK_ArrayNeedsInitListOrStringLiteral:
5047 OS << "array requires initializer list or string literal";
5048 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005049
Douglas Gregore2f943b2011-02-22 18:29:51 +00005050 case FK_ArrayTypeMismatch:
5051 OS << "array type mismatch";
5052 break;
5053
5054 case FK_NonConstantArrayInit:
5055 OS << "non-constant array initializer";
5056 break;
5057
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005058 case FK_AddressOfOverloadFailed:
5059 OS << "address of overloaded function failed";
5060 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005061
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005062 case FK_ReferenceInitOverloadFailed:
5063 OS << "overload resolution for reference initialization failed";
5064 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005066 case FK_NonConstLValueReferenceBindingToTemporary:
5067 OS << "non-const lvalue reference bound to temporary";
5068 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005070 case FK_NonConstLValueReferenceBindingToUnrelated:
5071 OS << "non-const lvalue reference bound to unrelated type";
5072 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005074 case FK_RValueReferenceBindingToLValue:
5075 OS << "rvalue reference bound to an lvalue";
5076 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005077
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005078 case FK_ReferenceInitDropsQualifiers:
5079 OS << "reference initialization drops qualifiers";
5080 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005081
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005082 case FK_ReferenceInitFailed:
5083 OS << "reference initialization failed";
5084 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005086 case FK_ConversionFailed:
5087 OS << "conversion failed";
5088 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005089
John Wiegley01296292011-04-08 18:41:53 +00005090 case FK_ConversionFromPropertyFailed:
5091 OS << "conversion from property failed";
5092 break;
5093
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005094 case FK_TooManyInitsForScalar:
5095 OS << "too many initializers for scalar";
5096 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005097
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005098 case FK_ReferenceBindingToInitList:
5099 OS << "referencing binding to initializer list";
5100 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005101
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005102 case FK_InitListBadDestinationType:
5103 OS << "initializer list for non-aggregate, non-scalar type";
5104 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005105
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005106 case FK_UserConversionOverloadFailed:
5107 OS << "overloading failed for user-defined conversion";
5108 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005110 case FK_ConstructorOverloadFailed:
5111 OS << "constructor overloading failed";
5112 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005114 case FK_DefaultInitOfConst:
5115 OS << "default initialization of a const variable";
5116 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00005118 case FK_Incomplete:
5119 OS << "initialization of incomplete type";
5120 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005121 }
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005122 OS << '\n';
5123 return;
5124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005126 case DependentSequence:
Sebastian Redld201edf2011-06-05 13:59:11 +00005127 OS << "Dependent sequence\n";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005128 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005129
Sebastian Redld201edf2011-06-05 13:59:11 +00005130 case NormalSequence:
5131 OS << "Normal sequence: ";
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005132 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005134
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005135 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5136 if (S != step_begin()) {
5137 OS << " -> ";
5138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005139
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005140 switch (S->Kind) {
5141 case SK_ResolveAddressOfOverloadedFunction:
5142 OS << "resolve address of overloaded function";
5143 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005144
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005145 case SK_CastDerivedToBaseRValue:
5146 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5147 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005148
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005149 case SK_CastDerivedToBaseXValue:
5150 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5151 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005152
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005153 case SK_CastDerivedToBaseLValue:
5154 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5155 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005157 case SK_BindReference:
5158 OS << "bind reference to lvalue";
5159 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005160
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005161 case SK_BindReferenceToTemporary:
5162 OS << "bind reference to a temporary";
5163 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005164
Douglas Gregorc9cd64e2010-04-18 07:40:54 +00005165 case SK_ExtraneousCopyToTemporary:
5166 OS << "extraneous C++03 copy to temporary";
5167 break;
5168
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005169 case SK_UserConversion:
Benjamin Kramerb11416d2010-04-17 09:33:03 +00005170 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005171 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005172
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005173 case SK_QualificationConversionRValue:
5174 OS << "qualification conversion (rvalue)";
5175
Sebastian Redlc57d34b2010-07-20 04:20:21 +00005176 case SK_QualificationConversionXValue:
5177 OS << "qualification conversion (xvalue)";
5178
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005179 case SK_QualificationConversionLValue:
5180 OS << "qualification conversion (lvalue)";
5181 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005182
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005183 case SK_ConversionSequence:
5184 OS << "implicit conversion sequence (";
5185 S->ICS->DebugPrint(); // FIXME: use OS
5186 OS << ")";
5187 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005188
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005189 case SK_ListInitialization:
5190 OS << "list initialization";
5191 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005192
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005193 case SK_ConstructorInitialization:
5194 OS << "constructor initialization";
5195 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005196
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005197 case SK_ZeroInitialization:
5198 OS << "zero initialization";
5199 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005200
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005201 case SK_CAssignment:
5202 OS << "C assignment";
5203 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005204
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005205 case SK_StringInit:
5206 OS << "string initialization";
5207 break;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00005208
5209 case SK_ObjCObjectConversion:
5210 OS << "Objective-C object conversion";
5211 break;
Douglas Gregore2f943b2011-02-22 18:29:51 +00005212
5213 case SK_ArrayInit:
5214 OS << "array initialization";
5215 break;
John McCall31168b02011-06-15 23:02:42 +00005216
5217 case SK_PassByIndirectCopyRestore:
5218 OS << "pass by indirect copy and restore";
5219 break;
5220
5221 case SK_PassByIndirectRestore:
5222 OS << "pass by indirect restore";
5223 break;
5224
5225 case SK_ProduceObjCObject:
5226 OS << "Objective-C object retension";
5227 break;
Douglas Gregor65eb86e2010-01-29 19:14:02 +00005228 }
5229 }
5230}
5231
5232void InitializationSequence::dump() const {
5233 dump(llvm::errs());
5234}
5235
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005236static void DiagnoseNarrowingInInitList(
5237 Sema& S, QualType EntityType, const Expr *InitE,
5238 bool Constant, const APValue &ConstantValue) {
5239 if (Constant) {
5240 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005241 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005242 ? diag::err_init_list_constant_narrowing
5243 : diag::warn_init_list_constant_narrowing)
5244 << InitE->getSourceRange()
5245 << ConstantValue
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005246 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005247 } else
5248 S.Diag(InitE->getLocStart(),
Francois Pichet0706d202011-09-17 17:15:52 +00005249 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005250 ? diag::err_init_list_variable_narrowing
5251 : diag::warn_init_list_variable_narrowing)
5252 << InitE->getSourceRange()
Jeffrey Yasskin74231382011-08-29 15:59:37 +00005253 << InitE->getType().getLocalUnqualifiedType()
5254 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005255
5256 llvm::SmallString<128> StaticCast;
5257 llvm::raw_svector_ostream OS(StaticCast);
5258 OS << "static_cast<";
5259 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5260 // It's important to use the typedef's name if there is one so that the
5261 // fixit doesn't break code using types like int64_t.
5262 //
5263 // FIXME: This will break if the typedef requires qualification. But
5264 // getQualifiedNameAsString() includes non-machine-parsable components.
5265 OS << TT->getDecl();
5266 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5267 OS << BT->getName(S.getLangOptions());
5268 else {
5269 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5270 // with a broken cast.
5271 return;
5272 }
5273 OS << ">(";
5274 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5275 << InitE->getSourceRange()
5276 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5277 << FixItHint::CreateInsertion(
5278 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5279}
5280
Douglas Gregore1314a62009-12-18 05:02:21 +00005281//===----------------------------------------------------------------------===//
5282// Initialization helper functions
5283//===----------------------------------------------------------------------===//
Alexis Hunt1f69a022011-05-12 22:46:29 +00005284bool
5285Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5286 ExprResult Init) {
5287 if (Init.isInvalid())
5288 return false;
5289
5290 Expr *InitE = Init.get();
5291 assert(InitE && "No initialization expression");
5292
5293 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5294 SourceLocation());
5295 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005296 return !Seq.Failed();
Alexis Hunt1f69a022011-05-12 22:46:29 +00005297}
5298
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299ExprResult
Douglas Gregore1314a62009-12-18 05:02:21 +00005300Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5301 SourceLocation EqualLoc,
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005302 ExprResult Init,
5303 bool TopLevelOfInitList) {
Douglas Gregore1314a62009-12-18 05:02:21 +00005304 if (Init.isInvalid())
5305 return ExprError();
5306
John McCall1f425642010-11-11 03:21:53 +00005307 Expr *InitE = Init.get();
Douglas Gregore1314a62009-12-18 05:02:21 +00005308 assert(InitE && "No initialization expression?");
5309
5310 if (EqualLoc.isInvalid())
5311 EqualLoc = InitE->getLocStart();
5312
5313 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5314 EqualLoc);
5315 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5316 Init.release();
Jeffrey Yasskina6667812011-07-26 23:20:30 +00005317
5318 bool Constant = false;
5319 APValue Result;
5320 if (TopLevelOfInitList &&
5321 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5322 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5323 Constant, Result);
5324 }
John McCallfaf5fb42010-08-26 23:41:50 +00005325 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregore1314a62009-12-18 05:02:21 +00005326}