blob: f5cfbcafb4a8dfacd68dc6b78b6c65a8e5b35479 [file] [log] [blame]
Steve Naroff0cca7492008-05-01 22:18:59 +00001//===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Sebastian Redl5d3d41d2011-09-24 17:47:39 +000010// This file implements semantic analysis for initializers.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000011//
Steve Naroff0cca7492008-05-01 22:18:59 +000012//===----------------------------------------------------------------------===//
13
John McCall19510852010-08-20 18:27:03 +000014#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000018#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000019#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000021#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000022#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000024#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000025#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000026#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000027using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000028
Chris Lattnerdd8e0062009-02-24 22:27:37 +000029//===----------------------------------------------------------------------===//
30// Sema Initialization Checking
31//===----------------------------------------------------------------------===//
32
John McCallce6c9b72011-02-21 07:22:22 +000033static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
34 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000035 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
36 return 0;
37
Chris Lattner8879e3b2009-02-26 23:26:43 +000038 // See if this is a string literal or @encode.
39 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000040
Chris Lattner8879e3b2009-02-26 23:26:43 +000041 // Handle @encode, which is a narrow string.
42 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
43 return Init;
44
45 // Otherwise we can only handle string literals.
46 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000047 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000048
49 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000050
51 switch (SL->getKind()) {
52 case StringLiteral::Ascii:
53 case StringLiteral::UTF8:
54 // char array can be initialized with a narrow string.
55 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000056 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000057 case StringLiteral::UTF16:
58 return ElemTy->isChar16Type() ? Init : 0;
59 case StringLiteral::UTF32:
60 return ElemTy->isChar32Type() ? Init : 0;
61 case StringLiteral::Wide:
62 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
63 // correction from DR343): "An array with element type compatible with a
64 // qualified or unqualified version of wchar_t may be initialized by a wide
65 // string literal, optionally enclosed in braces."
66 if (Context.typesAreCompatible(Context.getWCharType(),
67 ElemTy.getUnqualifiedType()))
68 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000069
Douglas Gregor5cee1192011-07-27 05:40:30 +000070 return 0;
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor5cee1192011-07-27 05:40:30 +000073 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000074}
75
John McCallce6c9b72011-02-21 07:22:22 +000076static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
77 const ArrayType *arrayType = Context.getAsArrayType(declType);
78 if (!arrayType) return 0;
79
80 return IsStringInit(init, arrayType, Context);
81}
82
John McCallfef8b342011-02-21 07:57:55 +000083static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
84 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000085 // Get the length of the string as parsed.
86 uint64_t StrLength =
87 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
88
Mike Stump1eb44332009-09-09 15:08:12 +000089
Chris Lattnerdd8e0062009-02-24 22:27:37 +000090 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000091 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 // being initialized to a string literal.
93 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000094 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000095 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000096 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
97 ConstVal,
98 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +000099 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000100 }
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Eli Friedman8718a6a2009-05-29 18:22:49 +0000102 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000104 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000105 // the size may be smaller or larger than the string we are initializing.
106 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000107 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000108 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
109 // For Pascal strings it's OK to strip off the terminating null character,
110 // so the example below is valid:
111 //
112 // unsigned char a[2] = "\pa";
113 if (SL->isPascal())
114 StrLength--;
115 }
116
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000117 // [dcl.init.string]p2
118 if (StrLength > CAT->getSize().getZExtValue())
119 S.Diag(Str->getSourceRange().getBegin(),
120 diag::err_initializer_string_for_char_array_too_long)
121 << Str->getSourceRange();
122 } else {
123 // C99 6.7.8p14.
124 if (StrLength-1 > CAT->getSize().getZExtValue())
125 S.Diag(Str->getSourceRange().getBegin(),
126 diag::warn_initializer_string_for_char_array_too_long)
127 << Str->getSourceRange();
128 }
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Eli Friedman8718a6a2009-05-29 18:22:49 +0000130 // Set the type to the actual size that we are initializing. If we have
131 // something like:
132 // char x[1] = "foo";
133 // then this will set the string literal's type to char[1].
134 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000135}
136
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137//===----------------------------------------------------------------------===//
138// Semantic checking for initializer lists.
139//===----------------------------------------------------------------------===//
140
Douglas Gregor9e80f722009-01-29 01:05:33 +0000141/// @brief Semantic checking for initializer lists.
142///
143/// The InitListChecker class contains a set of routines that each
144/// handle the initialization of a certain kind of entity, e.g.,
145/// arrays, vectors, struct/union types, scalars, etc. The
146/// InitListChecker itself performs a recursive walk of the subobject
147/// structure of the type to be initialized, while stepping through
148/// the initializer list one element at a time. The IList and Index
149/// parameters to each of the Check* routines contain the active
150/// (syntactic) initializer list and the index into that initializer
151/// list that represents the current initializer. Each routine is
152/// responsible for moving that Index forward as it consumes elements.
153///
154/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000155/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000156/// initializer list and the index into that initializer list where we
157/// are copying initializers as we map them over to the semantic
158/// list. Once we have completed our recursive walk of the subobject
159/// structure, we will have constructed a full semantic initializer
160/// list.
161///
162/// C99 designators cause changes in the initializer list traversal,
163/// because they make the initialization "jump" into a specific
164/// subobject and then continue the initialization from that
165/// point. CheckDesignatedInitializer() recursively steps into the
166/// designated subobject and manages backing out the recursion to
167/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000168namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000169class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000170 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000172 bool VerifyOnly; // no diagnostics, no structure building
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
174 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000175
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000176 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000177 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000178 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000179 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000180 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000181 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000182 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000183 unsigned &StructuredIndex,
184 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000185 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000186 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000187 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000188 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000189 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000190 unsigned &StructuredIndex,
191 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000192 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000193 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000194 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000195 InitListExpr *StructuredList,
196 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000197 void CheckComplexType(const InitializedEntity &Entity,
198 InitListExpr *IList, QualType DeclType,
199 unsigned &Index,
200 InitListExpr *StructuredList,
201 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000202 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000203 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000204 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000205 InitListExpr *StructuredList,
206 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000207 void CheckReferenceType(const InitializedEntity &Entity,
208 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000209 unsigned &Index,
210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000212 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000213 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000214 InitListExpr *StructuredList,
215 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000216 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000217 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000218 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000219 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000220 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000221 unsigned &StructuredIndex,
222 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000223 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000224 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000225 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000226 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000227 InitListExpr *StructuredList,
228 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000229 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000230 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000231 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000232 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000233 RecordDecl::field_iterator *NextField,
234 llvm::APSInt *NextElementIndex,
235 unsigned &Index,
236 InitListExpr *StructuredList,
237 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000238 bool FinishSubobjectInit,
239 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000240 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
241 QualType CurrentObjectType,
242 InitListExpr *StructuredList,
243 unsigned StructuredIndex,
244 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000245 void UpdateStructuredListElement(InitListExpr *StructuredList,
246 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000247 Expr *expr);
248 int numArrayElements(QualType DeclType);
249 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000250
Douglas Gregord6d37de2009-12-22 00:05:34 +0000251 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
252 const InitializedEntity &ParentEntity,
253 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000254 void FillInValueInitializations(const InitializedEntity &Entity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000256 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
257 Expr *InitExpr, FieldDecl *Field,
258 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000259public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000260 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000261 InitListExpr *IL, QualType &T, bool VerifyOnly);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000262 bool HadError() { return hadError; }
263
264 // @brief Retrieves the fully-structured initializer list used for
265 // semantic analysis and code generation.
266 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
267};
Chris Lattner8b419b92009-02-24 22:48:58 +0000268} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000269
Douglas Gregord6d37de2009-12-22 00:05:34 +0000270void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
271 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000273 bool &RequiresSecondPass) {
274 SourceLocation Loc = ILE->getSourceRange().getBegin();
275 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000276 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000277 = InitializedEntity::InitializeMember(Field, &ParentEntity);
278 if (Init >= NumInits || !ILE->getInit(Init)) {
279 // FIXME: We probably don't need to handle references
280 // specially here, since value-initialization of references is
281 // handled in InitializationSequence.
282 if (Field->getType()->isReferenceType()) {
283 // C++ [dcl.init.aggr]p9:
284 // If an incomplete or empty initializer-list leaves a
285 // member of reference type uninitialized, the program is
286 // ill-formed.
287 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
288 << Field->getType()
289 << ILE->getSyntacticForm()->getSourceRange();
290 SemaRef.Diag(Field->getLocation(),
291 diag::note_uninit_reference_member);
292 hadError = true;
293 return;
294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000295
Douglas Gregord6d37de2009-12-22 00:05:34 +0000296 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
297 true);
298 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
299 if (!InitSeq) {
300 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
301 hadError = true;
302 return;
303 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000304
John McCall60d7b3a2010-08-24 06:29:42 +0000305 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000306 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000307 if (MemberInit.isInvalid()) {
308 hadError = true;
309 return;
310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000311
Douglas Gregord6d37de2009-12-22 00:05:34 +0000312 if (hadError) {
313 // Do nothing
314 } else if (Init < NumInits) {
315 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000316 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000317 // Value-initialization requires a constructor call, so
318 // extend the initializer list to include the constructor
319 // call and make a note that we'll need to take another pass
320 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000321 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000322 RequiresSecondPass = true;
323 }
324 } else if (InitListExpr *InnerILE
325 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000326 FillInValueInitializations(MemberEntity, InnerILE,
327 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000328}
329
Douglas Gregor4c678342009-01-28 21:54:33 +0000330/// Recursively replaces NULL values within the given initializer list
331/// with expressions that perform value-initialization of the
332/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000333void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000334InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
335 InitListExpr *ILE,
336 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000337 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000338 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000339 SourceLocation Loc = ILE->getSourceRange().getBegin();
340 if (ILE->getSyntacticForm())
341 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Ted Kremenek6217b802009-07-29 21:53:49 +0000343 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000344 if (RType->getDecl()->isUnion() &&
345 ILE->getInitializedFieldInUnion())
346 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
347 Entity, ILE, RequiresSecondPass);
348 else {
349 unsigned Init = 0;
350 for (RecordDecl::field_iterator
351 Field = RType->getDecl()->field_begin(),
352 FieldEnd = RType->getDecl()->field_end();
353 Field != FieldEnd; ++Field) {
354 if (Field->isUnnamedBitfield())
355 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000356
Douglas Gregord6d37de2009-12-22 00:05:34 +0000357 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000359
360 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
361 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000362 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000363
Douglas Gregord6d37de2009-12-22 00:05:34 +0000364 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000365
Douglas Gregord6d37de2009-12-22 00:05:34 +0000366 // Only look at the first initialization of a union.
367 if (RType->getDecl()->isUnion())
368 break;
369 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000370 }
371
372 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000373 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000374
375 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000377 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 unsigned NumInits = ILE->getNumInits();
379 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000380 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000381 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000382 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
383 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000384 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000385 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000386 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000388 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000389 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000390 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000391 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000392 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000393
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000394
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000396 if (hadError)
397 return;
398
Anders Carlssond3d824d2010-01-23 04:34:47 +0000399 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
400 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000401 ElementEntity.setElementIndex(Init);
402
Douglas Gregor87fd7032009-02-02 17:43:21 +0000403 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000404 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
405 true);
406 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
407 if (!InitSeq) {
408 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000409 hadError = true;
410 return;
411 }
412
John McCall60d7b3a2010-08-24 06:29:42 +0000413 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000414 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000415 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000416 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000417 return;
418 }
419
420 if (hadError) {
421 // Do nothing
422 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000423 // For arrays, just set the expression used for value-initialization
424 // of the "holes" in the array.
425 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
426 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
427 else
428 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000429 } else {
430 // For arrays, just set the expression used for value-initialization
431 // of the rest of elements and exit.
432 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
433 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
434 return;
435 }
436
Sebastian Redl7491c492011-06-05 13:59:11 +0000437 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000438 // Value-initialization requires a constructor call, so
439 // extend the initializer list to include the constructor
440 // call and make a note that we'll need to take another pass
441 // through the initializer list.
442 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
443 RequiresSecondPass = true;
444 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000445 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000446 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000447 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
448 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000449 }
450}
451
Chris Lattner68355a52009-01-29 05:10:57 +0000452
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000453InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000454 InitListExpr *IL, QualType &T,
455 bool VerifyOnly)
456 : SemaRef(S), VerifyOnly(VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000457 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000458
Eli Friedmanb85f7072008-05-19 19:16:24 +0000459 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000460 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000461 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000462 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000463 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000464 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000465 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000466
Sebastian Redl14b0c192011-09-24 17:48:00 +0000467 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000468 bool RequiresSecondPass = false;
469 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000470 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000471 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000472 RequiresSecondPass);
473 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000474}
475
476int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000477 // FIXME: use a proper constant
478 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000479 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000480 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000481 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
482 }
483 return maxElements;
484}
485
486int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000487 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000488 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000489 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000490 Field = structDecl->field_begin(),
491 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000492 Field != FieldEnd; ++Field) {
493 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
494 ++InitializableMembers;
495 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000496 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000497 return std::min(InitializableMembers, 1);
498 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000499}
500
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000501void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000502 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000503 QualType T, unsigned &Index,
504 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000505 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000506 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Steve Naroff0cca7492008-05-01 22:18:59 +0000508 if (T->isArrayType())
509 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000510 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000511 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000512 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000513 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000514 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000515 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000516
Eli Friedman402256f2008-05-25 13:49:22 +0000517 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000518 if (!VerifyOnly)
519 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
520 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000522 hadError = true;
523 return;
524 }
525
Douglas Gregor4c678342009-01-28 21:54:33 +0000526 // Build a structured initializer list corresponding to this subobject.
527 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000528 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
529 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000530 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
531 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000532 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000533
Douglas Gregor4c678342009-01-28 21:54:33 +0000534 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000535 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000536 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000537 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000538 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000539 StructuredSubobjectInitIndex);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000540 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000541 if (!VerifyOnly) {
542 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000543
Sebastian Redl14b0c192011-09-24 17:48:00 +0000544 // Update the structured sub-object initializer so that it's ending
545 // range corresponds with the end of the last initializer it used.
546 if (EndIndex < ParentIList->getNumInits()) {
547 SourceLocation EndLoc
548 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
549 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000551
Sebastian Redl14b0c192011-09-24 17:48:00 +0000552 // Warn about missing braces.
553 if (T->isArrayType() || T->isRecordType()) {
554 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
555 diag::warn_missing_braces)
556 << StructuredSubobjectInitList->getSourceRange()
557 << FixItHint::CreateInsertion(
558 StructuredSubobjectInitList->getLocStart(), "{")
559 << FixItHint::CreateInsertion(
560 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000561 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000562 "}");
563 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000564 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000565}
566
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000567void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000568 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000569 unsigned &Index,
570 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000571 unsigned &StructuredIndex,
572 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000573 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000574 if (!VerifyOnly) {
575 SyntacticToSemantic[IList] = StructuredList;
576 StructuredList->setSyntacticForm(IList);
577 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000578 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000579 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000580 if (!VerifyOnly) {
581 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
582 IList->setType(ExprTy);
583 StructuredList->setType(ExprTy);
584 }
Eli Friedman638e1442008-05-25 13:22:35 +0000585 if (hadError)
586 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000587
Eli Friedman638e1442008-05-25 13:22:35 +0000588 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000589 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000590 if (VerifyOnly) {
591 if (SemaRef.getLangOptions().CPlusPlus ||
592 (SemaRef.getLangOptions().OpenCL &&
593 IList->getType()->isVectorType())) {
594 hadError = true;
595 }
596 return;
597 }
598
Eli Friedmane5408582009-05-29 20:20:05 +0000599 if (StructuredIndex == 1 &&
600 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000601 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000602 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000603 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000604 hadError = true;
605 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000606 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000607 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000608 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000609 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000610 // Don't complain for incomplete types, since we'll get an error
611 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000612 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000613 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000614 CurrentObjectType->isArrayType()? 0 :
615 CurrentObjectType->isVectorType()? 1 :
616 CurrentObjectType->isScalarType()? 2 :
617 CurrentObjectType->isUnionType()? 3 :
618 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000619
620 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000621 if (SemaRef.getLangOptions().CPlusPlus) {
622 DK = diag::err_excess_initializers;
623 hadError = true;
624 }
Nate Begeman08634522009-07-07 21:53:06 +0000625 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
626 DK = diag::err_excess_initializers;
627 hadError = true;
628 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000629
Chris Lattner08202542009-02-24 22:50:46 +0000630 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000631 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000632 }
633 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000634
Sebastian Redl14b0c192011-09-24 17:48:00 +0000635 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
636 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000637 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000638 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000639 << FixItHint::CreateRemoval(IList->getLocStart())
640 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000641}
642
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000643void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000644 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000645 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000646 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 unsigned &Index,
648 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000649 unsigned &StructuredIndex,
650 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000651 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
652 // Explicitly braced initializer for complex type can be real+imaginary
653 // parts.
654 CheckComplexType(Entity, IList, DeclType, Index,
655 StructuredList, StructuredIndex);
656 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000657 CheckScalarType(Entity, IList, DeclType, Index,
658 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000659 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000660 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000661 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000662 } else if (DeclType->isAggregateType()) {
663 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000664 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000665 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000666 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000667 StructuredList, StructuredIndex,
668 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000669 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000670 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000671 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000672 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000673 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000674 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000675 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000676 } else
David Blaikieb219cfc2011-09-23 05:06:16 +0000677 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000678 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
679 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000680 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000681 if (!VerifyOnly)
682 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
683 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000684 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000685 } else if (DeclType->isRecordType()) {
686 // C++ [dcl.init]p14:
687 // [...] If the class is an aggregate (8.5.1), and the initializer
688 // is a brace-enclosed list, see 8.5.1.
689 //
690 // Note: 8.5.1 is handled below; here, we diagnose the case where
691 // we have an initializer list and a destination type that is not
692 // an aggregate.
693 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000694 if (!VerifyOnly)
695 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
696 << DeclType << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000697 hadError = true;
698 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000699 CheckReferenceType(Entity, IList, DeclType, Index,
700 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000701 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000702 if (!VerifyOnly)
703 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
704 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000705 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000706 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000707 if (!VerifyOnly)
708 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
709 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000710 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000711 }
712}
713
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000714void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000715 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000716 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000717 unsigned &Index,
718 InitListExpr *StructuredList,
719 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000720 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000721 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
722 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000723 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000724 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000725 = getStructuredSubobjectInit(IList, Index, ElemType,
726 StructuredList, StructuredIndex,
727 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000728 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000729 newStructuredList, newStructuredIndex);
730 ++StructuredIndex;
731 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000732 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000733 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000734 return CheckScalarType(Entity, IList, ElemType, Index,
735 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000736 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000737 return CheckReferenceType(Entity, IList, ElemType, Index,
738 StructuredList, StructuredIndex);
739 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000740
John McCallfef8b342011-02-21 07:57:55 +0000741 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
742 // arrayType can be incomplete if we're initializing a flexible
743 // array member. There's nothing we can do with the completed
744 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000745
John McCallfef8b342011-02-21 07:57:55 +0000746 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000747 if (!VerifyOnly) {
748 CheckStringInit(Str, ElemType, arrayType, SemaRef);
749 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
750 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000751 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000752 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000753 }
John McCallfef8b342011-02-21 07:57:55 +0000754
755 // Fall through for subaggregate initialization.
756
757 } else if (SemaRef.getLangOptions().CPlusPlus) {
758 // C++ [dcl.init.aggr]p12:
759 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000760 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000761 // an initializer-list. If the initializer can initialize a
762 // member, the member is initialized. [...]
763
764 // FIXME: Better EqualLoc?
765 InitializationKind Kind =
766 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
767 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
768
769 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000770 if (!VerifyOnly) {
771 ExprResult Result =
772 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
773 if (Result.isInvalid())
774 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000775
Sebastian Redl14b0c192011-09-24 17:48:00 +0000776 UpdateStructuredListElement(StructuredList, StructuredIndex,
777 Result.takeAs<Expr>());
778 }
John McCallfef8b342011-02-21 07:57:55 +0000779 ++Index;
780 return;
781 }
782
783 // Fall through for subaggregate initialization
784 } else {
785 // C99 6.7.8p13:
786 //
787 // The initializer for a structure or union object that has
788 // automatic storage duration shall be either an initializer
789 // list as described below, or a single expression that has
790 // compatible structure or union type. In the latter case, the
791 // initial value of the object, including unnamed members, is
792 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000793 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000794 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000795 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
796 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000797 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000798 if (ExprRes.isInvalid())
799 hadError = true;
800 else {
801 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
802 if (ExprRes.isInvalid())
803 hadError = true;
804 }
805 UpdateStructuredListElement(StructuredList, StructuredIndex,
806 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000807 ++Index;
808 return;
809 }
John Wiegley429bb272011-04-08 18:41:53 +0000810 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000811 // Fall through for subaggregate initialization
812 }
813
814 // C++ [dcl.init.aggr]p12:
815 //
816 // [...] Otherwise, if the member is itself a non-empty
817 // subaggregate, brace elision is assumed and the initializer is
818 // considered for the initialization of the first member of
819 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000820 if (!SemaRef.getLangOptions().OpenCL &&
821 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000822 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
823 StructuredIndex);
824 ++StructuredIndex;
825 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000826 if (!VerifyOnly) {
827 // We cannot initialize this element, so let
828 // PerformCopyInitialization produce the appropriate diagnostic.
829 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
830 SemaRef.Owned(expr),
831 /*TopLevelOfInitList=*/true);
832 }
John McCallfef8b342011-02-21 07:57:55 +0000833 hadError = true;
834 ++Index;
835 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000836 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000837}
838
Eli Friedman0c706c22011-09-19 23:17:44 +0000839void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
840 InitListExpr *IList, QualType DeclType,
841 unsigned &Index,
842 InitListExpr *StructuredList,
843 unsigned &StructuredIndex) {
844 assert(Index == 0 && "Index in explicit init list must be zero");
845
846 // As an extension, clang supports complex initializers, which initialize
847 // a complex number component-wise. When an explicit initializer list for
848 // a complex number contains two two initializers, this extension kicks in:
849 // it exepcts the initializer list to contain two elements convertible to
850 // the element type of the complex type. The first element initializes
851 // the real part, and the second element intitializes the imaginary part.
852
853 if (IList->getNumInits() != 2)
854 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
855 StructuredIndex);
856
857 // This is an extension in C. (The builtin _Complex type does not exist
858 // in the C++ standard.)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000859 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000860 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
861 << IList->getSourceRange();
862
863 // Initialize the complex number.
864 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
865 InitializedEntity ElementEntity =
866 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
867
868 for (unsigned i = 0; i < 2; ++i) {
869 ElementEntity.setElementIndex(Index);
870 CheckSubElementType(ElementEntity, IList, elementType, Index,
871 StructuredList, StructuredIndex);
872 }
873}
874
875
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000876void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000877 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000878 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000879 InitListExpr *StructuredList,
880 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000881 if (Index >= IList->getNumInits()) {
Sebastian Redlcea8d962011-09-24 17:48:14 +0000882 if (!SemaRef.getLangOptions().CPlusPlus0x) {
883 if (!VerifyOnly)
884 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
885 << IList->getSourceRange();
886 hadError = true;
887 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000888 ++Index;
889 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000890 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000891 }
John McCallb934c2d2010-11-11 00:46:36 +0000892
893 Expr *expr = IList->getInit(Index);
894 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000895 if (!VerifyOnly)
896 SemaRef.Diag(SubIList->getLocStart(),
897 diag::warn_many_braces_around_scalar_init)
898 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000899
900 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
901 StructuredIndex);
902 return;
903 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000904 if (!VerifyOnly)
905 SemaRef.Diag(expr->getSourceRange().getBegin(),
906 diag::err_designator_for_scalar_init)
907 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000908 hadError = true;
909 ++Index;
910 ++StructuredIndex;
911 return;
912 }
913
Sebastian Redl14b0c192011-09-24 17:48:00 +0000914 if (VerifyOnly) {
915 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
916 hadError = true;
917 ++Index;
918 return;
919 }
920
John McCallb934c2d2010-11-11 00:46:36 +0000921 ExprResult Result =
922 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000923 SemaRef.Owned(expr),
924 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000925
926 Expr *ResultExpr = 0;
927
928 if (Result.isInvalid())
929 hadError = true; // types weren't compatible.
930 else {
931 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000932
John McCallb934c2d2010-11-11 00:46:36 +0000933 if (ResultExpr != expr) {
934 // The type was promoted, update initializer list.
935 IList->setInit(Index, ResultExpr);
936 }
937 }
938 if (hadError)
939 ++StructuredIndex;
940 else
941 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
942 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000943}
944
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000945void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
946 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000947 unsigned &Index,
948 InitListExpr *StructuredList,
949 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000950 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000951 // FIXME: It would be wonderful if we could point at the actual member. In
952 // general, it would be useful to pass location information down the stack,
953 // so that we know the location (or decl) of the "current object" being
954 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000955 if (!VerifyOnly)
956 SemaRef.Diag(IList->getLocStart(),
957 diag::err_init_reference_member_uninitialized)
958 << DeclType
959 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000960 hadError = true;
961 ++Index;
962 ++StructuredIndex;
963 return;
964 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000965
966 Expr *expr = IList->getInit(Index);
967 if (isa<InitListExpr>(expr)) {
968 // FIXME: Allowed in C++11.
969 if (!VerifyOnly)
970 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
971 << DeclType << IList->getSourceRange();
972 hadError = true;
973 ++Index;
974 ++StructuredIndex;
975 return;
976 }
977
978 if (VerifyOnly) {
979 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
980 hadError = true;
981 ++Index;
982 return;
983 }
984
985 ExprResult Result =
986 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
987 SemaRef.Owned(expr),
988 /*TopLevelOfInitList=*/true);
989
990 if (Result.isInvalid())
991 hadError = true;
992
993 expr = Result.takeAs<Expr>();
994 IList->setInit(Index, expr);
995
996 if (hadError)
997 ++StructuredIndex;
998 else
999 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1000 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001001}
1002
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001003void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001004 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001005 unsigned &Index,
1006 InitListExpr *StructuredList,
1007 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001008 if (Index >= IList->getNumInits())
1009 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001010
John McCall20e047a2010-10-30 00:11:39 +00001011 const VectorType *VT = DeclType->getAs<VectorType>();
1012 unsigned maxElements = VT->getNumElements();
1013 unsigned numEltsInit = 0;
1014 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001015
John McCall20e047a2010-10-30 00:11:39 +00001016 if (!SemaRef.getLangOptions().OpenCL) {
1017 // If the initializing element is a vector, try to copy-initialize
1018 // instead of breaking it apart (which is doomed to failure anyway).
1019 Expr *Init = IList->getInit(Index);
1020 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001021 if (VerifyOnly) {
1022 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1023 hadError = true;
1024 ++Index;
1025 return;
1026 }
1027
John McCall20e047a2010-10-30 00:11:39 +00001028 ExprResult Result =
1029 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001030 SemaRef.Owned(Init),
1031 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001032
1033 Expr *ResultExpr = 0;
1034 if (Result.isInvalid())
1035 hadError = true; // types weren't compatible.
1036 else {
1037 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001038
John McCall20e047a2010-10-30 00:11:39 +00001039 if (ResultExpr != Init) {
1040 // The type was promoted, update initializer list.
1041 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001042 }
1043 }
John McCall20e047a2010-10-30 00:11:39 +00001044 if (hadError)
1045 ++StructuredIndex;
1046 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001047 UpdateStructuredListElement(StructuredList, StructuredIndex,
1048 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001049 ++Index;
1050 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001051 }
Mike Stump1eb44332009-09-09 15:08:12 +00001052
John McCall20e047a2010-10-30 00:11:39 +00001053 InitializedEntity ElementEntity =
1054 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001055
John McCall20e047a2010-10-30 00:11:39 +00001056 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1057 // Don't attempt to go past the end of the init list
1058 if (Index >= IList->getNumInits())
1059 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001060
John McCall20e047a2010-10-30 00:11:39 +00001061 ElementEntity.setElementIndex(Index);
1062 CheckSubElementType(ElementEntity, IList, elementType, Index,
1063 StructuredList, StructuredIndex);
1064 }
1065 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001066 }
John McCall20e047a2010-10-30 00:11:39 +00001067
1068 InitializedEntity ElementEntity =
1069 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001070
John McCall20e047a2010-10-30 00:11:39 +00001071 // OpenCL initializers allows vectors to be constructed from vectors.
1072 for (unsigned i = 0; i < maxElements; ++i) {
1073 // Don't attempt to go past the end of the init list
1074 if (Index >= IList->getNumInits())
1075 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001076
John McCall20e047a2010-10-30 00:11:39 +00001077 ElementEntity.setElementIndex(Index);
1078
1079 QualType IType = IList->getInit(Index)->getType();
1080 if (!IType->isVectorType()) {
1081 CheckSubElementType(ElementEntity, IList, elementType, Index,
1082 StructuredList, StructuredIndex);
1083 ++numEltsInit;
1084 } else {
1085 QualType VecType;
1086 const VectorType *IVT = IType->getAs<VectorType>();
1087 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001088
John McCall20e047a2010-10-30 00:11:39 +00001089 if (IType->isExtVectorType())
1090 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1091 else
1092 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001093 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001094 CheckSubElementType(ElementEntity, IList, VecType, Index,
1095 StructuredList, StructuredIndex);
1096 numEltsInit += numIElts;
1097 }
1098 }
1099
1100 // OpenCL requires all elements to be initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001101 // FIXME: Shouldn't this set hadError to true then?
1102 if (numEltsInit != maxElements && !VerifyOnly)
1103 SemaRef.Diag(IList->getSourceRange().getBegin(),
1104 diag::err_vector_incorrect_num_initializers)
1105 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001106}
1107
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001108void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001109 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001110 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001111 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001112 unsigned &Index,
1113 InitListExpr *StructuredList,
1114 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001115 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1116
Steve Naroff0cca7492008-05-01 22:18:59 +00001117 // Check for the special-case of initializing an array with a string.
1118 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001119 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001120 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001121 // We place the string literal directly into the resulting
1122 // initializer list. This is the only place where the structure
1123 // of the structured initializer list doesn't match exactly,
1124 // because doing so would involve allocating one character
1125 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001126 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001127 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001128 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1129 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1130 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001131 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001132 return;
1133 }
1134 }
John McCallce6c9b72011-02-21 07:22:22 +00001135 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001136 // Check for VLAs; in standard C it would be possible to check this
1137 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1138 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001139 if (!VerifyOnly)
1140 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1141 diag::err_variable_object_no_init)
1142 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001143 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001144 ++Index;
1145 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001146 return;
1147 }
1148
Douglas Gregor05c13a32009-01-22 00:58:24 +00001149 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001150 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1151 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001152 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001153 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001154 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001155 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001156 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001157 maxElementsKnown = true;
1158 }
1159
John McCallce6c9b72011-02-21 07:22:22 +00001160 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001161 while (Index < IList->getNumInits()) {
1162 Expr *Init = IList->getInit(Index);
1163 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001164 // If we're not the subobject that matches up with the '{' for
1165 // the designator, we shouldn't be handling the
1166 // designator. Return immediately.
1167 if (!SubobjectIsDesignatorContext)
1168 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001169
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001170 // Handle this designated initializer. elementIndex will be
1171 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001172 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001173 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001174 StructuredList, StructuredIndex, true,
1175 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001176 hadError = true;
1177 continue;
1178 }
1179
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001180 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001181 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001182 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001183 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001184 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001185
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001186 // If the array is of incomplete type, keep track of the number of
1187 // elements in the initializer.
1188 if (!maxElementsKnown && elementIndex > maxElements)
1189 maxElements = elementIndex;
1190
Douglas Gregor05c13a32009-01-22 00:58:24 +00001191 continue;
1192 }
1193
1194 // If we know the maximum number of elements, and we've already
1195 // hit it, stop consuming elements in the initializer list.
1196 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001197 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001198
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001199 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001200 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001201 Entity);
1202 // Check this element.
1203 CheckSubElementType(ElementEntity, IList, elementType, Index,
1204 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001205 ++elementIndex;
1206
1207 // If the array is of incomplete type, keep track of the number of
1208 // elements in the initializer.
1209 if (!maxElementsKnown && elementIndex > maxElements)
1210 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001211 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001212 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001213 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001214 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001215 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001216 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001217 // Sizing an array implicitly to zero is not allowed by ISO C,
1218 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001219 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001220 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001221 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001222
Mike Stump1eb44332009-09-09 15:08:12 +00001223 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001224 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001225 }
1226}
1227
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001228bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1229 Expr *InitExpr,
1230 FieldDecl *Field,
1231 bool TopLevelObject) {
1232 // Handle GNU flexible array initializers.
1233 unsigned FlexArrayDiag;
1234 if (isa<InitListExpr>(InitExpr) &&
1235 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1236 // Empty flexible array init always allowed as an extension
1237 FlexArrayDiag = diag::ext_flexible_array_init;
1238 } else if (SemaRef.getLangOptions().CPlusPlus) {
1239 // Disallow flexible array init in C++; it is not required for gcc
1240 // compatibility, and it needs work to IRGen correctly in general.
1241 FlexArrayDiag = diag::err_flexible_array_init;
1242 } else if (!TopLevelObject) {
1243 // Disallow flexible array init on non-top-level object
1244 FlexArrayDiag = diag::err_flexible_array_init;
1245 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1246 // Disallow flexible array init on anything which is not a variable.
1247 FlexArrayDiag = diag::err_flexible_array_init;
1248 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1249 // Disallow flexible array init on local variables.
1250 FlexArrayDiag = diag::err_flexible_array_init;
1251 } else {
1252 // Allow other cases.
1253 FlexArrayDiag = diag::ext_flexible_array_init;
1254 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001255
1256 if (!VerifyOnly) {
1257 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1258 FlexArrayDiag)
1259 << InitExpr->getSourceRange().getBegin();
1260 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1261 << Field;
1262 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001263
1264 return FlexArrayDiag != diag::ext_flexible_array_init;
1265}
1266
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001267void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001268 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001269 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001270 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001271 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001272 unsigned &Index,
1273 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001274 unsigned &StructuredIndex,
1275 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001276 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Eli Friedmanb85f7072008-05-19 19:16:24 +00001278 // If the record is invalid, some of it's members are invalid. To avoid
1279 // confusion, we forgo checking the intializer for the entire record.
1280 if (structDecl->isInvalidDecl()) {
1281 hadError = true;
1282 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001283 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001284
1285 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001286 if (!VerifyOnly) {
1287 // Value-initialize the first named member of the union.
1288 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1289 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1290 Field != FieldEnd; ++Field) {
1291 if (Field->getDeclName()) {
1292 StructuredList->setInitializedFieldInUnion(*Field);
1293 break;
1294 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001295 }
1296 }
1297 return;
1298 }
1299
Douglas Gregor05c13a32009-01-22 00:58:24 +00001300 // If structDecl is a forward declaration, this loop won't do
1301 // anything except look at designated initializers; That's okay,
1302 // because an error should get printed out elsewhere. It might be
1303 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001304 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001305 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001306 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001307 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001308 while (Index < IList->getNumInits()) {
1309 Expr *Init = IList->getInit(Index);
1310
1311 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001312 // If we're not the subobject that matches up with the '{' for
1313 // the designator, we shouldn't be handling the
1314 // designator. Return immediately.
1315 if (!SubobjectIsDesignatorContext)
1316 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001317
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001318 // Handle this designated initializer. Field will be updated to
1319 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001320 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001321 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001322 StructuredList, StructuredIndex,
1323 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001324 hadError = true;
1325
Douglas Gregordfb5e592009-02-12 19:00:39 +00001326 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001327
1328 // Disable check for missing fields when designators are used.
1329 // This matches gcc behaviour.
1330 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001331 continue;
1332 }
1333
1334 if (Field == FieldEnd) {
1335 // We've run out of fields. We're done.
1336 break;
1337 }
1338
Douglas Gregordfb5e592009-02-12 19:00:39 +00001339 // We've already initialized a member of a union. We're done.
1340 if (InitializedSomething && DeclType->isUnionType())
1341 break;
1342
Douglas Gregor44b43212008-12-11 16:49:14 +00001343 // If we've hit the flexible array member at the end, we're done.
1344 if (Field->getType()->isIncompleteArrayType())
1345 break;
1346
Douglas Gregor0bb76892009-01-29 16:53:55 +00001347 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001348 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001349 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001350 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001351 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001352
Douglas Gregor54001c12011-06-29 21:51:31 +00001353 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001354 bool InvalidUse;
1355 if (VerifyOnly)
1356 InvalidUse = !SemaRef.CanUseDecl(*Field);
1357 else
1358 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1359 IList->getInit(Index)->getLocStart());
1360 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001361 ++Index;
1362 ++Field;
1363 hadError = true;
1364 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001365 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001366
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001367 InitializedEntity MemberEntity =
1368 InitializedEntity::InitializeMember(*Field, &Entity);
1369 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1370 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001371 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001372
Sebastian Redl14b0c192011-09-24 17:48:00 +00001373 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001374 // Initialize the first field within the union.
1375 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001376 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001377
1378 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001379 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001380
John McCall80639de2010-03-11 19:32:38 +00001381 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001382 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1383 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1384 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001385 // It is possible we have one or more unnamed bitfields remaining.
1386 // Find first (if any) named field and emit warning.
1387 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1388 it != end; ++it) {
1389 if (!it->isUnnamedBitfield()) {
1390 SemaRef.Diag(IList->getSourceRange().getEnd(),
1391 diag::warn_missing_field_initializers) << it->getName();
1392 break;
1393 }
1394 }
1395 }
1396
Mike Stump1eb44332009-09-09 15:08:12 +00001397 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001398 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001399 return;
1400
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001401 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1402 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001403 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001404 ++Index;
1405 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001406 }
1407
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001408 InitializedEntity MemberEntity =
1409 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001410
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001411 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001412 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001413 StructuredList, StructuredIndex);
1414 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001415 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001416 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001417}
Steve Naroff0cca7492008-05-01 22:18:59 +00001418
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001419/// \brief Expand a field designator that refers to a member of an
1420/// anonymous struct or union into a series of field designators that
1421/// refers to the field within the appropriate subobject.
1422///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001423static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001424 DesignatedInitExpr *DIE,
1425 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001426 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001427 typedef DesignatedInitExpr::Designator Designator;
1428
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001429 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001430 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001431 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1432 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1433 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001434 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001435 DIE->getDesignator(DesigIdx)->getDotLoc(),
1436 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1437 else
1438 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1439 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001440 assert(isa<FieldDecl>(*PI));
1441 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001442 }
1443
1444 // Expand the current designator into the set of replacement
1445 // designators, so we have a full subobject path down to where the
1446 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001447 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001448 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001449}
Mike Stump1eb44332009-09-09 15:08:12 +00001450
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001451/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001452/// corresponds to FieldName.
1453static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1454 IdentifierInfo *FieldName) {
1455 assert(AnonField->isAnonymousStructOrUnion());
1456 Decl *NextDecl = AnonField->getNextDeclInContext();
1457 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1458 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1459 return IF;
1460 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001461 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001462 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001463}
1464
Sebastian Redl14b0c192011-09-24 17:48:00 +00001465static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1466 DesignatedInitExpr *DIE) {
1467 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1468 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1469 for (unsigned I = 0; I < NumIndexExprs; ++I)
1470 IndexExprs[I] = DIE->getSubExpr(I + 1);
1471 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1472 DIE->size(), IndexExprs.data(),
1473 NumIndexExprs, DIE->getEqualOrColonLoc(),
1474 DIE->usesGNUSyntax(), DIE->getInit());
1475}
1476
Douglas Gregor05c13a32009-01-22 00:58:24 +00001477/// @brief Check the well-formedness of a C99 designated initializer.
1478///
1479/// Determines whether the designated initializer @p DIE, which
1480/// resides at the given @p Index within the initializer list @p
1481/// IList, is well-formed for a current object of type @p DeclType
1482/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001483/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001484/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001485///
1486/// @param IList The initializer list in which this designated
1487/// initializer occurs.
1488///
Douglas Gregor71199712009-04-15 04:56:10 +00001489/// @param DIE The designated initializer expression.
1490///
1491/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001492///
1493/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1494/// into which the designation in @p DIE should refer.
1495///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001496/// @param NextField If non-NULL and the first designator in @p DIE is
1497/// a field, this will be set to the field declaration corresponding
1498/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001499///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001500/// @param NextElementIndex If non-NULL and the first designator in @p
1501/// DIE is an array designator or GNU array-range designator, this
1502/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001503///
1504/// @param Index Index into @p IList where the designated initializer
1505/// @p DIE occurs.
1506///
Douglas Gregor4c678342009-01-28 21:54:33 +00001507/// @param StructuredList The initializer list expression that
1508/// describes all of the subobject initializers in the order they'll
1509/// actually be initialized.
1510///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001511/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001512bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001513InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001514 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001515 DesignatedInitExpr *DIE,
1516 unsigned DesigIdx,
1517 QualType &CurrentObjectType,
1518 RecordDecl::field_iterator *NextField,
1519 llvm::APSInt *NextElementIndex,
1520 unsigned &Index,
1521 InitListExpr *StructuredList,
1522 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001523 bool FinishSubobjectInit,
1524 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001525 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001526 // Check the actual initialization for the designated object type.
1527 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001528
1529 // Temporarily remove the designator expression from the
1530 // initializer list that the child calls see, so that we don't try
1531 // to re-process the designator.
1532 unsigned OldIndex = Index;
1533 IList->setInit(OldIndex, DIE->getInit());
1534
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001535 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001536 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001537
1538 // Restore the designated initializer expression in the syntactic
1539 // form of the initializer list.
1540 if (IList->getInit(OldIndex) != DIE->getInit())
1541 DIE->setInit(IList->getInit(OldIndex));
1542 IList->setInit(OldIndex, DIE);
1543
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001544 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001545 }
1546
Douglas Gregor71199712009-04-15 04:56:10 +00001547 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001548 bool IsFirstDesignator = (DesigIdx == 0);
1549 if (!VerifyOnly) {
1550 assert((IsFirstDesignator || StructuredList) &&
1551 "Need a non-designated initializer list to start from");
1552
1553 // Determine the structural initializer list that corresponds to the
1554 // current subobject.
1555 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1556 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1557 StructuredList, StructuredIndex,
1558 SourceRange(D->getStartLocation(),
1559 DIE->getSourceRange().getEnd()));
1560 assert(StructuredList && "Expected a structured initializer list");
1561 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001562
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001563 if (D->isFieldDesignator()) {
1564 // C99 6.7.8p7:
1565 //
1566 // If a designator has the form
1567 //
1568 // . identifier
1569 //
1570 // then the current object (defined below) shall have
1571 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001572 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001573 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001574 if (!RT) {
1575 SourceLocation Loc = D->getDotLoc();
1576 if (Loc.isInvalid())
1577 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001578 if (!VerifyOnly)
1579 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1580 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001581 ++Index;
1582 return true;
1583 }
1584
Douglas Gregor4c678342009-01-28 21:54:33 +00001585 // Note: we perform a linear search of the fields here, despite
1586 // the fact that we have a faster lookup method, because we always
1587 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001588 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001589 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001590 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001591 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001592 Field = RT->getDecl()->field_begin(),
1593 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001594 for (; Field != FieldEnd; ++Field) {
1595 if (Field->isUnnamedBitfield())
1596 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001597
Francois Picheta0e27f02010-12-22 03:46:10 +00001598 // If we find a field representing an anonymous field, look in the
1599 // IndirectFieldDecl that follow for the designated initializer.
1600 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1601 if (IndirectFieldDecl *IF =
1602 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001603 // In verify mode, don't modify the original.
1604 if (VerifyOnly)
1605 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001606 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1607 D = DIE->getDesignator(DesigIdx);
1608 break;
1609 }
1610 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001611 if (KnownField && KnownField == *Field)
1612 break;
1613 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001614 break;
1615
1616 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001617 }
1618
Douglas Gregor4c678342009-01-28 21:54:33 +00001619 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001620 if (VerifyOnly) {
1621 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001622 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001623 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001624
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001625 // There was no normal field in the struct with the designated
1626 // name. Perform another lookup for this name, which may find
1627 // something that we can't designate (e.g., a member function),
1628 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001629 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001630 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001631 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001632 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001633 // Name lookup didn't find anything. Determine whether this
1634 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001635 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001636 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001637 TypoCorrection Corrected = SemaRef.CorrectTypo(
1638 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1639 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1640 RT->getDecl(), false, Sema::CTC_NoKeywords);
1641 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001642 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001643 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001644 std::string CorrectedStr(
1645 Corrected.getAsString(SemaRef.getLangOptions()));
1646 std::string CorrectedQuotedStr(
1647 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001648 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001649 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001650 << FieldName << CurrentObjectType << CorrectedQuotedStr
1651 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001652 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001653 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001654 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001655 } else {
1656 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1657 << FieldName << CurrentObjectType;
1658 ++Index;
1659 return true;
1660 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001662
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001663 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001664 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001665 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001666 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001667 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001668 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001669 ++Index;
1670 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001671 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001672
Francois Picheta0e27f02010-12-22 03:46:10 +00001673 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001674 // The replacement field comes from typo correction; find it
1675 // in the list of fields.
1676 FieldIndex = 0;
1677 Field = RT->getDecl()->field_begin();
1678 for (; Field != FieldEnd; ++Field) {
1679 if (Field->isUnnamedBitfield())
1680 continue;
1681
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001682 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001683 Field->getIdentifier() == ReplacementField->getIdentifier())
1684 break;
1685
1686 ++FieldIndex;
1687 }
1688 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001689 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001690
1691 // All of the fields of a union are located at the same place in
1692 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001693 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001694 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001695 if (!VerifyOnly)
1696 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001697 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001698
Douglas Gregor54001c12011-06-29 21:51:31 +00001699 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001700 bool InvalidUse;
1701 if (VerifyOnly)
1702 InvalidUse = !SemaRef.CanUseDecl(*Field);
1703 else
1704 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1705 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001706 ++Index;
1707 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001708 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001709
Sebastian Redl14b0c192011-09-24 17:48:00 +00001710 if (!VerifyOnly) {
1711 // Update the designator with the field declaration.
1712 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Sebastian Redl14b0c192011-09-24 17:48:00 +00001714 // Make sure that our non-designated initializer list has space
1715 // for a subobject corresponding to this field.
1716 if (FieldIndex >= StructuredList->getNumInits())
1717 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1718 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001719
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001720 // This designator names a flexible array member.
1721 if (Field->getType()->isIncompleteArrayType()) {
1722 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001723 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001724 // We can't designate an object within the flexible array
1725 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001726 if (!VerifyOnly) {
1727 DesignatedInitExpr::Designator *NextD
1728 = DIE->getDesignator(DesigIdx + 1);
1729 SemaRef.Diag(NextD->getStartLocation(),
1730 diag::err_designator_into_flexible_array_member)
1731 << SourceRange(NextD->getStartLocation(),
1732 DIE->getSourceRange().getEnd());
1733 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1734 << *Field;
1735 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001736 Invalid = true;
1737 }
1738
Chris Lattner9046c222010-10-10 17:49:49 +00001739 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1740 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001741 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001742 if (!VerifyOnly) {
1743 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1744 diag::err_flexible_array_init_needs_braces)
1745 << DIE->getInit()->getSourceRange();
1746 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1747 << *Field;
1748 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001749 Invalid = true;
1750 }
1751
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001752 // Check GNU flexible array initializer.
1753 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1754 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001755 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001756
1757 if (Invalid) {
1758 ++Index;
1759 return true;
1760 }
1761
1762 // Initialize the array.
1763 bool prevHadError = hadError;
1764 unsigned newStructuredIndex = FieldIndex;
1765 unsigned OldIndex = Index;
1766 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001767
1768 InitializedEntity MemberEntity =
1769 InitializedEntity::InitializeMember(*Field, &Entity);
1770 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001771 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001772
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001773 IList->setInit(OldIndex, DIE);
1774 if (hadError && !prevHadError) {
1775 ++Field;
1776 ++FieldIndex;
1777 if (NextField)
1778 *NextField = Field;
1779 StructuredIndex = FieldIndex;
1780 return true;
1781 }
1782 } else {
1783 // Recurse to check later designated subobjects.
1784 QualType FieldType = (*Field)->getType();
1785 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001786
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001787 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001788 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001789 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1790 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001791 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001792 true, false))
1793 return true;
1794 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001795
1796 // Find the position of the next field to be initialized in this
1797 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001798 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001799 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001800
1801 // If this the first designator, our caller will continue checking
1802 // the rest of this struct/class/union subobject.
1803 if (IsFirstDesignator) {
1804 if (NextField)
1805 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001806 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001807 return false;
1808 }
1809
Douglas Gregor34e79462009-01-28 23:36:17 +00001810 if (!FinishSubobjectInit)
1811 return false;
1812
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001813 // We've already initialized something in the union; we're done.
1814 if (RT->getDecl()->isUnion())
1815 return hadError;
1816
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001817 // Check the remaining fields within this class/struct/union subobject.
1818 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001819
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001820 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001821 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001822 return hadError && !prevHadError;
1823 }
1824
1825 // C99 6.7.8p6:
1826 //
1827 // If a designator has the form
1828 //
1829 // [ constant-expression ]
1830 //
1831 // then the current object (defined below) shall have array
1832 // type and the expression shall be an integer constant
1833 // expression. If the array is of unknown size, any
1834 // nonnegative value is valid.
1835 //
1836 // Additionally, cope with the GNU extension that permits
1837 // designators of the form
1838 //
1839 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001840 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001841 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001842 if (!VerifyOnly)
1843 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1844 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001845 ++Index;
1846 return true;
1847 }
1848
1849 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001850 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1851 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001852 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001853 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001854 DesignatedEndIndex = DesignatedStartIndex;
1855 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001856 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001857
Mike Stump1eb44332009-09-09 15:08:12 +00001858 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001859 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001860 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001861 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001862 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001863
Chris Lattnere0fd8322011-02-19 22:28:58 +00001864 // Codegen can't handle evaluating array range designators that have side
1865 // effects, because we replicate the AST value for each initialized element.
1866 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1867 // elements with something that has a side effect, so codegen can emit an
1868 // "error unsupported" error instead of miscompiling the app.
1869 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001870 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001871 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001872 }
1873
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001874 if (isa<ConstantArrayType>(AT)) {
1875 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001876 DesignatedStartIndex
1877 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001878 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001879 DesignatedEndIndex
1880 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001881 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1882 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001883 if (!VerifyOnly)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001884 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1885 diag::err_array_designator_too_large)
1886 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1887 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001888 ++Index;
1889 return true;
1890 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001891 } else {
1892 // Make sure the bit-widths and signedness match.
1893 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001894 DesignatedEndIndex
1895 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001896 else if (DesignatedStartIndex.getBitWidth() <
1897 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001898 DesignatedStartIndex
1899 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001900 DesignatedStartIndex.setIsUnsigned(true);
1901 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001902 }
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Douglas Gregor4c678342009-01-28 21:54:33 +00001904 // Make sure that our non-designated initializer list has space
1905 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001906 if (!VerifyOnly &&
1907 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001908 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001909 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001910
Douglas Gregor34e79462009-01-28 23:36:17 +00001911 // Repeatedly perform subobject initializations in the range
1912 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001913
Douglas Gregor34e79462009-01-28 23:36:17 +00001914 // Move to the next designator
1915 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1916 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001917
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001918 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001919 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001920
Douglas Gregor34e79462009-01-28 23:36:17 +00001921 while (DesignatedStartIndex <= DesignatedEndIndex) {
1922 // Recurse to check later designated subobjects.
1923 QualType ElementType = AT->getElementType();
1924 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001925
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001926 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001927 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1928 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001929 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001930 (DesignatedStartIndex == DesignatedEndIndex),
1931 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001932 return true;
1933
1934 // Move to the next index in the array that we'll be initializing.
1935 ++DesignatedStartIndex;
1936 ElementIndex = DesignatedStartIndex.getZExtValue();
1937 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001938
1939 // If this the first designator, our caller will continue checking
1940 // the rest of this array subobject.
1941 if (IsFirstDesignator) {
1942 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001943 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001944 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001945 return false;
1946 }
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Douglas Gregor34e79462009-01-28 23:36:17 +00001948 if (!FinishSubobjectInit)
1949 return false;
1950
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001951 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001952 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001953 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001954 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001955 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001956 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001957}
1958
Douglas Gregor4c678342009-01-28 21:54:33 +00001959// Get the structured initializer list for a subobject of type
1960// @p CurrentObjectType.
1961InitListExpr *
1962InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1963 QualType CurrentObjectType,
1964 InitListExpr *StructuredList,
1965 unsigned StructuredIndex,
1966 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001967 if (VerifyOnly)
1968 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00001969 Expr *ExistingInit = 0;
1970 if (!StructuredList)
1971 ExistingInit = SyntacticToSemantic[IList];
1972 else if (StructuredIndex < StructuredList->getNumInits())
1973 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Douglas Gregor4c678342009-01-28 21:54:33 +00001975 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1976 return Result;
1977
1978 if (ExistingInit) {
1979 // We are creating an initializer list that initializes the
1980 // subobjects of the current object, but there was already an
1981 // initialization that completely initialized the current
1982 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001983 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001984 // struct X { int a, b; };
1985 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001986 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001987 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1988 // designated initializer re-initializes the whole
1989 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001990 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001991 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001992 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001993 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001994 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001995 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001996 << ExistingInit->getSourceRange();
1997 }
1998
Mike Stump1eb44332009-09-09 15:08:12 +00001999 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002000 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2001 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002002 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002003
Douglas Gregor63982352010-07-13 18:40:04 +00002004 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00002005
Douglas Gregorfa219202009-03-20 23:58:33 +00002006 // Pre-allocate storage for the structured initializer list.
2007 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002008 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002009 bool GotNumInits = false;
2010 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002011 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002012 GotNumInits = true;
2013 } else if (Index < IList->getNumInits()) {
2014 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002015 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002016 GotNumInits = true;
2017 }
Douglas Gregor08457732009-03-21 18:13:52 +00002018 }
2019
Mike Stump1eb44332009-09-09 15:08:12 +00002020 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002021 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2022 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2023 NumElements = CAType->getSize().getZExtValue();
2024 // Simple heuristic so that we don't allocate a very large
2025 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002026 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002027 NumElements = 0;
2028 }
John McCall183700f2009-09-21 23:43:11 +00002029 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002030 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002031 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002032 RecordDecl *RDecl = RType->getDecl();
2033 if (RDecl->isUnion())
2034 NumElements = 1;
2035 else
Mike Stump1eb44332009-09-09 15:08:12 +00002036 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002037 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002038 }
2039
Ted Kremenek709210f2010-04-13 23:39:13 +00002040 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002041
Douglas Gregor4c678342009-01-28 21:54:33 +00002042 // Link this new initializer list into the structured initializer
2043 // lists.
2044 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002045 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002046 else {
2047 Result->setSyntacticForm(IList);
2048 SyntacticToSemantic[IList] = Result;
2049 }
2050
2051 return Result;
2052}
2053
2054/// Update the initializer at index @p StructuredIndex within the
2055/// structured initializer list to the value @p expr.
2056void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2057 unsigned &StructuredIndex,
2058 Expr *expr) {
2059 // No structured initializer list to update
2060 if (!StructuredList)
2061 return;
2062
Ted Kremenek709210f2010-04-13 23:39:13 +00002063 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2064 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002065 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00002066 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002067 diag::warn_initializer_overrides)
2068 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002069 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002071 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002072 << PrevInit->getSourceRange();
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Douglas Gregor4c678342009-01-28 21:54:33 +00002075 ++StructuredIndex;
2076}
2077
Douglas Gregor05c13a32009-01-22 00:58:24 +00002078/// Check that the given Index expression is a valid array designator
2079/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002080/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002081/// and produces a reasonable diagnostic if there is a
2082/// failure. Returns true if there was an error, false otherwise. If
2083/// everything went okay, Value will receive the value of the constant
2084/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002085static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00002086CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002087 SourceLocation Loc = Index->getSourceRange().getBegin();
2088
2089 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00002090 if (S.VerifyIntegerConstantExpression(Index, &Value))
2091 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002092
Chris Lattner3bf68932009-04-25 21:59:05 +00002093 if (Value.isSigned() && Value.isNegative())
2094 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002095 << Value.toString(10) << Index->getSourceRange();
2096
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002097 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002098 return false;
2099}
2100
John McCall60d7b3a2010-08-24 06:29:42 +00002101ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002102 SourceLocation Loc,
2103 bool GNUSyntax,
2104 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002105 typedef DesignatedInitExpr::Designator ASTDesignator;
2106
2107 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002108 SmallVector<ASTDesignator, 32> Designators;
2109 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002110
2111 // Build designators and check array designator expressions.
2112 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2113 const Designator &D = Desig.getDesignator(Idx);
2114 switch (D.getKind()) {
2115 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002116 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002117 D.getFieldLoc()));
2118 break;
2119
2120 case Designator::ArrayDesignator: {
2121 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2122 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002123 if (!Index->isTypeDependent() &&
2124 !Index->isValueDependent() &&
2125 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002126 Invalid = true;
2127 else {
2128 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002129 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002130 D.getRBracketLoc()));
2131 InitExpressions.push_back(Index);
2132 }
2133 break;
2134 }
2135
2136 case Designator::ArrayRangeDesignator: {
2137 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2138 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2139 llvm::APSInt StartValue;
2140 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002141 bool StartDependent = StartIndex->isTypeDependent() ||
2142 StartIndex->isValueDependent();
2143 bool EndDependent = EndIndex->isTypeDependent() ||
2144 EndIndex->isValueDependent();
2145 if ((!StartDependent &&
2146 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2147 (!EndDependent &&
2148 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002149 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002150 else {
2151 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002152 if (StartDependent || EndDependent) {
2153 // Nothing to compute.
2154 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002155 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002156 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002157 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002158
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002159 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002160 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002161 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002162 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2163 Invalid = true;
2164 } else {
2165 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002166 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002167 D.getEllipsisLoc(),
2168 D.getRBracketLoc()));
2169 InitExpressions.push_back(StartIndex);
2170 InitExpressions.push_back(EndIndex);
2171 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002172 }
2173 break;
2174 }
2175 }
2176 }
2177
2178 if (Invalid || Init.isInvalid())
2179 return ExprError();
2180
2181 // Clear out the expressions within the designation.
2182 Desig.ClearExprs(*this);
2183
2184 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002185 = DesignatedInitExpr::Create(Context,
2186 Designators.data(), Designators.size(),
2187 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002188 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002189
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002190 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002191 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2192 << DIE->getSourceRange();
2193 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002194 Diag(DIE->getLocStart(), diag::ext_designated_init)
2195 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002196
Douglas Gregor05c13a32009-01-22 00:58:24 +00002197 return Owned(DIE);
2198}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002199
Douglas Gregor20093b42009-12-09 23:02:17 +00002200//===----------------------------------------------------------------------===//
2201// Initialization entity
2202//===----------------------------------------------------------------------===//
2203
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002204InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002205 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002206 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002207{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002208 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2209 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002210 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002211 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002212 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002213 Type = VT->getElementType();
2214 } else {
2215 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2216 assert(CT && "Unexpected type");
2217 Kind = EK_ComplexElement;
2218 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002219 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002220}
2221
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002222InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002223 CXXBaseSpecifier *Base,
2224 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002225{
2226 InitializedEntity Result;
2227 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002228 Result.Base = reinterpret_cast<uintptr_t>(Base);
2229 if (IsInheritedVirtualBase)
2230 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002231
Douglas Gregord6542d82009-12-22 15:35:07 +00002232 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002233 return Result;
2234}
2235
Douglas Gregor99a2e602009-12-16 01:38:02 +00002236DeclarationName InitializedEntity::getName() const {
2237 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002238 case EK_Parameter: {
2239 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2240 return (D ? D->getDeclName() : DeclarationName());
2241 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002242
2243 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002244 case EK_Member:
2245 return VariableOrMember->getDeclName();
2246
2247 case EK_Result:
2248 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002249 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002250 case EK_Temporary:
2251 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002252 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002253 case EK_ArrayElement:
2254 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002255 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002256 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002257 return DeclarationName();
2258 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002259
Douglas Gregor99a2e602009-12-16 01:38:02 +00002260 // Silence GCC warning
2261 return DeclarationName();
2262}
2263
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002264DeclaratorDecl *InitializedEntity::getDecl() const {
2265 switch (getKind()) {
2266 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002267 case EK_Member:
2268 return VariableOrMember;
2269
John McCallf85e1932011-06-15 23:02:42 +00002270 case EK_Parameter:
2271 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2272
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002273 case EK_Result:
2274 case EK_Exception:
2275 case EK_New:
2276 case EK_Temporary:
2277 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002278 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002279 case EK_ArrayElement:
2280 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002281 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002282 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002283 return 0;
2284 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002285
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002286 // Silence GCC warning
2287 return 0;
2288}
2289
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002290bool InitializedEntity::allowsNRVO() const {
2291 switch (getKind()) {
2292 case EK_Result:
2293 case EK_Exception:
2294 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002295
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002296 case EK_Variable:
2297 case EK_Parameter:
2298 case EK_Member:
2299 case EK_New:
2300 case EK_Temporary:
2301 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002302 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002303 case EK_ArrayElement:
2304 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002305 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002306 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002307 break;
2308 }
2309
2310 return false;
2311}
2312
Douglas Gregor20093b42009-12-09 23:02:17 +00002313//===----------------------------------------------------------------------===//
2314// Initialization sequence
2315//===----------------------------------------------------------------------===//
2316
2317void InitializationSequence::Step::Destroy() {
2318 switch (Kind) {
2319 case SK_ResolveAddressOfOverloadedFunction:
2320 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002321 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002322 case SK_CastDerivedToBaseLValue:
2323 case SK_BindReference:
2324 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002325 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002326 case SK_UserConversion:
2327 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002328 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002329 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002330 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002331 case SK_ListConstructorCall:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002332 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002333 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002334 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002335 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002336 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002337 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002338 case SK_PassByIndirectCopyRestore:
2339 case SK_PassByIndirectRestore:
2340 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002341 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002342
Douglas Gregor20093b42009-12-09 23:02:17 +00002343 case SK_ConversionSequence:
2344 delete ICS;
2345 }
2346}
2347
Douglas Gregorb70cf442010-03-26 20:14:36 +00002348bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002349 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002350}
2351
2352bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002353 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002354 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002355
Douglas Gregorb70cf442010-03-26 20:14:36 +00002356 switch (getFailureKind()) {
2357 case FK_TooManyInitsForReference:
2358 case FK_ArrayNeedsInitList:
2359 case FK_ArrayNeedsInitListOrStringLiteral:
2360 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2361 case FK_NonConstLValueReferenceBindingToTemporary:
2362 case FK_NonConstLValueReferenceBindingToUnrelated:
2363 case FK_RValueReferenceBindingToLValue:
2364 case FK_ReferenceInitDropsQualifiers:
2365 case FK_ReferenceInitFailed:
2366 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002367 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002368 case FK_TooManyInitsForScalar:
2369 case FK_ReferenceBindingToInitList:
2370 case FK_InitListBadDestinationType:
2371 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002372 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002373 case FK_ArrayTypeMismatch:
2374 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002375 case FK_ListInitializationFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002376 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002377
Douglas Gregorb70cf442010-03-26 20:14:36 +00002378 case FK_ReferenceInitOverloadFailed:
2379 case FK_UserConversionOverloadFailed:
2380 case FK_ConstructorOverloadFailed:
2381 return FailedOverloadResult == OR_Ambiguous;
2382 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002383
Douglas Gregorb70cf442010-03-26 20:14:36 +00002384 return false;
2385}
2386
Douglas Gregord6e44a32010-04-16 22:09:46 +00002387bool InitializationSequence::isConstructorInitialization() const {
2388 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2389}
2390
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002391bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2392 const Expr *Initializer,
2393 bool *isInitializerConstant,
2394 APValue *ConstantValue) const {
2395 if (Steps.empty() || Initializer->isValueDependent())
2396 return false;
2397
2398 const Step &LastStep = Steps.back();
2399 if (LastStep.Kind != SK_ConversionSequence)
2400 return false;
2401
2402 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2403 const StandardConversionSequence *SCS = NULL;
2404 switch (ICS.getKind()) {
2405 case ImplicitConversionSequence::StandardConversion:
2406 SCS = &ICS.Standard;
2407 break;
2408 case ImplicitConversionSequence::UserDefinedConversion:
2409 SCS = &ICS.UserDefined.After;
2410 break;
2411 case ImplicitConversionSequence::AmbiguousConversion:
2412 case ImplicitConversionSequence::EllipsisConversion:
2413 case ImplicitConversionSequence::BadConversion:
2414 return false;
2415 }
2416
2417 // Check if SCS represents a narrowing conversion, according to C++0x
2418 // [dcl.init.list]p7:
2419 //
2420 // A narrowing conversion is an implicit conversion ...
2421 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2422 QualType FromType = SCS->getToType(0);
2423 QualType ToType = SCS->getToType(1);
2424 switch (PossibleNarrowing) {
2425 // * from a floating-point type to an integer type, or
2426 //
2427 // * from an integer type or unscoped enumeration type to a floating-point
2428 // type, except where the source is a constant expression and the actual
2429 // value after conversion will fit into the target type and will produce
2430 // the original value when converted back to the original type, or
2431 case ICK_Floating_Integral:
2432 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2433 *isInitializerConstant = false;
2434 return true;
2435 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2436 llvm::APSInt IntConstantValue;
2437 if (Initializer &&
2438 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2439 // Convert the integer to the floating type.
2440 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2441 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2442 llvm::APFloat::rmNearestTiesToEven);
2443 // And back.
2444 llvm::APSInt ConvertedValue = IntConstantValue;
2445 bool ignored;
2446 Result.convertToInteger(ConvertedValue,
2447 llvm::APFloat::rmTowardZero, &ignored);
2448 // If the resulting value is different, this was a narrowing conversion.
2449 if (IntConstantValue != ConvertedValue) {
2450 *isInitializerConstant = true;
2451 *ConstantValue = APValue(IntConstantValue);
2452 return true;
2453 }
2454 } else {
2455 // Variables are always narrowings.
2456 *isInitializerConstant = false;
2457 return true;
2458 }
2459 }
2460 return false;
2461
2462 // * from long double to double or float, or from double to float, except
2463 // where the source is a constant expression and the actual value after
2464 // conversion is within the range of values that can be represented (even
2465 // if it cannot be represented exactly), or
2466 case ICK_Floating_Conversion:
2467 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2468 // FromType is larger than ToType.
2469 Expr::EvalResult InitializerValue;
2470 // FIXME: Check whether Initializer is a constant expression according
2471 // to C++0x [expr.const], rather than just whether it can be folded.
2472 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2473 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2474 // Constant! (Except for FIXME above.)
2475 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2476 // Convert the source value into the target type.
2477 bool ignored;
2478 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2479 Ctx.getFloatTypeSemantics(ToType),
2480 llvm::APFloat::rmNearestTiesToEven, &ignored);
2481 // If there was no overflow, the source value is within the range of
2482 // values that can be represented.
2483 if (ConvertStatus & llvm::APFloat::opOverflow) {
2484 *isInitializerConstant = true;
2485 *ConstantValue = InitializerValue.Val;
2486 return true;
2487 }
2488 } else {
2489 *isInitializerConstant = false;
2490 return true;
2491 }
2492 }
2493 return false;
2494
2495 // * from an integer type or unscoped enumeration type to an integer type
2496 // that cannot represent all the values of the original type, except where
2497 // the source is a constant expression and the actual value after
2498 // conversion will fit into the target type and will produce the original
2499 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002500 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002501 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2502 // Boolean conversions can be from pointers and pointers to members
2503 // [conv.bool], and those aren't considered narrowing conversions.
2504 return false;
2505 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002506 case ICK_Integral_Conversion: {
2507 assert(FromType->isIntegralOrUnscopedEnumerationType());
2508 assert(ToType->isIntegralOrUnscopedEnumerationType());
2509 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2510 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2511 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2512 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2513
2514 if (FromWidth > ToWidth ||
2515 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2516 // Not all values of FromType can be represented in ToType.
2517 llvm::APSInt InitializerValue;
2518 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2519 *isInitializerConstant = true;
2520 *ConstantValue = APValue(InitializerValue);
2521
2522 // Add a bit to the InitializerValue so we don't have to worry about
2523 // signed vs. unsigned comparisons.
2524 InitializerValue = InitializerValue.extend(
2525 InitializerValue.getBitWidth() + 1);
2526 // Convert the initializer to and from the target width and signed-ness.
2527 llvm::APSInt ConvertedValue = InitializerValue;
2528 ConvertedValue = ConvertedValue.trunc(ToWidth);
2529 ConvertedValue.setIsSigned(ToSigned);
2530 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2531 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2532 // If the result is different, this was a narrowing conversion.
2533 return ConvertedValue != InitializerValue;
2534 } else {
2535 // Variables are always narrowings.
2536 *isInitializerConstant = false;
2537 return true;
2538 }
2539 }
2540 return false;
2541 }
2542
2543 default:
2544 // Other kinds of conversions are not narrowings.
2545 return false;
2546 }
2547}
2548
Douglas Gregor20093b42009-12-09 23:02:17 +00002549void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002550 FunctionDecl *Function,
2551 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002552 Step S;
2553 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2554 S.Type = Function->getType();
Benjamin Kramer85035642011-10-09 17:58:25 +00002555 S.Function.HadMultipleCandidates = false;
John McCall9aa472c2010-03-19 07:35:19 +00002556 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002557 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002558 Steps.push_back(S);
2559}
2560
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002561void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002562 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002563 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002564 switch (VK) {
2565 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2566 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2567 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002568 default: llvm_unreachable("No such category");
2569 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002570 S.Type = BaseType;
2571 Steps.push_back(S);
2572}
2573
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002574void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002575 bool BindingTemporary) {
2576 Step S;
2577 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2578 S.Type = T;
2579 Steps.push_back(S);
2580}
2581
Douglas Gregor523d46a2010-04-18 07:40:54 +00002582void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2583 Step S;
2584 S.Kind = SK_ExtraneousCopyToTemporary;
2585 S.Type = T;
2586 Steps.push_back(S);
2587}
2588
Eli Friedman03981012009-12-11 02:42:07 +00002589void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002590 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002591 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002592 Step S;
2593 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002594 S.Type = T;
Benjamin Kramer85035642011-10-09 17:58:25 +00002595 S.Function.HadMultipleCandidates = false;
John McCall9aa472c2010-03-19 07:35:19 +00002596 S.Function.Function = Function;
2597 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002598 Steps.push_back(S);
2599}
2600
2601void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002602 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002603 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002604 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002605 switch (VK) {
2606 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002607 S.Kind = SK_QualificationConversionRValue;
2608 break;
John McCall5baba9d2010-08-25 10:28:54 +00002609 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002610 S.Kind = SK_QualificationConversionXValue;
2611 break;
John McCall5baba9d2010-08-25 10:28:54 +00002612 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002613 S.Kind = SK_QualificationConversionLValue;
2614 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002615 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002616 S.Type = Ty;
2617 Steps.push_back(S);
2618}
2619
2620void InitializationSequence::AddConversionSequenceStep(
2621 const ImplicitConversionSequence &ICS,
2622 QualType T) {
2623 Step S;
2624 S.Kind = SK_ConversionSequence;
2625 S.Type = T;
2626 S.ICS = new ImplicitConversionSequence(ICS);
2627 Steps.push_back(S);
2628}
2629
Douglas Gregord87b61f2009-12-10 17:56:55 +00002630void InitializationSequence::AddListInitializationStep(QualType T) {
2631 Step S;
2632 S.Kind = SK_ListInitialization;
2633 S.Type = T;
2634 Steps.push_back(S);
2635}
2636
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002637void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002638InitializationSequence::AddConstructorInitializationStep(
2639 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002640 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002641 QualType T) {
2642 Step S;
2643 S.Kind = SK_ConstructorInitialization;
2644 S.Type = T;
Benjamin Kramer85035642011-10-09 17:58:25 +00002645 S.Function.HadMultipleCandidates = false;
John McCall9aa472c2010-03-19 07:35:19 +00002646 S.Function.Function = Constructor;
2647 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002648 Steps.push_back(S);
2649}
2650
Douglas Gregor71d17402009-12-15 00:01:57 +00002651void InitializationSequence::AddZeroInitializationStep(QualType T) {
2652 Step S;
2653 S.Kind = SK_ZeroInitialization;
2654 S.Type = T;
2655 Steps.push_back(S);
2656}
2657
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002658void InitializationSequence::AddCAssignmentStep(QualType T) {
2659 Step S;
2660 S.Kind = SK_CAssignment;
2661 S.Type = T;
2662 Steps.push_back(S);
2663}
2664
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002665void InitializationSequence::AddStringInitStep(QualType T) {
2666 Step S;
2667 S.Kind = SK_StringInit;
2668 S.Type = T;
2669 Steps.push_back(S);
2670}
2671
Douglas Gregor569c3162010-08-07 11:51:51 +00002672void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2673 Step S;
2674 S.Kind = SK_ObjCObjectConversion;
2675 S.Type = T;
2676 Steps.push_back(S);
2677}
2678
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002679void InitializationSequence::AddArrayInitStep(QualType T) {
2680 Step S;
2681 S.Kind = SK_ArrayInit;
2682 S.Type = T;
2683 Steps.push_back(S);
2684}
2685
John McCallf85e1932011-06-15 23:02:42 +00002686void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2687 bool shouldCopy) {
2688 Step s;
2689 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2690 : SK_PassByIndirectRestore);
2691 s.Type = type;
2692 Steps.push_back(s);
2693}
2694
2695void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2696 Step S;
2697 S.Kind = SK_ProduceObjCObject;
2698 S.Type = T;
2699 Steps.push_back(S);
2700}
2701
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002703 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002704 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002705 this->Failure = Failure;
2706 this->FailedOverloadResult = Result;
2707}
2708
2709//===----------------------------------------------------------------------===//
2710// Attempt initialization
2711//===----------------------------------------------------------------------===//
2712
John McCallf85e1932011-06-15 23:02:42 +00002713static void MaybeProduceObjCObject(Sema &S,
2714 InitializationSequence &Sequence,
2715 const InitializedEntity &Entity) {
2716 if (!S.getLangOptions().ObjCAutoRefCount) return;
2717
2718 /// When initializing a parameter, produce the value if it's marked
2719 /// __attribute__((ns_consumed)).
2720 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2721 if (!Entity.isParameterConsumed())
2722 return;
2723
2724 assert(Entity.getType()->isObjCRetainableType() &&
2725 "consuming an object of unretainable type?");
2726 Sequence.AddProduceObjCObjectStep(Entity.getType());
2727
2728 /// When initializing a return value, if the return type is a
2729 /// retainable type, then returns need to immediately retain the
2730 /// object. If an autorelease is required, it will be done at the
2731 /// last instant.
2732 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2733 if (!Entity.getType()->isObjCRetainableType())
2734 return;
2735
2736 Sequence.AddProduceObjCObjectStep(Entity.getType());
2737 }
2738}
2739
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002740/// \brief Attempt list initialization (C++0x [dcl.init.list])
2741static void TryListInitialization(Sema &S,
2742 const InitializedEntity &Entity,
2743 const InitializationKind &Kind,
2744 InitListExpr *InitList,
2745 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002746 QualType DestType = Entity.getType();
2747
Sebastian Redl14b0c192011-09-24 17:48:00 +00002748 // C++ doesn't allow scalar initialization with more than one argument.
2749 // But C99 complex numbers are scalars and it makes sense there.
2750 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
2751 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
2752 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2753 return;
2754 }
2755 // FIXME: C++0x defines behavior for these two cases.
2756 if (DestType->isReferenceType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002757 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2758 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00002759 }
2760 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002761 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00002762 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002763 }
2764
Sebastian Redl14b0c192011-09-24 17:48:00 +00002765 InitListChecker CheckInitList(S, Entity, InitList,
2766 DestType, /*VerifyOnly=*/true);
2767 if (CheckInitList.HadError()) {
2768 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
2769 return;
2770 }
2771
2772 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002773 Sequence.AddListInitializationStep(DestType);
2774}
Douglas Gregor20093b42009-12-09 23:02:17 +00002775
2776/// \brief Try a reference initialization that involves calling a conversion
2777/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002778static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2779 const InitializedEntity &Entity,
2780 const InitializationKind &Kind,
2781 Expr *Initializer,
2782 bool AllowRValues,
2783 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002784 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002785 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2786 QualType T1 = cv1T1.getUnqualifiedType();
2787 QualType cv2T2 = Initializer->getType();
2788 QualType T2 = cv2T2.getUnqualifiedType();
2789
2790 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002791 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002792 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002793 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002794 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002795 ObjCConversion,
2796 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002797 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002798 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002799 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002800 (void)ObjCLifetimeConversion;
2801
Douglas Gregor20093b42009-12-09 23:02:17 +00002802 // Build the candidate set directly in the initialization sequence
2803 // structure, so that it will persist if we fail.
2804 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2805 CandidateSet.clear();
2806
2807 // Determine whether we are allowed to call explicit constructors or
2808 // explicit conversion operators.
2809 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810
Douglas Gregor20093b42009-12-09 23:02:17 +00002811 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002812 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2813 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002814 // The type we're converting to is a class type. Enumerate its constructors
2815 // to see if there is a suitable conversion.
2816 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002817
Douglas Gregor20093b42009-12-09 23:02:17 +00002818 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002819 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002820 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002821 NamedDecl *D = *Con;
2822 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2823
Douglas Gregor20093b42009-12-09 23:02:17 +00002824 // Find the constructor (which may be a template).
2825 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002826 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002827 if (ConstructorTmpl)
2828 Constructor = cast<CXXConstructorDecl>(
2829 ConstructorTmpl->getTemplatedDecl());
2830 else
John McCall9aa472c2010-03-19 07:35:19 +00002831 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002832
Douglas Gregor20093b42009-12-09 23:02:17 +00002833 if (!Constructor->isInvalidDecl() &&
2834 Constructor->isConvertingConstructor(AllowExplicit)) {
2835 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002836 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002837 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002838 &Initializer, 1, CandidateSet,
2839 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002840 else
John McCall9aa472c2010-03-19 07:35:19 +00002841 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002842 &Initializer, 1, CandidateSet,
2843 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002844 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002845 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002846 }
John McCall572fc622010-08-17 07:23:57 +00002847 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2848 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002849
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002850 const RecordType *T2RecordType = 0;
2851 if ((T2RecordType = T2->getAs<RecordType>()) &&
2852 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002853 // The type we're converting from is a class type, enumerate its conversion
2854 // functions.
2855 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2856
John McCalleec51cf2010-01-20 00:46:10 +00002857 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002858 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002859 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2860 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002861 NamedDecl *D = *I;
2862 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2863 if (isa<UsingShadowDecl>(D))
2864 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002865
Douglas Gregor20093b42009-12-09 23:02:17 +00002866 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2867 CXXConversionDecl *Conv;
2868 if (ConvTemplate)
2869 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2870 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002871 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002872
Douglas Gregor20093b42009-12-09 23:02:17 +00002873 // If the conversion function doesn't return a reference type,
2874 // it can't be considered for this conversion unless we're allowed to
2875 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002876 // FIXME: Do we need to make sure that we only consider conversion
2877 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002878 // break recursion.
2879 if ((AllowExplicit || !Conv->isExplicit()) &&
2880 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2881 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002882 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002883 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002884 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002885 else
John McCall9aa472c2010-03-19 07:35:19 +00002886 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002887 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002888 }
2889 }
2890 }
John McCall572fc622010-08-17 07:23:57 +00002891 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2892 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002893
Douglas Gregor20093b42009-12-09 23:02:17 +00002894 SourceLocation DeclLoc = Initializer->getLocStart();
2895
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002896 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002897 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002898 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002899 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002900 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002901
Douglas Gregor20093b42009-12-09 23:02:17 +00002902 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002903
Chandler Carruth25ca4212011-02-25 19:41:05 +00002904 // This is the overload that will actually be used for the initialization, so
2905 // mark it as used.
2906 S.MarkDeclarationReferenced(DeclLoc, Function);
2907
Eli Friedman03981012009-12-11 02:42:07 +00002908 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002909 if (isa<CXXConversionDecl>(Function))
2910 T2 = Function->getResultType();
2911 else
2912 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002913
2914 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002915 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002916 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002917
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002918 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002919 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002920 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002921 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002922 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002923 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002924 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002925
Douglas Gregor20093b42009-12-09 23:02:17 +00002926 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002927 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002928 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002929 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002930 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002931 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002932 NewDerivedToBase, NewObjCConversion,
2933 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002934 if (NewRefRelationship == Sema::Ref_Incompatible) {
2935 // If the type we've converted to is not reference-related to the
2936 // type we're looking for, then there is another conversion step
2937 // we need to perform to produce a temporary of the right type
2938 // that we'll be binding to.
2939 ImplicitConversionSequence ICS;
2940 ICS.setStandard();
2941 ICS.Standard = Best->FinalConversion;
2942 T2 = ICS.Standard.getToType(2);
2943 Sequence.AddConversionSequenceStep(ICS, T2);
2944 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002945 Sequence.AddDerivedToBaseCastStep(
2946 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002947 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002948 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002949 else if (NewObjCConversion)
2950 Sequence.AddObjCObjectConversionStep(
2951 S.Context.getQualifiedType(T1,
2952 T2.getNonReferenceType().getQualifiers()));
2953
Douglas Gregor20093b42009-12-09 23:02:17 +00002954 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002955 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002956
Douglas Gregor20093b42009-12-09 23:02:17 +00002957 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2958 return OR_Success;
2959}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002960
2961/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2962static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002963 const InitializedEntity &Entity,
2964 const InitializationKind &Kind,
2965 Expr *Initializer,
2966 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002967 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002968 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002969 Qualifiers T1Quals;
2970 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002971 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002972 Qualifiers T2Quals;
2973 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002974 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002975
Douglas Gregor20093b42009-12-09 23:02:17 +00002976 // If the initializer is the address of an overloaded function, try
2977 // to resolve the overloaded function. If all goes well, T2 is the
2978 // type of the resulting function.
2979 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002980 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002981 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002982 T1,
2983 false,
2984 Found)) {
2985 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2986 cv2T2 = Fn->getType();
2987 T2 = cv2T2.getUnqualifiedType();
2988 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002989 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2990 return;
2991 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002992 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002993
Douglas Gregor20093b42009-12-09 23:02:17 +00002994 // Compute some basic properties of the types and the initializer.
2995 bool isLValueRef = DestType->isLValueReferenceType();
2996 bool isRValueRef = !isLValueRef;
2997 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002998 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002999 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003000 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003001 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003002 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003003 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003004
Douglas Gregor20093b42009-12-09 23:02:17 +00003005 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003006 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003007 // "cv2 T2" as follows:
3008 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003009 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003010 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003011 // Note the analogous bullet points for rvlaue refs to functions. Because
3012 // there are no function rvalues in C++, rvalue refs to functions are treated
3013 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003014 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003015 bool T1Function = T1->isFunctionType();
3016 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003017 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003018 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003019 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003020 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003021 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003022 // reference-compatible with "cv2 T2," or
3023 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003024 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003025 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003026 // can occur. However, we do pay attention to whether it is a bit-field
3027 // to decide whether we're actually binding to a temporary created from
3028 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003029 if (DerivedToBase)
3030 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003031 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003032 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003033 else if (ObjCConversion)
3034 Sequence.AddObjCObjectConversionStep(
3035 S.Context.getQualifiedType(T1, T2Quals));
3036
Chandler Carruth5535c382010-01-12 20:32:25 +00003037 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003038 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003039 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003040 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003041 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003042 return;
3043 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003044
3045 // - has a class type (i.e., T2 is a class type), where T1 is not
3046 // reference-related to T2, and can be implicitly converted to an
3047 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3048 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003049 // applicable conversion functions (13.3.1.6) and choosing the best
3050 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003051 // If we have an rvalue ref to function type here, the rhs must be
3052 // an rvalue.
3053 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3054 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003055 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003056 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003057 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003058 Sequence);
3059 if (ConvOvlResult == OR_Success)
3060 return;
John McCall1d318332010-01-12 00:44:57 +00003061 if (ConvOvlResult != OR_No_Viable_Function) {
3062 Sequence.SetOverloadFailure(
3063 InitializationSequence::FK_ReferenceInitOverloadFailed,
3064 ConvOvlResult);
3065 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003066 }
3067 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003068
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003069 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003070 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003071 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003072 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003073 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3074 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3075 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003076 Sequence.SetOverloadFailure(
3077 InitializationSequence::FK_ReferenceInitOverloadFailed,
3078 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003079 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003080 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003081 ? (RefRelationship == Sema::Ref_Related
3082 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3083 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3084 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003085
Douglas Gregor20093b42009-12-09 23:02:17 +00003086 return;
3087 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003088
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003089 // - If the initializer expression
3090 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3091 // "cv1 T1" is reference-compatible with "cv2 T2"
3092 // Note: functions are handled below.
3093 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003094 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003095 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003096 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003097 (InitCategory.isXValue() ||
3098 (InitCategory.isPRValue() && T2->isRecordType()) ||
3099 (InitCategory.isPRValue() && T2->isArrayType()))) {
3100 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3101 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003102 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3103 // compiler the freedom to perform a copy here or bind to the
3104 // object, while C++0x requires that we bind directly to the
3105 // object. Hence, we always bind to the object without making an
3106 // extra copy. However, in C++03 requires that we check for the
3107 // presence of a suitable copy constructor:
3108 //
3109 // The constructor that would be used to make the copy shall
3110 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003111 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003112 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00003113 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003114
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003115 if (DerivedToBase)
3116 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3117 ValueKind);
3118 else if (ObjCConversion)
3119 Sequence.AddObjCObjectConversionStep(
3120 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003122 if (T1Quals != T2Quals)
3123 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003125 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003126 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003127 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003128
3129 // - has a class type (i.e., T2 is a class type), where T1 is not
3130 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003131 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3132 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003133 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003134 if (RefRelationship == Sema::Ref_Incompatible) {
3135 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3136 Kind, Initializer,
3137 /*AllowRValues=*/true,
3138 Sequence);
3139 if (ConvOvlResult)
3140 Sequence.SetOverloadFailure(
3141 InitializationSequence::FK_ReferenceInitOverloadFailed,
3142 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003143
Douglas Gregor20093b42009-12-09 23:02:17 +00003144 return;
3145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003146
Douglas Gregor20093b42009-12-09 23:02:17 +00003147 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3148 return;
3149 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003150
3151 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003152 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003153 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003154 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003155
Douglas Gregor20093b42009-12-09 23:02:17 +00003156 // Determine whether we are allowed to call explicit constructors or
3157 // explicit conversion operators.
3158 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003159
3160 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3161
John McCallf85e1932011-06-15 23:02:42 +00003162 ImplicitConversionSequence ICS
3163 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003164 /*SuppressUserConversions*/ false,
3165 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003166 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003167 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3168 /*AllowObjCWritebackConversion=*/false);
3169
3170 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003171 // FIXME: Use the conversion function set stored in ICS to turn
3172 // this into an overloading ambiguity diagnostic. However, we need
3173 // to keep that set as an OverloadCandidateSet rather than as some
3174 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003175 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3176 Sequence.SetOverloadFailure(
3177 InitializationSequence::FK_ReferenceInitOverloadFailed,
3178 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003179 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3180 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003181 else
3182 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003183 return;
John McCallf85e1932011-06-15 23:02:42 +00003184 } else {
3185 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003186 }
3187
3188 // [...] If T1 is reference-related to T2, cv1 must be the
3189 // same cv-qualification as, or greater cv-qualification
3190 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003191 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3192 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003194 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003195 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3196 return;
3197 }
3198
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003200 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003202 InitCategory.isLValue()) {
3203 Sequence.SetFailed(
3204 InitializationSequence::FK_RValueReferenceBindingToLValue);
3205 return;
3206 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003207
Douglas Gregor20093b42009-12-09 23:02:17 +00003208 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3209 return;
3210}
3211
3212/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003213/// (C++ [dcl.init.string], C99 6.7.8).
3214static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003215 const InitializedEntity &Entity,
3216 const InitializationKind &Kind,
3217 Expr *Initializer,
3218 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003219 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003220}
3221
Douglas Gregor20093b42009-12-09 23:02:17 +00003222/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3223/// enumerates the constructors of the initialized entity and performs overload
3224/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003225static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003226 const InitializedEntity &Entity,
3227 const InitializationKind &Kind,
3228 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003229 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003230 InitializationSequence &Sequence) {
Richard Trieu898267f2011-09-01 21:44:13 +00003231 // Check constructor arguments for self reference.
3232 if (DeclaratorDecl *DD = Entity.getDecl())
3233 // Parameters arguments are occassionially constructed with itself,
3234 // for instance, in recursive functions. Skip them.
3235 if (!isa<ParmVarDecl>(DD))
3236 for (unsigned i = 0; i < NumArgs; ++i)
3237 S.CheckSelfReference(DD, Args[i]);
3238
Douglas Gregor51c56d62009-12-14 20:49:26 +00003239 // Build the candidate set directly in the initialization sequence
3240 // structure, so that it will persist if we fail.
3241 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3242 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003243
Douglas Gregor51c56d62009-12-14 20:49:26 +00003244 // Determine whether we are allowed to call explicit constructors or
3245 // explicit conversion operators.
3246 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3247 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003248 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003249
3250 // The type we're constructing needs to be complete.
3251 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003252 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003253 return;
3254 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255
Douglas Gregor51c56d62009-12-14 20:49:26 +00003256 // The type we're converting to is a class type. Enumerate its constructors
3257 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003258 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003259 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003260 CXXRecordDecl *DestRecordDecl
3261 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003262
Douglas Gregor51c56d62009-12-14 20:49:26 +00003263 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003264 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003265 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003266 NamedDecl *D = *Con;
3267 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003268 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003269
Douglas Gregor51c56d62009-12-14 20:49:26 +00003270 // Find the constructor (which may be a template).
3271 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003272 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003273 if (ConstructorTmpl)
3274 Constructor = cast<CXXConstructorDecl>(
3275 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003276 else {
John McCall9aa472c2010-03-19 07:35:19 +00003277 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003278
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003279 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003280 // suppress user-defined conversions on the arguments.
3281 // FIXME: Move constructors?
3282 if (Kind.getKind() == InitializationKind::IK_Copy &&
3283 Constructor->isCopyConstructor())
3284 SuppressUserConversions = true;
3285 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003286
Douglas Gregor51c56d62009-12-14 20:49:26 +00003287 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003288 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003289 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003290 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003291 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003292 Args, NumArgs, CandidateSet,
3293 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003294 else
John McCall9aa472c2010-03-19 07:35:19 +00003295 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003296 Args, NumArgs, CandidateSet,
3297 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003298 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003299 }
3300
Douglas Gregor51c56d62009-12-14 20:49:26 +00003301 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003302
3303 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003304 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003305 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003306 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003307 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003308 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003309 Result);
3310 return;
3311 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003312
3313 // C++0x [dcl.init]p6:
3314 // If a program calls for the default initialization of an object
3315 // of a const-qualified type T, T shall be a class type with a
3316 // user-provided default constructor.
3317 if (Kind.getKind() == InitializationKind::IK_Default &&
3318 Entity.getType().isConstQualified() &&
3319 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3320 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3321 return;
3322 }
3323
Douglas Gregor51c56d62009-12-14 20:49:26 +00003324 // Add the constructor initialization step. Any cv-qualification conversion is
3325 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003326 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003328 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003329 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003330}
3331
Douglas Gregor71d17402009-12-15 00:01:57 +00003332/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003333static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003334 const InitializedEntity &Entity,
3335 const InitializationKind &Kind,
3336 InitializationSequence &Sequence) {
3337 // C++ [dcl.init]p5:
3338 //
3339 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003340 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003341
Douglas Gregor71d17402009-12-15 00:01:57 +00003342 // -- if T is an array type, then each element is value-initialized;
3343 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3344 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003345
Douglas Gregor71d17402009-12-15 00:01:57 +00003346 if (const RecordType *RT = T->getAs<RecordType>()) {
3347 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3348 // -- if T is a class type (clause 9) with a user-declared
3349 // constructor (12.1), then the default constructor for T is
3350 // called (and the initialization is ill-formed if T has no
3351 // accessible default constructor);
3352 //
3353 // FIXME: we really want to refer to a single subobject of the array,
3354 // but Entity doesn't have a way to capture that (yet).
3355 if (ClassDecl->hasUserDeclaredConstructor())
3356 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003357
Douglas Gregor16006c92009-12-16 18:50:27 +00003358 // -- if T is a (possibly cv-qualified) non-union class type
3359 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003360 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003361 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003362 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003363 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003364 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003366 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003367 }
3368 }
3369
Douglas Gregord6542d82009-12-22 15:35:07 +00003370 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003371}
3372
Douglas Gregor99a2e602009-12-16 01:38:02 +00003373/// \brief Attempt default initialization (C++ [dcl.init]p6).
3374static void TryDefaultInitialization(Sema &S,
3375 const InitializedEntity &Entity,
3376 const InitializationKind &Kind,
3377 InitializationSequence &Sequence) {
3378 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379
Douglas Gregor99a2e602009-12-16 01:38:02 +00003380 // C++ [dcl.init]p6:
3381 // To default-initialize an object of type T means:
3382 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003383 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3384
Douglas Gregor99a2e602009-12-16 01:38:02 +00003385 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3386 // constructor for T is called (and the initialization is ill-formed if
3387 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003388 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003389 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3390 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003391 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003392
Douglas Gregor99a2e602009-12-16 01:38:02 +00003393 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003394
Douglas Gregor99a2e602009-12-16 01:38:02 +00003395 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003396 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003397 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003398 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003399 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003400 return;
3401 }
3402
3403 // If the destination type has a lifetime property, zero-initialize it.
3404 if (DestType.getQualifiers().hasObjCLifetime()) {
3405 Sequence.AddZeroInitializationStep(Entity.getType());
3406 return;
3407 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003408}
3409
Douglas Gregor20093b42009-12-09 23:02:17 +00003410/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3411/// which enumerates all conversion functions and performs overload resolution
3412/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003413static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003414 const InitializedEntity &Entity,
3415 const InitializationKind &Kind,
3416 Expr *Initializer,
3417 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003418 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003419 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3420 QualType SourceType = Initializer->getType();
3421 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3422 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003423
Douglas Gregor4a520a22009-12-14 17:27:33 +00003424 // Build the candidate set directly in the initialization sequence
3425 // structure, so that it will persist if we fail.
3426 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3427 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003428
Douglas Gregor4a520a22009-12-14 17:27:33 +00003429 // Determine whether we are allowed to call explicit constructors or
3430 // explicit conversion operators.
3431 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003432
Douglas Gregor4a520a22009-12-14 17:27:33 +00003433 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3434 // The type we're converting to is a class type. Enumerate its constructors
3435 // to see if there is a suitable conversion.
3436 CXXRecordDecl *DestRecordDecl
3437 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003438
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003439 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003440 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003441 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003442 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003443 Con != ConEnd; ++Con) {
3444 NamedDecl *D = *Con;
3445 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003446
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003447 // Find the constructor (which may be a template).
3448 CXXConstructorDecl *Constructor = 0;
3449 FunctionTemplateDecl *ConstructorTmpl
3450 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003451 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003452 Constructor = cast<CXXConstructorDecl>(
3453 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003454 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003455 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003456
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003457 if (!Constructor->isInvalidDecl() &&
3458 Constructor->isConvertingConstructor(AllowExplicit)) {
3459 if (ConstructorTmpl)
3460 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3461 /*ExplicitArgs*/ 0,
3462 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003463 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003464 else
3465 S.AddOverloadCandidate(Constructor, FoundDecl,
3466 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003467 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003468 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003469 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003470 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003471 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003472
3473 SourceLocation DeclLoc = Initializer->getLocStart();
3474
Douglas Gregor4a520a22009-12-14 17:27:33 +00003475 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3476 // The type we're converting from is a class type, enumerate its conversion
3477 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003478
Eli Friedman33c2da92009-12-20 22:12:03 +00003479 // We can only enumerate the conversion functions for a complete type; if
3480 // the type isn't complete, simply skip this step.
3481 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3482 CXXRecordDecl *SourceRecordDecl
3483 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003484
John McCalleec51cf2010-01-20 00:46:10 +00003485 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003486 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003487 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003488 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003489 I != E; ++I) {
3490 NamedDecl *D = *I;
3491 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3492 if (isa<UsingShadowDecl>(D))
3493 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003494
Eli Friedman33c2da92009-12-20 22:12:03 +00003495 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3496 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003497 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003498 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003499 else
John McCall32daa422010-03-31 01:36:47 +00003500 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003501
Eli Friedman33c2da92009-12-20 22:12:03 +00003502 if (AllowExplicit || !Conv->isExplicit()) {
3503 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003504 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003505 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003506 CandidateSet);
3507 else
John McCall9aa472c2010-03-19 07:35:19 +00003508 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003509 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003510 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003511 }
3512 }
3513 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003514
3515 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003516 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003517 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003518 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003519 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003520 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003521 Result);
3522 return;
3523 }
John McCall1d318332010-01-12 00:44:57 +00003524
Douglas Gregor4a520a22009-12-14 17:27:33 +00003525 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003526 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003527
Douglas Gregor4a520a22009-12-14 17:27:33 +00003528 if (isa<CXXConstructorDecl>(Function)) {
3529 // Add the user-defined conversion step. Any cv-qualification conversion is
3530 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003531 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003532 return;
3533 }
3534
3535 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003536 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003537 if (ConvType->getAs<RecordType>()) {
3538 // If we're converting to a class type, there may be an copy if
3539 // the resulting temporary object (possible to create an object of
3540 // a base class type). That copy is not a separate conversion, so
3541 // we just make a note of the actual destination type (possibly a
3542 // base class of the type returned by the conversion function) and
3543 // let the user-defined conversion step handle the conversion.
3544 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3545 return;
3546 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003547
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003548 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003549
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003550 // If the conversion following the call to the conversion function
3551 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003552 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3553 Best->FinalConversion.Third) {
3554 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003555 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003556 ICS.Standard = Best->FinalConversion;
3557 Sequence.AddConversionSequenceStep(ICS, DestType);
3558 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003559}
3560
John McCallf85e1932011-06-15 23:02:42 +00003561/// The non-zero enum values here are indexes into diagnostic alternatives.
3562enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3563
3564/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003565static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3566 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003567 // Skip parens.
3568 e = e->IgnoreParens();
3569
3570 // Skip address-of nodes.
3571 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3572 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003573 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003574
3575 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003576 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3577 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003578 case CK_Dependent:
3579 case CK_BitCast:
3580 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003581 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003582 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003583
3584 case CK_ArrayToPointerDecay:
3585 return IIK_nonscalar;
3586
3587 case CK_NullToPointer:
3588 return IIK_okay;
3589
3590 default:
3591 break;
3592 }
3593
3594 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003595 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3596 if (!isAddressOf) return IIK_nonlocal;
3597
3598 VarDecl *var;
3599 if (isa<DeclRefExpr>(e)) {
3600 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3601 if (!var) return IIK_nonlocal;
3602 } else {
3603 var = cast<BlockDeclRefExpr>(e)->getDecl();
3604 }
3605
3606 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003607
3608 // If we have a conditional operator, check both sides.
3609 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003610 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003611 return iik;
3612
John McCallc03fa492011-06-27 23:59:58 +00003613 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003614
3615 // These are never scalar.
3616 } else if (isa<ArraySubscriptExpr>(e)) {
3617 return IIK_nonscalar;
3618
3619 // Otherwise, it needs to be a null pointer constant.
3620 } else {
3621 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3622 ? IIK_okay : IIK_nonlocal);
3623 }
3624
3625 return IIK_nonlocal;
3626}
3627
3628/// Check whether the given expression is a valid operand for an
3629/// indirect copy/restore.
3630static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3631 assert(src->isRValue());
3632
John McCallc03fa492011-06-27 23:59:58 +00003633 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003634 if (iik == IIK_okay) return;
3635
3636 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3637 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3638 << src->getSourceRange();
3639}
3640
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003641/// \brief Determine whether we have compatible array types for the
3642/// purposes of GNU by-copy array initialization.
3643static bool hasCompatibleArrayTypes(ASTContext &Context,
3644 const ArrayType *Dest,
3645 const ArrayType *Source) {
3646 // If the source and destination array types are equivalent, we're
3647 // done.
3648 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3649 return true;
3650
3651 // Make sure that the element types are the same.
3652 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3653 return false;
3654
3655 // The only mismatch we allow is when the destination is an
3656 // incomplete array type and the source is a constant array type.
3657 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3658}
3659
John McCallf85e1932011-06-15 23:02:42 +00003660static bool tryObjCWritebackConversion(Sema &S,
3661 InitializationSequence &Sequence,
3662 const InitializedEntity &Entity,
3663 Expr *Initializer) {
3664 bool ArrayDecay = false;
3665 QualType ArgType = Initializer->getType();
3666 QualType ArgPointee;
3667 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3668 ArrayDecay = true;
3669 ArgPointee = ArgArrayType->getElementType();
3670 ArgType = S.Context.getPointerType(ArgPointee);
3671 }
3672
3673 // Handle write-back conversion.
3674 QualType ConvertedArgType;
3675 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3676 ConvertedArgType))
3677 return false;
3678
3679 // We should copy unless we're passing to an argument explicitly
3680 // marked 'out'.
3681 bool ShouldCopy = true;
3682 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3683 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3684
3685 // Do we need an lvalue conversion?
3686 if (ArrayDecay || Initializer->isGLValue()) {
3687 ImplicitConversionSequence ICS;
3688 ICS.setStandard();
3689 ICS.Standard.setAsIdentityConversion();
3690
3691 QualType ResultType;
3692 if (ArrayDecay) {
3693 ICS.Standard.First = ICK_Array_To_Pointer;
3694 ResultType = S.Context.getPointerType(ArgPointee);
3695 } else {
3696 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3697 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3698 }
3699
3700 Sequence.AddConversionSequenceStep(ICS, ResultType);
3701 }
3702
3703 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3704 return true;
3705}
3706
Douglas Gregor20093b42009-12-09 23:02:17 +00003707InitializationSequence::InitializationSequence(Sema &S,
3708 const InitializedEntity &Entity,
3709 const InitializationKind &Kind,
3710 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003711 unsigned NumArgs)
3712 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003713 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003714
Douglas Gregor20093b42009-12-09 23:02:17 +00003715 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003716 // The semantics of initializers are as follows. The destination type is
3717 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003718 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003719 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003720 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003721 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003722
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003723 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003724 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3725 SequenceKind = DependentSequence;
3726 return;
3727 }
3728
Sebastian Redl7491c492011-06-05 13:59:11 +00003729 // Almost everything is a normal sequence.
3730 setSequenceKind(NormalSequence);
3731
John McCall241d5582010-12-07 22:54:16 +00003732 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003733 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3734 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3735 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003736 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003737 return;
3738 }
3739 Args[I] = Result.take();
3740 }
John McCall241d5582010-12-07 22:54:16 +00003741
Douglas Gregor20093b42009-12-09 23:02:17 +00003742 QualType SourceType;
3743 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003744 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003745 Initializer = Args[0];
3746 if (!isa<InitListExpr>(Initializer))
3747 SourceType = Initializer->getType();
3748 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003749
3750 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003751 // list-initialized (8.5.4).
3752 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003753 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003754 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003755 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003756
Douglas Gregor20093b42009-12-09 23:02:17 +00003757 // - If the destination type is a reference type, see 8.5.3.
3758 if (DestType->isReferenceType()) {
3759 // C++0x [dcl.init.ref]p1:
3760 // A variable declared to be a T& or T&&, that is, "reference to type T"
3761 // (8.3.2), shall be initialized by an object, or function, of type T or
3762 // by an object that can be converted into a T.
3763 // (Therefore, multiple arguments are not permitted.)
3764 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003765 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003766 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003767 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003768 return;
3769 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770
Douglas Gregor20093b42009-12-09 23:02:17 +00003771 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003772 if (Kind.getKind() == InitializationKind::IK_Value ||
3773 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003774 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003775 return;
3776 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003777
Douglas Gregor99a2e602009-12-16 01:38:02 +00003778 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003779 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003780 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003781 return;
3782 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003783
John McCallce6c9b72011-02-21 07:22:22 +00003784 // - If the destination type is an array of characters, an array of
3785 // char16_t, an array of char32_t, or an array of wchar_t, and the
3786 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003787 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003788 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003789 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3790 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003791 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003792 return;
3793 }
3794
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003795 // Note: as an GNU C extension, we allow initialization of an
3796 // array from a compound literal that creates an array of the same
3797 // type, so long as the initializer has no side effects.
3798 if (!S.getLangOptions().CPlusPlus && Initializer &&
3799 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3800 Initializer->getType()->isArrayType()) {
3801 const ArrayType *SourceAT
3802 = Context.getAsArrayType(Initializer->getType());
3803 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003804 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003805 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003806 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003807 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003808 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003809 }
3810 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003811 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003812 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003813 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814
Douglas Gregor20093b42009-12-09 23:02:17 +00003815 return;
3816 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003817
John McCallf85e1932011-06-15 23:02:42 +00003818 // Determine whether we should consider writeback conversions for
3819 // Objective-C ARC.
3820 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3821 Entity.getKind() == InitializedEntity::EK_Parameter;
3822
3823 // We're at the end of the line for C: it's either a write-back conversion
3824 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003825 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003826 // If allowed, check whether this is an Objective-C writeback conversion.
3827 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003828 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003829 return;
3830 }
3831
3832 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003833 AddCAssignmentStep(DestType);
3834 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003835 return;
3836 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003837
John McCallf85e1932011-06-15 23:02:42 +00003838 assert(S.getLangOptions().CPlusPlus);
3839
Douglas Gregor20093b42009-12-09 23:02:17 +00003840 // - If the destination type is a (possibly cv-qualified) class type:
3841 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842 // - If the initialization is direct-initialization, or if it is
3843 // copy-initialization where the cv-unqualified version of the
3844 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003845 // class of the destination, constructors are considered. [...]
3846 if (Kind.getKind() == InitializationKind::IK_Direct ||
3847 (Kind.getKind() == InitializationKind::IK_Copy &&
3848 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3849 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003850 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003851 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003852 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003853 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003854 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003855 // used) to a derived class thereof are enumerated as described in
3856 // 13.3.1.4, and the best one is chosen through overload resolution
3857 // (13.3).
3858 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003859 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003860 return;
3861 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003862
Douglas Gregor99a2e602009-12-16 01:38:02 +00003863 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003864 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003865 return;
3866 }
3867 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868
3869 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003870 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003871 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003872 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3873 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003874 return;
3875 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003876
Douglas Gregor20093b42009-12-09 23:02:17 +00003877 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003878 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003879 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003880 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003881 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003882
3883 ImplicitConversionSequence ICS
3884 = S.TryImplicitConversion(Initializer, Entity.getType(),
3885 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003886 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003887 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003888 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3889 allowObjCWritebackConversion);
3890
3891 if (ICS.isStandard() &&
3892 ICS.Standard.Second == ICK_Writeback_Conversion) {
3893 // Objective-C ARC writeback conversion.
3894
3895 // We should copy unless we're passing to an argument explicitly
3896 // marked 'out'.
3897 bool ShouldCopy = true;
3898 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3899 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3900
3901 // If there was an lvalue adjustment, add it as a separate conversion.
3902 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3903 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3904 ImplicitConversionSequence LvalueICS;
3905 LvalueICS.setStandard();
3906 LvalueICS.Standard.setAsIdentityConversion();
3907 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3908 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003909 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003910 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003911
3912 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003913 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003914 DeclAccessPair dap;
3915 if (Initializer->getType() == Context.OverloadTy &&
3916 !S.ResolveAddressOfOverloadedFunction(Initializer
3917 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003918 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003919 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003920 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003921 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003922 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003923
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003924 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003925 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003926}
3927
3928InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003929 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003930 StepEnd = Steps.end();
3931 Step != StepEnd; ++Step)
3932 Step->Destroy();
3933}
3934
3935//===----------------------------------------------------------------------===//
3936// Perform initialization
3937//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003939getAssignmentAction(const InitializedEntity &Entity) {
3940 switch(Entity.getKind()) {
3941 case InitializedEntity::EK_Variable:
3942 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003943 case InitializedEntity::EK_Exception:
3944 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003945 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003946 return Sema::AA_Initializing;
3947
3948 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003949 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003950 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3951 return Sema::AA_Sending;
3952
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003953 return Sema::AA_Passing;
3954
3955 case InitializedEntity::EK_Result:
3956 return Sema::AA_Returning;
3957
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003958 case InitializedEntity::EK_Temporary:
3959 // FIXME: Can we tell apart casting vs. converting?
3960 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003961
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003962 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003963 case InitializedEntity::EK_ArrayElement:
3964 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00003965 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003966 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003967 return Sema::AA_Initializing;
3968 }
3969
3970 return Sema::AA_Converting;
3971}
3972
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003973/// \brief Whether we should binding a created object as a temporary when
3974/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003975static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003976 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003977 case InitializedEntity::EK_ArrayElement:
3978 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003979 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003980 case InitializedEntity::EK_New:
3981 case InitializedEntity::EK_Variable:
3982 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003983 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003984 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00003985 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003986 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003987 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003988 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003989
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003990 case InitializedEntity::EK_Parameter:
3991 case InitializedEntity::EK_Temporary:
3992 return true;
3993 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003994
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003995 llvm_unreachable("missed an InitializedEntity kind?");
3996}
3997
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003998/// \brief Whether the given entity, when initialized with an object
3999/// created for that initialization, requires destruction.
4000static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4001 switch (Entity.getKind()) {
4002 case InitializedEntity::EK_Member:
4003 case InitializedEntity::EK_Result:
4004 case InitializedEntity::EK_New:
4005 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004006 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004007 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004008 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004009 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004010 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004011
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004012 case InitializedEntity::EK_Variable:
4013 case InitializedEntity::EK_Parameter:
4014 case InitializedEntity::EK_Temporary:
4015 case InitializedEntity::EK_ArrayElement:
4016 case InitializedEntity::EK_Exception:
4017 return true;
4018 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004019
4020 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004021}
4022
Douglas Gregor523d46a2010-04-18 07:40:54 +00004023/// \brief Make a (potentially elidable) temporary copy of the object
4024/// provided by the given initializer by calling the appropriate copy
4025/// constructor.
4026///
4027/// \param S The Sema object used for type-checking.
4028///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004029/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004030/// the type of the initializer expression or a superclass thereof.
4031///
4032/// \param Enter The entity being initialized.
4033///
4034/// \param CurInit The initializer expression.
4035///
4036/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4037/// is permitted in C++03 (but not C++0x) when binding a reference to
4038/// an rvalue.
4039///
4040/// \returns An expression that copies the initializer expression into
4041/// a temporary object, or an error expression if a copy could not be
4042/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004043static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004044 QualType T,
4045 const InitializedEntity &Entity,
4046 ExprResult CurInit,
4047 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004048 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004049 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004050 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004051 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004052 Class = cast<CXXRecordDecl>(Record->getDecl());
4053 if (!Class)
4054 return move(CurInit);
4055
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004056 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004057 // When certain criteria are met, an implementation is allowed to
4058 // omit the copy/move construction of a class object, even if the
4059 // copy/move constructor and/or destructor for the object have
4060 // side effects. [...]
4061 // - when a temporary class object that has not been bound to a
4062 // reference (12.2) would be copied/moved to a class object
4063 // with the same cv-unqualified type, the copy/move operation
4064 // can be omitted by constructing the temporary object
4065 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004066 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004067 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004068 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004069 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004070 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004071 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004072 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004073 switch (Entity.getKind()) {
4074 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004075 Loc = Entity.getReturnLoc();
4076 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004077
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004078 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004079 Loc = Entity.getThrowLoc();
4080 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004081
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004082 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004083 Loc = Entity.getDecl()->getLocation();
4084 break;
4085
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004086 case InitializedEntity::EK_ArrayElement:
4087 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004088 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004089 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00004090 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004091 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004092 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004093 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004094 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004095 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00004096 Loc = CurInitExpr->getLocStart();
4097 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004098 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004099
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004100 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004101 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4102 return move(CurInit);
4103
Douglas Gregorcc15f012011-01-21 19:38:21 +00004104 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004105 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00004106 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00004107 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004108 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00004109 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004110 // C++0x [dcl.init]p16, second bullet to class types, this
4111 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00004112 CXXConstructorDecl *Constructor = 0;
4113
4114 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00004115 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00004116 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00004117 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004118 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00004119 continue;
4120
4121 DeclAccessPair FoundDecl
4122 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4123 S.AddOverloadCandidate(Constructor, FoundDecl,
4124 &CurInitExpr, 1, CandidateSet);
4125 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004126 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00004127
4128 // Handle constructor templates.
4129 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4130 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004131 continue;
John McCall9aa472c2010-03-19 07:35:19 +00004132
Douglas Gregor6493cc52010-11-08 17:16:59 +00004133 Constructor = cast<CXXConstructorDecl>(
4134 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00004135 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00004136 continue;
4137
4138 // FIXME: Do we need to limit this to copy-constructor-like
4139 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00004140 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00004141 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4142 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4143 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00004144 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004145
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004146 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4147
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004148 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004149 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004150 case OR_Success:
4151 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004153 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004154 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4155 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4156 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004157 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004158 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004159 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004160 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004161 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004162 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004163
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004164 case OR_Ambiguous:
4165 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004166 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004167 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004168 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004169 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004170
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004171 case OR_Deleted:
4172 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004173 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004174 << CurInitExpr->getSourceRange();
4175 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004176 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004177 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004178 }
4179
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004180 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004181 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004182 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004183
Anders Carlsson9a68a672010-04-21 18:47:17 +00004184 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004185 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004186
4187 if (IsExtraneousCopy) {
4188 // If this is a totally extraneous copy for C++03 reference
4189 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004190 // expression. We don't generate an (elided) copy operation here
4191 // because doing so would require us to pass down a flag to avoid
4192 // infinite recursion, where each step adds another extraneous,
4193 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004194
Douglas Gregor2559a702010-04-18 07:57:34 +00004195 // Instantiate the default arguments of any extra parameters in
4196 // the selected copy constructor, as if we were going to create a
4197 // proper call to the copy constructor.
4198 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4199 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4200 if (S.RequireCompleteType(Loc, Parm->getType(),
4201 S.PDiag(diag::err_call_incomplete_argument)))
4202 break;
4203
4204 // Build the default argument expression; we don't actually care
4205 // if this succeeds or not, because this routine will complain
4206 // if there was a problem.
4207 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4208 }
4209
Douglas Gregor523d46a2010-04-18 07:40:54 +00004210 return S.Owned(CurInitExpr);
4211 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004212
Chandler Carruth25ca4212011-02-25 19:41:05 +00004213 S.MarkDeclarationReferenced(Loc, Constructor);
4214
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004215 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004216 // constructor call (we might have derived-to-base conversions, or
4217 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004218 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004219 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004220 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004221
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004222 // Actually perform the constructor call.
4223 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004224 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004225 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004226 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004227 CXXConstructExpr::CK_Complete,
4228 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004229
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004230 // If we're supposed to bind temporaries, do so.
4231 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4232 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4233 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004234}
Douglas Gregor20093b42009-12-09 23:02:17 +00004235
Douglas Gregora41a8c52010-04-22 00:20:18 +00004236void InitializationSequence::PrintInitLocationNote(Sema &S,
4237 const InitializedEntity &Entity) {
4238 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4239 if (Entity.getDecl()->getLocation().isInvalid())
4240 return;
4241
4242 if (Entity.getDecl()->getDeclName())
4243 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4244 << Entity.getDecl()->getDeclName();
4245 else
4246 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4247 }
4248}
4249
Sebastian Redl3b802322011-07-14 19:07:55 +00004250static bool isReferenceBinding(const InitializationSequence::Step &s) {
4251 return s.Kind == InitializationSequence::SK_BindReference ||
4252 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4253}
4254
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004255ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004256InitializationSequence::Perform(Sema &S,
4257 const InitializedEntity &Entity,
4258 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004259 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004260 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004261 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004262 unsigned NumArgs = Args.size();
4263 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004264 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004265 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004266
Sebastian Redl7491c492011-06-05 13:59:11 +00004267 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004268 // If the declaration is a non-dependent, incomplete array type
4269 // that has an initializer, then its type will be completed once
4270 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004271 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004272 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004273 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004274 if (const IncompleteArrayType *ArrayT
4275 = S.Context.getAsIncompleteArrayType(DeclType)) {
4276 // FIXME: We don't currently have the ability to accurately
4277 // compute the length of an initializer list without
4278 // performing full type-checking of the initializer list
4279 // (since we have to determine where braces are implicitly
4280 // introduced and such). So, we fall back to making the array
4281 // type a dependently-sized array type with no specified
4282 // bound.
4283 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4284 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004285
Douglas Gregord87b61f2009-12-10 17:56:55 +00004286 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004287 if (DeclaratorDecl *DD = Entity.getDecl()) {
4288 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4289 TypeLoc TL = TInfo->getTypeLoc();
4290 if (IncompleteArrayTypeLoc *ArrayLoc
4291 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4292 Brackets = ArrayLoc->getBracketsRange();
4293 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004294 }
4295
4296 *ResultType
4297 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4298 /*NumElts=*/0,
4299 ArrayT->getSizeModifier(),
4300 ArrayT->getIndexTypeCVRQualifiers(),
4301 Brackets);
4302 }
4303
4304 }
4305 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004306 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4307 Kind.isExplicitCast());
4308 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004309 }
4310
Sebastian Redl7491c492011-06-05 13:59:11 +00004311 // No steps means no initialization.
4312 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004313 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314
Douglas Gregord6542d82009-12-22 15:35:07 +00004315 QualType DestType = Entity.getType().getNonReferenceType();
4316 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004317 // the same as Entity.getDecl()->getType() in cases involving type merging,
4318 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004319 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004320 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004321 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004322
John McCall60d7b3a2010-08-24 06:29:42 +00004323 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004324
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004325 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004326 // grab the only argument out the Args and place it into the "current"
4327 // initializer.
4328 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004329 case SK_ResolveAddressOfOverloadedFunction:
4330 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004331 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004332 case SK_CastDerivedToBaseLValue:
4333 case SK_BindReference:
4334 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004335 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004336 case SK_UserConversion:
4337 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004338 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004339 case SK_QualificationConversionRValue:
4340 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004341 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004342 case SK_ListInitialization:
4343 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004344 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004345 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004346 case SK_ArrayInit:
4347 case SK_PassByIndirectCopyRestore:
4348 case SK_PassByIndirectRestore:
4349 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004350 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004351 CurInit = Args.get()[0];
4352 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004353
4354 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004355 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4356 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4357 if (CurInit.isInvalid())
4358 return ExprError();
4359 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004360 break;
John McCallf6a16482010-12-04 03:47:34 +00004361 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004362
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004363 case SK_ConstructorInitialization:
4364 case SK_ZeroInitialization:
4365 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004366 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004367
4368 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004369 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004370 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004371 for (step_iterator Step = step_begin(), StepEnd = step_end();
4372 Step != StepEnd; ++Step) {
4373 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004374 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004375
John Wiegley429bb272011-04-08 18:41:53 +00004376 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004377
Douglas Gregor20093b42009-12-09 23:02:17 +00004378 switch (Step->Kind) {
4379 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004380 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004381 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004382 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004383 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004384 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004385 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004386 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004387 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004388
Douglas Gregor20093b42009-12-09 23:02:17 +00004389 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004390 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004391 case SK_CastDerivedToBaseLValue: {
4392 // We have a derived-to-base cast that produces either an rvalue or an
4393 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004394
John McCallf871d0c2010-08-07 06:22:56 +00004395 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004396
Douglas Gregor20093b42009-12-09 23:02:17 +00004397 // Casts to inaccessible base classes are allowed with C-style casts.
4398 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4399 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004400 CurInit.get()->getLocStart(),
4401 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004402 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004403 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004404
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004405 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4406 QualType T = SourceType;
4407 if (const PointerType *Pointer = T->getAs<PointerType>())
4408 T = Pointer->getPointeeType();
4409 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004410 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004411 cast<CXXRecordDecl>(RecordTy->getDecl()));
4412 }
4413
John McCall5baba9d2010-08-25 10:28:54 +00004414 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004415 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004416 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004417 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004418 VK_XValue :
4419 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004420 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4421 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004422 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004423 CurInit.get(),
4424 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004425 break;
4426 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004427
Douglas Gregor20093b42009-12-09 23:02:17 +00004428 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004429 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004430 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4431 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004432 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004433 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004434 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004435 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004436 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004437 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004438
John Wiegley429bb272011-04-08 18:41:53 +00004439 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004440 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004441 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4442 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004443 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004444 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004445 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004446 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004447
Douglas Gregor20093b42009-12-09 23:02:17 +00004448 // Reference binding does not have any corresponding ASTs.
4449
4450 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004451 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004452 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004453
Douglas Gregor20093b42009-12-09 23:02:17 +00004454 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004455
Douglas Gregor20093b42009-12-09 23:02:17 +00004456 case SK_BindReferenceToTemporary:
4457 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004458 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004459 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004460
Douglas Gregor03e80032011-06-21 17:03:29 +00004461 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004462 CurInit = new (S.Context) MaterializeTemporaryExpr(
4463 Entity.getType().getNonReferenceType(),
4464 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004465 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004466
4467 // If we're binding to an Objective-C object that has lifetime, we
4468 // need cleanups.
4469 if (S.getLangOptions().ObjCAutoRefCount &&
4470 CurInit.get()->getType()->isObjCLifetimeType())
4471 S.ExprNeedsCleanups = true;
4472
Douglas Gregor20093b42009-12-09 23:02:17 +00004473 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004474
Douglas Gregor523d46a2010-04-18 07:40:54 +00004475 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004476 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004477 /*IsExtraneousCopy=*/true);
4478 break;
4479
Douglas Gregor20093b42009-12-09 23:02:17 +00004480 case SK_UserConversion: {
4481 // We have a user-defined conversion that invokes either a constructor
4482 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004483 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004484 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004485 FunctionDecl *Fn = Step->Function.Function;
4486 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004487 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004488 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00004489 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004490 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004491 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004492 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004493 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004494
Douglas Gregor20093b42009-12-09 23:02:17 +00004495 // Determine the arguments required to actually perform the constructor
4496 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004497 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004498 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004499 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004500 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004501 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004502
Douglas Gregor20093b42009-12-09 23:02:17 +00004503 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004504 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004505 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004506 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004507 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004508 CXXConstructExpr::CK_Complete,
4509 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004510 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004511 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004512
Anders Carlsson9a68a672010-04-21 18:47:17 +00004513 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004514 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004515 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004516
John McCall2de56d12010-08-25 11:45:40 +00004517 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004518 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4519 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4520 S.IsDerivedFrom(SourceType, Class))
4521 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004522
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004523 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004524 } else {
4525 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004526 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00004527 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004528 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004529 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004530
4531 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004532 // derived-to-base conversion? I believe the answer is "no", because
4533 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004534 ExprResult CurInitExprRes =
4535 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4536 FoundFn, Conversion);
4537 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004538 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004539 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540
Douglas Gregor20093b42009-12-09 23:02:17 +00004541 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004542 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
4543 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00004544 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004545 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004546
John McCall2de56d12010-08-25 11:45:40 +00004547 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004548
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004549 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004551
Sebastian Redl3b802322011-07-14 19:07:55 +00004552 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004553 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004554 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004555 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004556 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004557 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004558 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004559 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004560 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004561 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004562 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4563 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004564 }
4565 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004566
John McCallf871d0c2010-08-07 06:22:56 +00004567 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004568 CurInit.get()->getType(),
4569 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00004570 CurInit.get()->getValueKind()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004571
Douglas Gregor2f599792010-04-02 18:24:57 +00004572 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004573 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4574 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004575
Douglas Gregor20093b42009-12-09 23:02:17 +00004576 break;
4577 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004578
Douglas Gregor20093b42009-12-09 23:02:17 +00004579 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004580 case SK_QualificationConversionXValue:
4581 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004582 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004583 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004584 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004585 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004586 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004587 VK_XValue :
4588 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004589 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004590 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004591 }
4592
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004593 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004594 Sema::CheckedConversionKind CCK
4595 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4596 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4597 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4598 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004599 ExprResult CurInitExprRes =
4600 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004601 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004602 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004603 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004604 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004605 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004606 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004607
Douglas Gregord87b61f2009-12-10 17:56:55 +00004608 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004609 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004610 QualType Ty = Step->Type;
Sebastian Redl14b0c192011-09-24 17:48:00 +00004611 InitListChecker PerformInitList(S, Entity, InitList,
4612 ResultType ? *ResultType : Ty, /*VerifyOnly=*/false);
4613 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00004614 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004615
4616 CurInit.release();
Sebastian Redl14b0c192011-09-24 17:48:00 +00004617 CurInit = S.Owned(PerformInitList.getFullyStructuredList());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004618 break;
4619 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004620
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004621 case SK_ListConstructorCall:
4622 assert(false && "List constructor calls not yet supported.");
4623
Douglas Gregor51c56d62009-12-14 20:49:26 +00004624 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004625 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004626 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004627 = cast<CXXConstructorDecl>(Step->Function.Function);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004628 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004629
Douglas Gregor51c56d62009-12-14 20:49:26 +00004630 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004631 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004632 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4633 ? Kind.getEqualLoc()
4634 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004635
4636 if (Kind.getKind() == InitializationKind::IK_Default) {
4637 // Force even a trivial, implicit default constructor to be
4638 // semantically checked. We do this explicitly because we don't build
4639 // the definition for completely trivial constructors.
4640 CXXRecordDecl *ClassDecl = Constructor->getParent();
4641 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004642 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004643 ClassDecl->hasTrivialDefaultConstructor() &&
4644 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004645 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4646 }
4647
Douglas Gregor51c56d62009-12-14 20:49:26 +00004648 // Determine the arguments required to actually perform the constructor
4649 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004650 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004651 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004652 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004653
4654
Douglas Gregor91be6f52010-03-02 17:18:33 +00004655 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004656 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004657 (Kind.getKind() == InitializationKind::IK_Direct ||
4658 Kind.getKind() == InitializationKind::IK_Value)) {
4659 // An explicitly-constructed temporary, e.g., X(1, 2).
4660 unsigned NumExprs = ConstructorArgs.size();
4661 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004662 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004663 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004664
Douglas Gregorab6677e2010-09-08 00:15:04 +00004665 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4666 if (!TSInfo)
4667 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004668
Douglas Gregor91be6f52010-03-02 17:18:33 +00004669 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4670 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004671 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004672 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004673 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004674 Kind.getParenRange(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004675 HadMultipleCandidates,
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004676 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004677 } else {
4678 CXXConstructExpr::ConstructionKind ConstructKind =
4679 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004680
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004681 if (Entity.getKind() == InitializedEntity::EK_Base) {
4682 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004683 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004684 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004685 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004686 ConstructKind = CXXConstructExpr::CK_Delegating;
4687 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004688
Chandler Carruth428edaf2010-10-25 08:47:36 +00004689 // Only get the parenthesis range if it is a direct construction.
4690 SourceRange parenRange =
4691 Kind.getKind() == InitializationKind::IK_Direct ?
4692 Kind.getParenRange() : SourceRange();
4693
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004694 // If the entity allows NRVO, mark the construction as elidable
4695 // unconditionally.
4696 if (Entity.allowsNRVO())
4697 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4698 Constructor, /*Elidable=*/true,
4699 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004700 HadMultipleCandidates,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004701 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004702 ConstructKind,
4703 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004704 else
4705 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004706 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004707 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004708 HadMultipleCandidates,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004709 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004710 ConstructKind,
4711 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004712 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004713 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004714 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004715
4716 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004717 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004718 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004719 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004720
Douglas Gregor2f599792010-04-02 18:24:57 +00004721 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004722 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004723
Douglas Gregor51c56d62009-12-14 20:49:26 +00004724 break;
4725 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004726
Douglas Gregor71d17402009-12-15 00:01:57 +00004727 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004728 step_iterator NextStep = Step;
4729 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004730 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004731 NextStep->Kind == SK_ConstructorInitialization) {
4732 // The need for zero-initialization is recorded directly into
4733 // the call to the object's constructor within the next step.
4734 ConstructorInitRequiresZeroInit = true;
4735 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4736 S.getLangOptions().CPlusPlus &&
4737 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004738 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4739 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004740 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004741 Kind.getRange().getBegin());
4742
4743 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4744 TSInfo->getType().getNonLValueExprType(S.Context),
4745 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004746 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004747 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004748 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004749 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004750 break;
4751 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004752
4753 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004754 QualType SourceType = CurInit.get()->getType();
4755 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004756 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004757 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4758 if (Result.isInvalid())
4759 return ExprError();
4760 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004761
4762 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004763 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004764 if (ConvTy != Sema::Compatible &&
4765 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004766 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004767 == Sema::Compatible)
4768 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004769 if (CurInitExprRes.isInvalid())
4770 return ExprError();
4771 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004772
Douglas Gregora41a8c52010-04-22 00:20:18 +00004773 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004774 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4775 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004776 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004777 getAssignmentAction(Entity),
4778 &Complained)) {
4779 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004780 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004781 } else if (Complained)
4782 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004783 break;
4784 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004785
4786 case SK_StringInit: {
4787 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004788 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004789 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004790 break;
4791 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004792
4793 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004794 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004795 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00004796 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00004797 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004798
4799 case SK_ArrayInit:
4800 // Okay: we checked everything before creating this step. Note that
4801 // this is a GNU extension.
4802 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004803 << Step->Type << CurInit.get()->getType()
4804 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004805
4806 // If the destination type is an incomplete array type, update the
4807 // type accordingly.
4808 if (ResultType) {
4809 if (const IncompleteArrayType *IncompleteDest
4810 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4811 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004812 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004813 *ResultType = S.Context.getConstantArrayType(
4814 IncompleteDest->getElementType(),
4815 ConstantSource->getSize(),
4816 ArrayType::Normal, 0);
4817 }
4818 }
4819 }
John McCallf85e1932011-06-15 23:02:42 +00004820 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004821
John McCallf85e1932011-06-15 23:02:42 +00004822 case SK_PassByIndirectCopyRestore:
4823 case SK_PassByIndirectRestore:
4824 checkIndirectCopyRestoreSource(S, CurInit.get());
4825 CurInit = S.Owned(new (S.Context)
4826 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4827 Step->Kind == SK_PassByIndirectCopyRestore));
4828 break;
4829
4830 case SK_ProduceObjCObject:
4831 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00004832 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00004833 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004834 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004835 }
4836 }
John McCall15d7d122010-11-11 03:21:53 +00004837
4838 // Diagnose non-fatal problems with the completed initialization.
4839 if (Entity.getKind() == InitializedEntity::EK_Member &&
4840 cast<FieldDecl>(Entity.getDecl())->isBitField())
4841 S.CheckBitFieldInitialization(Kind.getLocation(),
4842 cast<FieldDecl>(Entity.getDecl()),
4843 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004844
Douglas Gregor20093b42009-12-09 23:02:17 +00004845 return move(CurInit);
4846}
4847
4848//===----------------------------------------------------------------------===//
4849// Diagnose initialization failures
4850//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004851bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004852 const InitializedEntity &Entity,
4853 const InitializationKind &Kind,
4854 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004855 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004856 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004857
Douglas Gregord6542d82009-12-22 15:35:07 +00004858 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004859 switch (Failure) {
4860 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004861 // FIXME: Customize for the initialized entity?
4862 if (NumArgs == 0)
4863 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4864 << DestType.getNonReferenceType();
4865 else // FIXME: diagnostic below could be better!
4866 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4867 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004868 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004869
Douglas Gregor20093b42009-12-09 23:02:17 +00004870 case FK_ArrayNeedsInitList:
4871 case FK_ArrayNeedsInitListOrStringLiteral:
4872 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4873 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4874 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004875
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004876 case FK_ArrayTypeMismatch:
4877 case FK_NonConstantArrayInit:
4878 S.Diag(Kind.getLocation(),
4879 (Failure == FK_ArrayTypeMismatch
4880 ? diag::err_array_init_different_type
4881 : diag::err_array_init_non_constant_array))
4882 << DestType.getNonReferenceType()
4883 << Args[0]->getType()
4884 << Args[0]->getSourceRange();
4885 break;
4886
John McCall6bb80172010-03-30 21:47:33 +00004887 case FK_AddressOfOverloadFailed: {
4888 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004889 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004890 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004891 true,
4892 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004893 break;
John McCall6bb80172010-03-30 21:47:33 +00004894 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004895
Douglas Gregor20093b42009-12-09 23:02:17 +00004896 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004897 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004898 switch (FailedOverloadResult) {
4899 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004900 if (Failure == FK_UserConversionOverloadFailed)
4901 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4902 << Args[0]->getType() << DestType
4903 << Args[0]->getSourceRange();
4904 else
4905 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4906 << DestType << Args[0]->getType()
4907 << Args[0]->getSourceRange();
4908
John McCall120d63c2010-08-24 20:38:10 +00004909 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004910 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004911
Douglas Gregor20093b42009-12-09 23:02:17 +00004912 case OR_No_Viable_Function:
4913 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4914 << Args[0]->getType() << DestType.getNonReferenceType()
4915 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004916 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004917 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004918
Douglas Gregor20093b42009-12-09 23:02:17 +00004919 case OR_Deleted: {
4920 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4921 << Args[0]->getType() << DestType.getNonReferenceType()
4922 << Args[0]->getSourceRange();
4923 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004924 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004925 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4926 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004927 if (Ovl == OR_Deleted) {
4928 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004929 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004930 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004931 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004932 }
4933 break;
4934 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004935
Douglas Gregor20093b42009-12-09 23:02:17 +00004936 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004937 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004938 break;
4939 }
4940 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004941
Douglas Gregor20093b42009-12-09 23:02:17 +00004942 case FK_NonConstLValueReferenceBindingToTemporary:
4943 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004944 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004945 Failure == FK_NonConstLValueReferenceBindingToTemporary
4946 ? diag::err_lvalue_reference_bind_to_temporary
4947 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004948 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004949 << DestType.getNonReferenceType()
4950 << Args[0]->getType()
4951 << Args[0]->getSourceRange();
4952 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004953
Douglas Gregor20093b42009-12-09 23:02:17 +00004954 case FK_RValueReferenceBindingToLValue:
4955 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004956 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004957 << Args[0]->getSourceRange();
4958 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004959
Douglas Gregor20093b42009-12-09 23:02:17 +00004960 case FK_ReferenceInitDropsQualifiers:
4961 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4962 << DestType.getNonReferenceType()
4963 << Args[0]->getType()
4964 << Args[0]->getSourceRange();
4965 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004966
Douglas Gregor20093b42009-12-09 23:02:17 +00004967 case FK_ReferenceInitFailed:
4968 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4969 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004970 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004971 << Args[0]->getType()
4972 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004973 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4974 Args[0]->getType()->isObjCObjectPointerType())
4975 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004976 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004977
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004978 case FK_ConversionFailed: {
4979 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004980 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4981 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004982 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004983 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004984 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004985 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004986 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4987 Args[0]->getType()->isObjCObjectPointerType())
4988 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004989 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004990 }
John Wiegley429bb272011-04-08 18:41:53 +00004991
4992 case FK_ConversionFromPropertyFailed:
4993 // No-op. This error has already been reported.
4994 break;
4995
Douglas Gregord87b61f2009-12-10 17:56:55 +00004996 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004997 SourceRange R;
4998
4999 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005000 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005001 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005002 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005003 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005004
Douglas Gregor19311e72010-09-08 21:40:08 +00005005 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5006 if (Kind.isCStyleOrFunctionalCast())
5007 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5008 << R;
5009 else
5010 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5011 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005012 break;
5013 }
5014
5015 case FK_ReferenceBindingToInitList:
5016 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5017 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5018 break;
5019
5020 case FK_InitListBadDestinationType:
5021 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5022 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5023 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005024
Douglas Gregor51c56d62009-12-14 20:49:26 +00005025 case FK_ConstructorOverloadFailed: {
5026 SourceRange ArgsRange;
5027 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005028 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005029 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005030
Douglas Gregor51c56d62009-12-14 20:49:26 +00005031 // FIXME: Using "DestType" for the entity we're printing is probably
5032 // bad.
5033 switch (FailedOverloadResult) {
5034 case OR_Ambiguous:
5035 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5036 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005037 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5038 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005039 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005040
Douglas Gregor51c56d62009-12-14 20:49:26 +00005041 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005042 if (Kind.getKind() == InitializationKind::IK_Default &&
5043 (Entity.getKind() == InitializedEntity::EK_Base ||
5044 Entity.getKind() == InitializedEntity::EK_Member) &&
5045 isa<CXXConstructorDecl>(S.CurContext)) {
5046 // This is implicit default initialization of a member or
5047 // base within a constructor. If no viable function was
5048 // found, notify the user that she needs to explicitly
5049 // initialize this base/member.
5050 CXXConstructorDecl *Constructor
5051 = cast<CXXConstructorDecl>(S.CurContext);
5052 if (Entity.getKind() == InitializedEntity::EK_Base) {
5053 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5054 << Constructor->isImplicit()
5055 << S.Context.getTypeDeclType(Constructor->getParent())
5056 << /*base=*/0
5057 << Entity.getType();
5058
5059 RecordDecl *BaseDecl
5060 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5061 ->getDecl();
5062 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5063 << S.Context.getTagDeclType(BaseDecl);
5064 } else {
5065 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5066 << Constructor->isImplicit()
5067 << S.Context.getTypeDeclType(Constructor->getParent())
5068 << /*member=*/1
5069 << Entity.getName();
5070 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5071
5072 if (const RecordType *Record
5073 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005074 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005075 diag::note_previous_decl)
5076 << S.Context.getTagDeclType(Record->getDecl());
5077 }
5078 break;
5079 }
5080
Douglas Gregor51c56d62009-12-14 20:49:26 +00005081 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5082 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005083 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005084 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005085
Douglas Gregor51c56d62009-12-14 20:49:26 +00005086 case OR_Deleted: {
5087 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5088 << true << DestType << ArgsRange;
5089 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005090 OverloadingResult Ovl
5091 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005092 if (Ovl == OR_Deleted) {
5093 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005094 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005095 } else {
5096 llvm_unreachable("Inconsistent overload resolution?");
5097 }
5098 break;
5099 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005100
Douglas Gregor51c56d62009-12-14 20:49:26 +00005101 case OR_Success:
5102 llvm_unreachable("Conversion did not fail!");
5103 break;
5104 }
5105 break;
5106 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005107
Douglas Gregor99a2e602009-12-16 01:38:02 +00005108 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005109 if (Entity.getKind() == InitializedEntity::EK_Member &&
5110 isa<CXXConstructorDecl>(S.CurContext)) {
5111 // This is implicit default-initialization of a const member in
5112 // a constructor. Complain that it needs to be explicitly
5113 // initialized.
5114 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5115 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5116 << Constructor->isImplicit()
5117 << S.Context.getTypeDeclType(Constructor->getParent())
5118 << /*const=*/1
5119 << Entity.getName();
5120 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5121 << Entity.getName();
5122 } else {
5123 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5124 << DestType << (bool)DestType->getAs<RecordType>();
5125 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005126 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005127
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005128 case FK_Incomplete:
5129 S.RequireCompleteType(Kind.getLocation(), DestType,
5130 diag::err_init_incomplete_type);
5131 break;
5132
Sebastian Redl14b0c192011-09-24 17:48:00 +00005133 case FK_ListInitializationFailed: {
5134 // Run the init list checker again to emit diagnostics.
5135 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5136 QualType DestType = Entity.getType();
5137 InitListChecker DiagnoseInitList(S, Entity, InitList,
5138 DestType, /*VerifyOnly=*/false);
5139 assert(DiagnoseInitList.HadError() &&
5140 "Inconsistent init list check result.");
5141 break;
5142 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005143 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005144
Douglas Gregora41a8c52010-04-22 00:20:18 +00005145 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005146 return true;
5147}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005148
Chris Lattner5f9e2722011-07-23 10:55:15 +00005149void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005150 switch (SequenceKind) {
5151 case FailedSequence: {
5152 OS << "Failed sequence: ";
5153 switch (Failure) {
5154 case FK_TooManyInitsForReference:
5155 OS << "too many initializers for reference";
5156 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005157
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005158 case FK_ArrayNeedsInitList:
5159 OS << "array requires initializer list";
5160 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005161
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005162 case FK_ArrayNeedsInitListOrStringLiteral:
5163 OS << "array requires initializer list or string literal";
5164 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005165
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005166 case FK_ArrayTypeMismatch:
5167 OS << "array type mismatch";
5168 break;
5169
5170 case FK_NonConstantArrayInit:
5171 OS << "non-constant array initializer";
5172 break;
5173
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005174 case FK_AddressOfOverloadFailed:
5175 OS << "address of overloaded function failed";
5176 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005177
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005178 case FK_ReferenceInitOverloadFailed:
5179 OS << "overload resolution for reference initialization failed";
5180 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005181
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005182 case FK_NonConstLValueReferenceBindingToTemporary:
5183 OS << "non-const lvalue reference bound to temporary";
5184 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005185
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005186 case FK_NonConstLValueReferenceBindingToUnrelated:
5187 OS << "non-const lvalue reference bound to unrelated type";
5188 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005189
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005190 case FK_RValueReferenceBindingToLValue:
5191 OS << "rvalue reference bound to an lvalue";
5192 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005193
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005194 case FK_ReferenceInitDropsQualifiers:
5195 OS << "reference initialization drops qualifiers";
5196 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005197
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005198 case FK_ReferenceInitFailed:
5199 OS << "reference initialization failed";
5200 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005201
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005202 case FK_ConversionFailed:
5203 OS << "conversion failed";
5204 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005205
John Wiegley429bb272011-04-08 18:41:53 +00005206 case FK_ConversionFromPropertyFailed:
5207 OS << "conversion from property failed";
5208 break;
5209
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005210 case FK_TooManyInitsForScalar:
5211 OS << "too many initializers for scalar";
5212 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005213
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005214 case FK_ReferenceBindingToInitList:
5215 OS << "referencing binding to initializer list";
5216 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005217
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005218 case FK_InitListBadDestinationType:
5219 OS << "initializer list for non-aggregate, non-scalar type";
5220 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005221
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005222 case FK_UserConversionOverloadFailed:
5223 OS << "overloading failed for user-defined conversion";
5224 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005225
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005226 case FK_ConstructorOverloadFailed:
5227 OS << "constructor overloading failed";
5228 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005229
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005230 case FK_DefaultInitOfConst:
5231 OS << "default initialization of a const variable";
5232 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005233
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005234 case FK_Incomplete:
5235 OS << "initialization of incomplete type";
5236 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005237
5238 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005239 OS << "list initialization checker failure";
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005240 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005241 OS << '\n';
5242 return;
5243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005244
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005245 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005246 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005247 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005248
Sebastian Redl7491c492011-06-05 13:59:11 +00005249 case NormalSequence:
5250 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005251 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005252 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005253
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005254 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5255 if (S != step_begin()) {
5256 OS << " -> ";
5257 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005258
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005259 switch (S->Kind) {
5260 case SK_ResolveAddressOfOverloadedFunction:
5261 OS << "resolve address of overloaded function";
5262 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005263
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005264 case SK_CastDerivedToBaseRValue:
5265 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5266 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005267
Sebastian Redl906082e2010-07-20 04:20:21 +00005268 case SK_CastDerivedToBaseXValue:
5269 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5270 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005271
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005272 case SK_CastDerivedToBaseLValue:
5273 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5274 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005275
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005276 case SK_BindReference:
5277 OS << "bind reference to lvalue";
5278 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005279
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005280 case SK_BindReferenceToTemporary:
5281 OS << "bind reference to a temporary";
5282 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005283
Douglas Gregor523d46a2010-04-18 07:40:54 +00005284 case SK_ExtraneousCopyToTemporary:
5285 OS << "extraneous C++03 copy to temporary";
5286 break;
5287
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005288 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00005289 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005290 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005291
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005292 case SK_QualificationConversionRValue:
5293 OS << "qualification conversion (rvalue)";
5294
Sebastian Redl906082e2010-07-20 04:20:21 +00005295 case SK_QualificationConversionXValue:
5296 OS << "qualification conversion (xvalue)";
5297
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005298 case SK_QualificationConversionLValue:
5299 OS << "qualification conversion (lvalue)";
5300 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005301
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005302 case SK_ConversionSequence:
5303 OS << "implicit conversion sequence (";
5304 S->ICS->DebugPrint(); // FIXME: use OS
5305 OS << ")";
5306 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005307
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005308 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005309 OS << "list aggregate initialization";
5310 break;
5311
5312 case SK_ListConstructorCall:
5313 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005314 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005315
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005316 case SK_ConstructorInitialization:
5317 OS << "constructor initialization";
5318 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005319
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005320 case SK_ZeroInitialization:
5321 OS << "zero initialization";
5322 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005323
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005324 case SK_CAssignment:
5325 OS << "C assignment";
5326 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005327
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005328 case SK_StringInit:
5329 OS << "string initialization";
5330 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005331
5332 case SK_ObjCObjectConversion:
5333 OS << "Objective-C object conversion";
5334 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005335
5336 case SK_ArrayInit:
5337 OS << "array initialization";
5338 break;
John McCallf85e1932011-06-15 23:02:42 +00005339
5340 case SK_PassByIndirectCopyRestore:
5341 OS << "pass by indirect copy and restore";
5342 break;
5343
5344 case SK_PassByIndirectRestore:
5345 OS << "pass by indirect restore";
5346 break;
5347
5348 case SK_ProduceObjCObject:
5349 OS << "Objective-C object retension";
5350 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005351 }
5352 }
5353}
5354
5355void InitializationSequence::dump() const {
5356 dump(llvm::errs());
5357}
5358
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005359static void DiagnoseNarrowingInInitList(
5360 Sema& S, QualType EntityType, const Expr *InitE,
5361 bool Constant, const APValue &ConstantValue) {
5362 if (Constant) {
5363 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005364 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005365 ? diag::err_init_list_constant_narrowing
5366 : diag::warn_init_list_constant_narrowing)
5367 << InitE->getSourceRange()
5368 << ConstantValue
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005369 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005370 } else
5371 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005372 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005373 ? diag::err_init_list_variable_narrowing
5374 : diag::warn_init_list_variable_narrowing)
5375 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005376 << InitE->getType().getLocalUnqualifiedType()
5377 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005378
5379 llvm::SmallString<128> StaticCast;
5380 llvm::raw_svector_ostream OS(StaticCast);
5381 OS << "static_cast<";
5382 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5383 // It's important to use the typedef's name if there is one so that the
5384 // fixit doesn't break code using types like int64_t.
5385 //
5386 // FIXME: This will break if the typedef requires qualification. But
5387 // getQualifiedNameAsString() includes non-machine-parsable components.
5388 OS << TT->getDecl();
5389 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5390 OS << BT->getName(S.getLangOptions());
5391 else {
5392 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5393 // with a broken cast.
5394 return;
5395 }
5396 OS << ">(";
5397 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5398 << InitE->getSourceRange()
5399 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5400 << FixItHint::CreateInsertion(
5401 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5402}
5403
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005404//===----------------------------------------------------------------------===//
5405// Initialization helper functions
5406//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005407bool
5408Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5409 ExprResult Init) {
5410 if (Init.isInvalid())
5411 return false;
5412
5413 Expr *InitE = Init.get();
5414 assert(InitE && "No initialization expression");
5415
5416 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5417 SourceLocation());
5418 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005419 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005420}
5421
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005422ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005423Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5424 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005425 ExprResult Init,
5426 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005427 if (Init.isInvalid())
5428 return ExprError();
5429
John McCall15d7d122010-11-11 03:21:53 +00005430 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005431 assert(InitE && "No initialization expression?");
5432
5433 if (EqualLoc.isInvalid())
5434 EqualLoc = InitE->getLocStart();
5435
5436 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5437 EqualLoc);
5438 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5439 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005440
5441 bool Constant = false;
5442 APValue Result;
5443 if (TopLevelOfInitList &&
5444 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5445 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5446 Constant, Result);
5447 }
John McCallf312b1e2010-08-26 23:41:50 +00005448 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005449}