blob: 2f9b33edeb81e9e26ea771bca84ed88071cc8e81 [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"
Sebastian Redl2b916b82012-01-17 22:49:42 +000024#include "llvm/ADT/APInt.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000025#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000026#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000027#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000028using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000029
Chris Lattnerdd8e0062009-02-24 22:27:37 +000030//===----------------------------------------------------------------------===//
31// Sema Initialization Checking
32//===----------------------------------------------------------------------===//
33
John McCallce6c9b72011-02-21 07:22:22 +000034static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
35 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000036 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
37 return 0;
38
Chris Lattner8879e3b2009-02-26 23:26:43 +000039 // See if this is a string literal or @encode.
40 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner8879e3b2009-02-26 23:26:43 +000042 // Handle @encode, which is a narrow string.
43 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
44 return Init;
45
46 // Otherwise we can only handle string literals.
47 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000048 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000049
50 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000051
52 switch (SL->getKind()) {
53 case StringLiteral::Ascii:
54 case StringLiteral::UTF8:
55 // char array can be initialized with a narrow string.
56 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000057 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000058 case StringLiteral::UTF16:
59 return ElemTy->isChar16Type() ? Init : 0;
60 case StringLiteral::UTF32:
61 return ElemTy->isChar32Type() ? Init : 0;
62 case StringLiteral::Wide:
63 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
64 // correction from DR343): "An array with element type compatible with a
65 // qualified or unqualified version of wchar_t may be initialized by a wide
66 // string literal, optionally enclosed in braces."
67 if (Context.typesAreCompatible(Context.getWCharType(),
68 ElemTy.getUnqualifiedType()))
69 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000070
Douglas Gregor5cee1192011-07-27 05:40:30 +000071 return 0;
72 }
Mike Stump1eb44332009-09-09 15:08:12 +000073
Douglas Gregor5cee1192011-07-27 05:40:30 +000074 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000075}
76
John McCallce6c9b72011-02-21 07:22:22 +000077static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
78 const ArrayType *arrayType = Context.getAsArrayType(declType);
79 if (!arrayType) return 0;
80
81 return IsStringInit(init, arrayType, Context);
82}
83
John McCallfef8b342011-02-21 07:57:55 +000084static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
85 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000086 // Get the length of the string as parsed.
87 uint64_t StrLength =
88 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
89
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattnerdd8e0062009-02-24 22:27:37 +000091 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000092 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000093 // being initialized to a string literal.
94 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000095 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000096 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000097 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
98 ConstVal,
99 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000100 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000101 }
Mike Stump1eb44332009-09-09 15:08:12 +0000102
Eli Friedman8718a6a2009-05-29 18:22:49 +0000103 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000105 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000106 // the size may be smaller or larger than the string we are initializing.
107 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000108 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000109 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
110 // For Pascal strings it's OK to strip off the terminating null character,
111 // so the example below is valid:
112 //
113 // unsigned char a[2] = "\pa";
114 if (SL->isPascal())
115 StrLength--;
116 }
117
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000118 // [dcl.init.string]p2
119 if (StrLength > CAT->getSize().getZExtValue())
120 S.Diag(Str->getSourceRange().getBegin(),
121 diag::err_initializer_string_for_char_array_too_long)
122 << Str->getSourceRange();
123 } else {
124 // C99 6.7.8p14.
125 if (StrLength-1 > CAT->getSize().getZExtValue())
126 S.Diag(Str->getSourceRange().getBegin(),
127 diag::warn_initializer_string_for_char_array_too_long)
128 << Str->getSourceRange();
129 }
Mike Stump1eb44332009-09-09 15:08:12 +0000130
Eli Friedman8718a6a2009-05-29 18:22:49 +0000131 // Set the type to the actual size that we are initializing. If we have
132 // something like:
133 // char x[1] = "foo";
134 // then this will set the string literal's type to char[1].
135 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000136}
137
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000138//===----------------------------------------------------------------------===//
139// Semantic checking for initializer lists.
140//===----------------------------------------------------------------------===//
141
Douglas Gregor9e80f722009-01-29 01:05:33 +0000142/// @brief Semantic checking for initializer lists.
143///
144/// The InitListChecker class contains a set of routines that each
145/// handle the initialization of a certain kind of entity, e.g.,
146/// arrays, vectors, struct/union types, scalars, etc. The
147/// InitListChecker itself performs a recursive walk of the subobject
148/// structure of the type to be initialized, while stepping through
149/// the initializer list one element at a time. The IList and Index
150/// parameters to each of the Check* routines contain the active
151/// (syntactic) initializer list and the index into that initializer
152/// list that represents the current initializer. Each routine is
153/// responsible for moving that Index forward as it consumes elements.
154///
155/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000156/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000157/// initializer list and the index into that initializer list where we
158/// are copying initializers as we map them over to the semantic
159/// list. Once we have completed our recursive walk of the subobject
160/// structure, we will have constructed a full semantic initializer
161/// list.
162///
163/// C99 designators cause changes in the initializer list traversal,
164/// because they make the initialization "jump" into a specific
165/// subobject and then continue the initialization from that
166/// point. CheckDesignatedInitializer() recursively steps into the
167/// designated subobject and manages backing out the recursion to
168/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000169namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000170class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000171 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000172 bool hadError;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000173 bool VerifyOnly; // no diagnostics, no structure building
Sebastian Redlc2235182011-10-16 18:19:28 +0000174 bool AllowBraceElision;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000175 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
176 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000178 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000179 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000180 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000181 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000182 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000183 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000184 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000185 unsigned &StructuredIndex,
186 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000187 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000188 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000189 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000190 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000191 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000192 unsigned &StructuredIndex,
193 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000194 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000195 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000196 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000197 InitListExpr *StructuredList,
198 unsigned &StructuredIndex);
Eli Friedman0c706c22011-09-19 23:17:44 +0000199 void CheckComplexType(const InitializedEntity &Entity,
200 InitListExpr *IList, QualType DeclType,
201 unsigned &Index,
202 InitListExpr *StructuredList,
203 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000204 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000205 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000206 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000207 InitListExpr *StructuredList,
208 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000209 void CheckReferenceType(const InitializedEntity &Entity,
210 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000211 unsigned &Index,
212 InitListExpr *StructuredList,
213 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000214 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000215 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
217 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000218 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000219 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000220 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000221 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000222 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000223 unsigned &StructuredIndex,
224 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000225 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000226 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000227 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000228 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000229 InitListExpr *StructuredList,
230 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000231 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000232 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000233 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000234 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000235 RecordDecl::field_iterator *NextField,
236 llvm::APSInt *NextElementIndex,
237 unsigned &Index,
238 InitListExpr *StructuredList,
239 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000240 bool FinishSubobjectInit,
241 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000242 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
243 QualType CurrentObjectType,
244 InitListExpr *StructuredList,
245 unsigned StructuredIndex,
246 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000247 void UpdateStructuredListElement(InitListExpr *StructuredList,
248 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000249 Expr *expr);
250 int numArrayElements(QualType DeclType);
251 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000252
Douglas Gregord6d37de2009-12-22 00:05:34 +0000253 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
254 const InitializedEntity &ParentEntity,
255 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000256 void FillInValueInitializations(const InitializedEntity &Entity,
257 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000258 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
259 Expr *InitExpr, FieldDecl *Field,
260 bool TopLevelObject);
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000261 void CheckValueInitializable(const InitializedEntity &Entity);
262
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000263public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000264 InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redlc2235182011-10-16 18:19:28 +0000265 InitListExpr *IL, QualType &T, bool VerifyOnly,
266 bool AllowBraceElision);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000267 bool HadError() { return hadError; }
268
269 // @brief Retrieves the fully-structured initializer list used for
270 // semantic analysis and code generation.
271 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
272};
Chris Lattner8b419b92009-02-24 22:48:58 +0000273} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000274
Sebastian Redl3ff5c862011-10-16 18:19:20 +0000275void InitListChecker::CheckValueInitializable(const InitializedEntity &Entity) {
276 assert(VerifyOnly &&
277 "CheckValueInitializable is only inteded for verification mode.");
278
279 SourceLocation Loc;
280 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
281 true);
282 InitializationSequence InitSeq(SemaRef, Entity, Kind, 0, 0);
283 if (InitSeq.Failed())
284 hadError = true;
285}
286
Douglas Gregord6d37de2009-12-22 00:05:34 +0000287void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
288 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000289 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000290 bool &RequiresSecondPass) {
291 SourceLocation Loc = ILE->getSourceRange().getBegin();
292 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000293 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000294 = InitializedEntity::InitializeMember(Field, &ParentEntity);
295 if (Init >= NumInits || !ILE->getInit(Init)) {
296 // FIXME: We probably don't need to handle references
297 // specially here, since value-initialization of references is
298 // handled in InitializationSequence.
299 if (Field->getType()->isReferenceType()) {
300 // C++ [dcl.init.aggr]p9:
301 // If an incomplete or empty initializer-list leaves a
302 // member of reference type uninitialized, the program is
303 // ill-formed.
304 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
305 << Field->getType()
306 << ILE->getSyntacticForm()->getSourceRange();
307 SemaRef.Diag(Field->getLocation(),
308 diag::note_uninit_reference_member);
309 hadError = true;
310 return;
311 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000312
Douglas Gregord6d37de2009-12-22 00:05:34 +0000313 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
314 true);
315 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
316 if (!InitSeq) {
317 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
318 hadError = true;
319 return;
320 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000321
John McCall60d7b3a2010-08-24 06:29:42 +0000322 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000323 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000324 if (MemberInit.isInvalid()) {
325 hadError = true;
326 return;
327 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000328
Douglas Gregord6d37de2009-12-22 00:05:34 +0000329 if (hadError) {
330 // Do nothing
331 } else if (Init < NumInits) {
332 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000333 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000334 // Value-initialization requires a constructor call, so
335 // extend the initializer list to include the constructor
336 // call and make a note that we'll need to take another pass
337 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000338 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000339 RequiresSecondPass = true;
340 }
341 } else if (InitListExpr *InnerILE
342 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000343 FillInValueInitializations(MemberEntity, InnerILE,
344 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000345}
346
Douglas Gregor4c678342009-01-28 21:54:33 +0000347/// Recursively replaces NULL values within the given initializer list
348/// with expressions that perform value-initialization of the
349/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000350void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000351InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
352 InitListExpr *ILE,
353 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000354 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000355 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000356 SourceLocation Loc = ILE->getSourceRange().getBegin();
357 if (ILE->getSyntacticForm())
358 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Ted Kremenek6217b802009-07-29 21:53:49 +0000360 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000361 if (RType->getDecl()->isUnion() &&
362 ILE->getInitializedFieldInUnion())
363 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
364 Entity, ILE, RequiresSecondPass);
365 else {
366 unsigned Init = 0;
367 for (RecordDecl::field_iterator
368 Field = RType->getDecl()->field_begin(),
369 FieldEnd = RType->getDecl()->field_end();
370 Field != FieldEnd; ++Field) {
371 if (Field->isUnnamedBitfield())
372 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000373
Douglas Gregord6d37de2009-12-22 00:05:34 +0000374 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000375 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000376
377 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
378 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000379 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000380
Douglas Gregord6d37de2009-12-22 00:05:34 +0000381 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000382
Douglas Gregord6d37de2009-12-22 00:05:34 +0000383 // Only look at the first initialization of a union.
384 if (RType->getDecl()->isUnion())
385 break;
386 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000387 }
388
389 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000390 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000391
392 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000394 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000395 unsigned NumInits = ILE->getNumInits();
396 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000397 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000398 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
400 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000401 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000402 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000403 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000404 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000405 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000406 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000407 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000408 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000409 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000410
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000411
Douglas Gregor87fd7032009-02-02 17:43:21 +0000412 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000413 if (hadError)
414 return;
415
Anders Carlssond3d824d2010-01-23 04:34:47 +0000416 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
417 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000418 ElementEntity.setElementIndex(Init);
419
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000420 Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : 0);
421 if (!InitExpr && !ILE->hasArrayFiller()) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000422 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
423 true);
424 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
425 if (!InitSeq) {
426 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000427 hadError = true;
428 return;
429 }
430
John McCall60d7b3a2010-08-24 06:29:42 +0000431 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000432 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000433 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000434 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000435 return;
436 }
437
438 if (hadError) {
439 // Do nothing
440 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000441 // For arrays, just set the expression used for value-initialization
442 // of the "holes" in the array.
443 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
444 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
445 else
446 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000447 } else {
448 // For arrays, just set the expression used for value-initialization
449 // of the rest of elements and exit.
450 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
451 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
452 return;
453 }
454
Sebastian Redl7491c492011-06-05 13:59:11 +0000455 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000456 // Value-initialization requires a constructor call, so
457 // extend the initializer list to include the constructor
458 // call and make a note that we'll need to take another pass
459 // through the initializer list.
460 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
461 RequiresSecondPass = true;
462 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000463 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000464 } else if (InitListExpr *InnerILE
Argyrios Kyrtzidis21f77cd2011-10-21 23:02:22 +0000465 = dyn_cast_or_null<InitListExpr>(InitExpr))
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000466 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000467 }
468}
469
Chris Lattner68355a52009-01-29 05:10:57 +0000470
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000471InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
Sebastian Redl14b0c192011-09-24 17:48:00 +0000472 InitListExpr *IL, QualType &T,
Sebastian Redlc2235182011-10-16 18:19:28 +0000473 bool VerifyOnly, bool AllowBraceElision)
Richard Smithb6f8d282011-12-20 04:00:21 +0000474 : SemaRef(S), VerifyOnly(VerifyOnly), AllowBraceElision(AllowBraceElision) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000475 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000476
Eli Friedmanb85f7072008-05-19 19:16:24 +0000477 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000478 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000479 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000480 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000481 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000482 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000483 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000484
Sebastian Redl14b0c192011-09-24 17:48:00 +0000485 if (!hadError && !VerifyOnly) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000486 bool RequiresSecondPass = false;
487 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000488 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000489 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000490 RequiresSecondPass);
491 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000492}
493
494int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000495 // FIXME: use a proper constant
496 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000497 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000498 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000499 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
500 }
501 return maxElements;
502}
503
504int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000505 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000506 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000507 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000508 Field = structDecl->field_begin(),
509 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000510 Field != FieldEnd; ++Field) {
Douglas Gregord61db332011-10-10 17:22:13 +0000511 if (!Field->isUnnamedBitfield())
Douglas Gregor4c678342009-01-28 21:54:33 +0000512 ++InitializableMembers;
513 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000514 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000515 return std::min(InitializableMembers, 1);
516 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000517}
518
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000519void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000520 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000521 QualType T, unsigned &Index,
522 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000523 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000524 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Steve Naroff0cca7492008-05-01 22:18:59 +0000526 if (T->isArrayType())
527 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000528 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000529 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000530 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000531 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000532 else
David Blaikieb219cfc2011-09-23 05:06:16 +0000533 llvm_unreachable("CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000534
Eli Friedman402256f2008-05-25 13:49:22 +0000535 if (maxElements == 0) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000536 if (!VerifyOnly)
537 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
538 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000539 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000540 hadError = true;
541 return;
542 }
543
Douglas Gregor4c678342009-01-28 21:54:33 +0000544 // Build a structured initializer list corresponding to this subobject.
545 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000546 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
547 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000548 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
549 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000550 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000551
Douglas Gregor4c678342009-01-28 21:54:33 +0000552 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000553 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000554 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000555 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000556 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000557 StructuredSubobjectInitIndex);
Sebastian Redlc2235182011-10-16 18:19:28 +0000558
559 if (VerifyOnly) {
560 if (!AllowBraceElision && (T->isArrayType() || T->isRecordType()))
561 hadError = true;
562 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000563 StructuredSubobjectInitList->setType(T);
Douglas Gregora6457962009-03-20 00:32:56 +0000564
Sebastian Redlc2235182011-10-16 18:19:28 +0000565 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000566 // Update the structured sub-object initializer so that it's ending
567 // range corresponds with the end of the last initializer it used.
568 if (EndIndex < ParentIList->getNumInits()) {
569 SourceLocation EndLoc
570 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
571 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
572 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573
Sebastian Redlc2235182011-10-16 18:19:28 +0000574 // Complain about missing braces.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000575 if (T->isArrayType() || T->isRecordType()) {
576 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
Sebastian Redlc2235182011-10-16 18:19:28 +0000577 AllowBraceElision ? diag::warn_missing_braces :
578 diag::err_missing_braces)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000579 << StructuredSubobjectInitList->getSourceRange()
580 << FixItHint::CreateInsertion(
581 StructuredSubobjectInitList->getLocStart(), "{")
582 << FixItHint::CreateInsertion(
583 SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584 StructuredSubobjectInitList->getLocEnd()),
Sebastian Redl14b0c192011-09-24 17:48:00 +0000585 "}");
Sebastian Redlc2235182011-10-16 18:19:28 +0000586 if (!AllowBraceElision)
587 hadError = true;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000588 }
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000589 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000590}
591
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000592void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000593 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000594 unsigned &Index,
595 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000596 unsigned &StructuredIndex,
597 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000598 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Sebastian Redl14b0c192011-09-24 17:48:00 +0000599 if (!VerifyOnly) {
600 SyntacticToSemantic[IList] = StructuredList;
601 StructuredList->setSyntacticForm(IList);
602 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000603 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000604 Index, StructuredList, StructuredIndex, TopLevelObject);
Sebastian Redl14b0c192011-09-24 17:48:00 +0000605 if (!VerifyOnly) {
606 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
607 IList->setType(ExprTy);
608 StructuredList->setType(ExprTy);
609 }
Eli Friedman638e1442008-05-25 13:22:35 +0000610 if (hadError)
611 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000612
Eli Friedman638e1442008-05-25 13:22:35 +0000613 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000614 // We have leftover initializers
Sebastian Redl14b0c192011-09-24 17:48:00 +0000615 if (VerifyOnly) {
616 if (SemaRef.getLangOptions().CPlusPlus ||
617 (SemaRef.getLangOptions().OpenCL &&
618 IList->getType()->isVectorType())) {
619 hadError = true;
620 }
621 return;
622 }
623
Eli Friedmane5408582009-05-29 20:20:05 +0000624 if (StructuredIndex == 1 &&
625 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000626 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000627 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000628 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000629 hadError = true;
630 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000631 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000632 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000633 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000634 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000635 // Don't complain for incomplete types, since we'll get an error
636 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000637 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000638 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 CurrentObjectType->isArrayType()? 0 :
640 CurrentObjectType->isVectorType()? 1 :
641 CurrentObjectType->isScalarType()? 2 :
642 CurrentObjectType->isUnionType()? 3 :
643 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000644
645 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000646 if (SemaRef.getLangOptions().CPlusPlus) {
647 DK = diag::err_excess_initializers;
648 hadError = true;
649 }
Nate Begeman08634522009-07-07 21:53:06 +0000650 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
651 DK = diag::err_excess_initializers;
652 hadError = true;
653 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000654
Chris Lattner08202542009-02-24 22:50:46 +0000655 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000656 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000657 }
658 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000659
Sebastian Redl14b0c192011-09-24 17:48:00 +0000660 if (!VerifyOnly && T->isScalarType() && IList->getNumInits() == 1 &&
661 !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000662 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000663 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000664 << FixItHint::CreateRemoval(IList->getLocStart())
665 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000666}
667
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000668void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000669 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000670 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000671 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000672 unsigned &Index,
673 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000674 unsigned &StructuredIndex,
675 bool TopLevelObject) {
Eli Friedman0c706c22011-09-19 23:17:44 +0000676 if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) {
677 // Explicitly braced initializer for complex type can be real+imaginary
678 // parts.
679 CheckComplexType(Entity, IList, DeclType, Index,
680 StructuredList, StructuredIndex);
681 } else if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000682 CheckScalarType(Entity, IList, DeclType, Index,
683 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000684 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000685 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000686 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000687 } else if (DeclType->isAggregateType()) {
688 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000689 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000690 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000692 StructuredList, StructuredIndex,
693 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000694 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000695 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000696 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000697 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000698 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000699 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000700 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000701 } else
David Blaikieb219cfc2011-09-23 05:06:16 +0000702 llvm_unreachable("Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000703 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
704 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000705 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +0000706 if (!VerifyOnly)
707 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
708 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000709 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000710 } else if (DeclType->isRecordType()) {
711 // C++ [dcl.init]p14:
712 // [...] If the class is an aggregate (8.5.1), and the initializer
713 // is a brace-enclosed list, see 8.5.1.
714 //
715 // Note: 8.5.1 is handled below; here, we diagnose the case where
716 // we have an initializer list and a destination type that is not
717 // an aggregate.
718 // FIXME: In C++0x, this is yet another form of initialization.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000719 if (!VerifyOnly)
720 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
721 << DeclType << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000722 hadError = true;
723 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000724 CheckReferenceType(Entity, IList, DeclType, Index,
725 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000726 } else if (DeclType->isObjCObjectType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000727 if (!VerifyOnly)
728 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
729 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000730 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000731 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000732 if (!VerifyOnly)
733 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
734 << DeclType;
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000735 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000736 }
737}
738
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000739void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000740 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000741 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000742 unsigned &Index,
743 InitListExpr *StructuredList,
744 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000745 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000746 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
747 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000748 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000749 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000750 = getStructuredSubobjectInit(IList, Index, ElemType,
751 StructuredList, StructuredIndex,
752 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000753 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000754 newStructuredList, newStructuredIndex);
755 ++StructuredIndex;
756 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000757 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000758 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000759 return CheckScalarType(Entity, IList, ElemType, Index,
760 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000761 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000762 return CheckReferenceType(Entity, IList, ElemType, Index,
763 StructuredList, StructuredIndex);
764 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000765
John McCallfef8b342011-02-21 07:57:55 +0000766 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
767 // arrayType can be incomplete if we're initializing a flexible
768 // array member. There's nothing we can do with the completed
769 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000770
John McCallfef8b342011-02-21 07:57:55 +0000771 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
Eli Friedman8a5d9292011-09-26 19:09:09 +0000772 if (!VerifyOnly) {
773 CheckStringInit(Str, ElemType, arrayType, SemaRef);
774 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
775 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000776 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000777 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000778 }
John McCallfef8b342011-02-21 07:57:55 +0000779
780 // Fall through for subaggregate initialization.
781
782 } else if (SemaRef.getLangOptions().CPlusPlus) {
783 // C++ [dcl.init.aggr]p12:
784 // All implicit type conversions (clause 4) are considered when
Sebastian Redl5d3d41d2011-09-24 17:47:39 +0000785 // initializing the aggregate member with an initializer from
John McCallfef8b342011-02-21 07:57:55 +0000786 // an initializer-list. If the initializer can initialize a
787 // member, the member is initialized. [...]
788
789 // FIXME: Better EqualLoc?
790 InitializationKind Kind =
791 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
792 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
793
794 if (Seq) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000795 if (!VerifyOnly) {
Richard Smithb6f8d282011-12-20 04:00:21 +0000796 ExprResult Result =
797 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
798 if (Result.isInvalid())
799 hadError = true;
John McCallfef8b342011-02-21 07:57:55 +0000800
Sebastian Redl14b0c192011-09-24 17:48:00 +0000801 UpdateStructuredListElement(StructuredList, StructuredIndex,
Richard Smithb6f8d282011-12-20 04:00:21 +0000802 Result.takeAs<Expr>());
Sebastian Redl14b0c192011-09-24 17:48:00 +0000803 }
John McCallfef8b342011-02-21 07:57:55 +0000804 ++Index;
805 return;
806 }
807
808 // Fall through for subaggregate initialization
809 } else {
810 // C99 6.7.8p13:
811 //
812 // The initializer for a structure or union object that has
813 // automatic storage duration shall be either an initializer
814 // list as described below, or a single expression that has
815 // compatible structure or union type. In the latter case, the
816 // initial value of the object, including unnamed members, is
817 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000818 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000819 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
Sebastian Redl14b0c192011-09-24 17:48:00 +0000820 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes,
821 !VerifyOnly)
John McCallfef8b342011-02-21 07:57:55 +0000822 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000823 if (ExprRes.isInvalid())
824 hadError = true;
825 else {
826 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
827 if (ExprRes.isInvalid())
828 hadError = true;
829 }
830 UpdateStructuredListElement(StructuredList, StructuredIndex,
831 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000832 ++Index;
833 return;
834 }
John Wiegley429bb272011-04-08 18:41:53 +0000835 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000836 // Fall through for subaggregate initialization
837 }
838
839 // C++ [dcl.init.aggr]p12:
840 //
841 // [...] Otherwise, if the member is itself a non-empty
842 // subaggregate, brace elision is assumed and the initializer is
843 // considered for the initialization of the first member of
844 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000845 if (!SemaRef.getLangOptions().OpenCL &&
846 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000847 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
848 StructuredIndex);
849 ++StructuredIndex;
850 } else {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000851 if (!VerifyOnly) {
852 // We cannot initialize this element, so let
853 // PerformCopyInitialization produce the appropriate diagnostic.
854 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
855 SemaRef.Owned(expr),
856 /*TopLevelOfInitList=*/true);
857 }
John McCallfef8b342011-02-21 07:57:55 +0000858 hadError = true;
859 ++Index;
860 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000861 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000862}
863
Eli Friedman0c706c22011-09-19 23:17:44 +0000864void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
865 InitListExpr *IList, QualType DeclType,
866 unsigned &Index,
867 InitListExpr *StructuredList,
868 unsigned &StructuredIndex) {
869 assert(Index == 0 && "Index in explicit init list must be zero");
870
871 // As an extension, clang supports complex initializers, which initialize
872 // a complex number component-wise. When an explicit initializer list for
873 // a complex number contains two two initializers, this extension kicks in:
874 // it exepcts the initializer list to contain two elements convertible to
875 // the element type of the complex type. The first element initializes
876 // the real part, and the second element intitializes the imaginary part.
877
878 if (IList->getNumInits() != 2)
879 return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
880 StructuredIndex);
881
882 // This is an extension in C. (The builtin _Complex type does not exist
883 // in the C++ standard.)
Sebastian Redl14b0c192011-09-24 17:48:00 +0000884 if (!SemaRef.getLangOptions().CPlusPlus && !VerifyOnly)
Eli Friedman0c706c22011-09-19 23:17:44 +0000885 SemaRef.Diag(IList->getLocStart(), diag::ext_complex_component_init)
886 << IList->getSourceRange();
887
888 // Initialize the complex number.
889 QualType elementType = DeclType->getAs<ComplexType>()->getElementType();
890 InitializedEntity ElementEntity =
891 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
892
893 for (unsigned i = 0; i < 2; ++i) {
894 ElementEntity.setElementIndex(Index);
895 CheckSubElementType(ElementEntity, IList, elementType, Index,
896 StructuredList, StructuredIndex);
897 }
898}
899
900
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000901void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000902 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000903 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000904 InitListExpr *StructuredList,
905 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000906 if (Index >= IList->getNumInits()) {
Richard Smith6b130222011-10-18 21:39:00 +0000907 if (!VerifyOnly)
908 SemaRef.Diag(IList->getLocStart(),
909 SemaRef.getLangOptions().CPlusPlus0x ?
910 diag::warn_cxx98_compat_empty_scalar_initializer :
911 diag::err_empty_scalar_initializer)
912 << IList->getSourceRange();
913 hadError = !SemaRef.getLangOptions().CPlusPlus0x;
Douglas Gregor4c678342009-01-28 21:54:33 +0000914 ++Index;
915 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000916 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000917 }
John McCallb934c2d2010-11-11 00:46:36 +0000918
919 Expr *expr = IList->getInit(Index);
920 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000921 if (!VerifyOnly)
922 SemaRef.Diag(SubIList->getLocStart(),
923 diag::warn_many_braces_around_scalar_init)
924 << SubIList->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000925
926 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
927 StructuredIndex);
928 return;
929 } else if (isa<DesignatedInitExpr>(expr)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000930 if (!VerifyOnly)
931 SemaRef.Diag(expr->getSourceRange().getBegin(),
932 diag::err_designator_for_scalar_init)
933 << DeclType << expr->getSourceRange();
John McCallb934c2d2010-11-11 00:46:36 +0000934 hadError = true;
935 ++Index;
936 ++StructuredIndex;
937 return;
938 }
939
Sebastian Redl14b0c192011-09-24 17:48:00 +0000940 if (VerifyOnly) {
941 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
942 hadError = true;
943 ++Index;
944 return;
945 }
946
John McCallb934c2d2010-11-11 00:46:36 +0000947 ExprResult Result =
948 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000949 SemaRef.Owned(expr),
950 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000951
952 Expr *ResultExpr = 0;
953
954 if (Result.isInvalid())
955 hadError = true; // types weren't compatible.
956 else {
957 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000958
John McCallb934c2d2010-11-11 00:46:36 +0000959 if (ResultExpr != expr) {
960 // The type was promoted, update initializer list.
961 IList->setInit(Index, ResultExpr);
962 }
963 }
964 if (hadError)
965 ++StructuredIndex;
966 else
967 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
968 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000969}
970
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000971void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
972 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000973 unsigned &Index,
974 InitListExpr *StructuredList,
975 unsigned &StructuredIndex) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000976 if (Index >= IList->getNumInits()) {
Mike Stump390b4cc2009-05-16 07:39:55 +0000977 // FIXME: It would be wonderful if we could point at the actual member. In
978 // general, it would be useful to pass location information down the stack,
979 // so that we know the location (or decl) of the "current object" being
980 // initialized.
Sebastian Redl14b0c192011-09-24 17:48:00 +0000981 if (!VerifyOnly)
982 SemaRef.Diag(IList->getLocStart(),
983 diag::err_init_reference_member_uninitialized)
984 << DeclType
985 << IList->getSourceRange();
Douglas Gregor930d8b52009-01-30 22:09:00 +0000986 hadError = true;
987 ++Index;
988 ++StructuredIndex;
989 return;
990 }
Sebastian Redl14b0c192011-09-24 17:48:00 +0000991
992 Expr *expr = IList->getInit(Index);
Sebastian Redl13dc8f92011-11-27 16:50:07 +0000993 if (isa<InitListExpr>(expr) && !SemaRef.getLangOptions().CPlusPlus0x) {
Sebastian Redl14b0c192011-09-24 17:48:00 +0000994 if (!VerifyOnly)
995 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
996 << DeclType << IList->getSourceRange();
997 hadError = true;
998 ++Index;
999 ++StructuredIndex;
1000 return;
1001 }
1002
1003 if (VerifyOnly) {
1004 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(expr)))
1005 hadError = true;
1006 ++Index;
1007 return;
1008 }
1009
1010 ExprResult Result =
1011 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
1012 SemaRef.Owned(expr),
1013 /*TopLevelOfInitList=*/true);
1014
1015 if (Result.isInvalid())
1016 hadError = true;
1017
1018 expr = Result.takeAs<Expr>();
1019 IList->setInit(Index, expr);
1020
1021 if (hadError)
1022 ++StructuredIndex;
1023 else
1024 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1025 ++Index;
Douglas Gregor930d8b52009-01-30 22:09:00 +00001026}
1027
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001028void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +00001029 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +00001030 unsigned &Index,
1031 InitListExpr *StructuredList,
1032 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +00001033 const VectorType *VT = DeclType->getAs<VectorType>();
1034 unsigned maxElements = VT->getNumElements();
1035 unsigned numEltsInit = 0;
1036 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +00001037
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001038 if (Index >= IList->getNumInits()) {
1039 // Make sure the element type can be value-initialized.
1040 if (VerifyOnly)
1041 CheckValueInitializable(
1042 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity));
1043 return;
1044 }
1045
John McCall20e047a2010-10-30 00:11:39 +00001046 if (!SemaRef.getLangOptions().OpenCL) {
1047 // If the initializing element is a vector, try to copy-initialize
1048 // instead of breaking it apart (which is doomed to failure anyway).
1049 Expr *Init = IList->getInit(Index);
1050 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001051 if (VerifyOnly) {
1052 if (!SemaRef.CanPerformCopyInitialization(Entity, SemaRef.Owned(Init)))
1053 hadError = true;
1054 ++Index;
1055 return;
1056 }
1057
John McCall20e047a2010-10-30 00:11:39 +00001058 ExprResult Result =
1059 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +00001060 SemaRef.Owned(Init),
1061 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +00001062
1063 Expr *ResultExpr = 0;
1064 if (Result.isInvalid())
1065 hadError = true; // types weren't compatible.
1066 else {
1067 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068
John McCall20e047a2010-10-30 00:11:39 +00001069 if (ResultExpr != Init) {
1070 // The type was promoted, update initializer list.
1071 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +00001072 }
1073 }
John McCall20e047a2010-10-30 00:11:39 +00001074 if (hadError)
1075 ++StructuredIndex;
1076 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001077 UpdateStructuredListElement(StructuredList, StructuredIndex,
1078 ResultExpr);
John McCall20e047a2010-10-30 00:11:39 +00001079 ++Index;
1080 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001081 }
Mike Stump1eb44332009-09-09 15:08:12 +00001082
John McCall20e047a2010-10-30 00:11:39 +00001083 InitializedEntity ElementEntity =
1084 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
John McCall20e047a2010-10-30 00:11:39 +00001086 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
1087 // Don't attempt to go past the end of the init list
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001088 if (Index >= IList->getNumInits()) {
1089 if (VerifyOnly)
1090 CheckValueInitializable(ElementEntity);
John McCall20e047a2010-10-30 00:11:39 +00001091 break;
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001092 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001093
John McCall20e047a2010-10-30 00:11:39 +00001094 ElementEntity.setElementIndex(Index);
1095 CheckSubElementType(ElementEntity, IList, elementType, Index,
1096 StructuredList, StructuredIndex);
1097 }
1098 return;
Steve Naroff0cca7492008-05-01 22:18:59 +00001099 }
John McCall20e047a2010-10-30 00:11:39 +00001100
1101 InitializedEntity ElementEntity =
1102 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001103
John McCall20e047a2010-10-30 00:11:39 +00001104 // OpenCL initializers allows vectors to be constructed from vectors.
1105 for (unsigned i = 0; i < maxElements; ++i) {
1106 // Don't attempt to go past the end of the init list
1107 if (Index >= IList->getNumInits())
1108 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001109
John McCall20e047a2010-10-30 00:11:39 +00001110 ElementEntity.setElementIndex(Index);
1111
1112 QualType IType = IList->getInit(Index)->getType();
1113 if (!IType->isVectorType()) {
1114 CheckSubElementType(ElementEntity, IList, elementType, Index,
1115 StructuredList, StructuredIndex);
1116 ++numEltsInit;
1117 } else {
1118 QualType VecType;
1119 const VectorType *IVT = IType->getAs<VectorType>();
1120 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001121
John McCall20e047a2010-10-30 00:11:39 +00001122 if (IType->isExtVectorType())
1123 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1124 else
1125 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001126 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +00001127 CheckSubElementType(ElementEntity, IList, VecType, Index,
1128 StructuredList, StructuredIndex);
1129 numEltsInit += numIElts;
1130 }
1131 }
1132
1133 // OpenCL requires all elements to be initialized.
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001134 if (numEltsInit != maxElements) {
1135 if (!VerifyOnly)
1136 SemaRef.Diag(IList->getSourceRange().getBegin(),
1137 diag::err_vector_incorrect_num_initializers)
1138 << (numEltsInit < maxElements) << maxElements << numEltsInit;
1139 hadError = true;
1140 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001141}
1142
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001143void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001144 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001145 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001146 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001147 unsigned &Index,
1148 InitListExpr *StructuredList,
1149 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001150 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1151
Steve Naroff0cca7492008-05-01 22:18:59 +00001152 // Check for the special-case of initializing an array with a string.
1153 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001154 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001155 SemaRef.Context)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001156 // We place the string literal directly into the resulting
1157 // initializer list. This is the only place where the structure
1158 // of the structured initializer list doesn't match exactly,
1159 // because doing so would involve allocating one character
1160 // constant for each string.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001161 if (!VerifyOnly) {
Eli Friedman8a5d9292011-09-26 19:09:09 +00001162 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001163 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
1164 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1165 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001166 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001167 return;
1168 }
1169 }
John McCallce6c9b72011-02-21 07:22:22 +00001170 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001171 // Check for VLAs; in standard C it would be possible to check this
1172 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1173 // them in all sorts of strange places).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001174 if (!VerifyOnly)
1175 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
1176 diag::err_variable_object_no_init)
1177 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001178 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001179 ++Index;
1180 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001181 return;
1182 }
1183
Douglas Gregor05c13a32009-01-22 00:58:24 +00001184 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001185 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1186 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001188 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001189 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001190 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001191 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001192 maxElementsKnown = true;
1193 }
1194
John McCallce6c9b72011-02-21 07:22:22 +00001195 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001196 while (Index < IList->getNumInits()) {
1197 Expr *Init = IList->getInit(Index);
1198 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001199 // If we're not the subobject that matches up with the '{' for
1200 // the designator, we shouldn't be handling the
1201 // designator. Return immediately.
1202 if (!SubobjectIsDesignatorContext)
1203 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001204
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001205 // Handle this designated initializer. elementIndex will be
1206 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001207 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001208 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001209 StructuredList, StructuredIndex, true,
1210 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001211 hadError = true;
1212 continue;
1213 }
1214
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001215 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001216 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001217 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001218 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001219 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001220
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001221 // If the array is of incomplete type, keep track of the number of
1222 // elements in the initializer.
1223 if (!maxElementsKnown && elementIndex > maxElements)
1224 maxElements = elementIndex;
1225
Douglas Gregor05c13a32009-01-22 00:58:24 +00001226 continue;
1227 }
1228
1229 // If we know the maximum number of elements, and we've already
1230 // hit it, stop consuming elements in the initializer list.
1231 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001232 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001233
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001234 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001235 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001236 Entity);
1237 // Check this element.
1238 CheckSubElementType(ElementEntity, IList, elementType, Index,
1239 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001240 ++elementIndex;
1241
1242 // If the array is of incomplete type, keep track of the number of
1243 // elements in the initializer.
1244 if (!maxElementsKnown && elementIndex > maxElements)
1245 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001246 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001247 if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001248 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001249 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001250 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001251 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001252 // Sizing an array implicitly to zero is not allowed by ISO C,
1253 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001254 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001255 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001256 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001257
Mike Stump1eb44332009-09-09 15:08:12 +00001258 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001259 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001260 }
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001261 if (!hadError && VerifyOnly) {
1262 // Check if there are any members of the array that get value-initialized.
1263 // If so, check if doing that is possible.
1264 // FIXME: This needs to detect holes left by designated initializers too.
1265 if (maxElementsKnown && elementIndex < maxElements)
1266 CheckValueInitializable(InitializedEntity::InitializeElement(
1267 SemaRef.Context, 0, Entity));
1268 }
Steve Naroff0cca7492008-05-01 22:18:59 +00001269}
1270
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001271bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1272 Expr *InitExpr,
1273 FieldDecl *Field,
1274 bool TopLevelObject) {
1275 // Handle GNU flexible array initializers.
1276 unsigned FlexArrayDiag;
1277 if (isa<InitListExpr>(InitExpr) &&
1278 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1279 // Empty flexible array init always allowed as an extension
1280 FlexArrayDiag = diag::ext_flexible_array_init;
1281 } else if (SemaRef.getLangOptions().CPlusPlus) {
1282 // Disallow flexible array init in C++; it is not required for gcc
1283 // compatibility, and it needs work to IRGen correctly in general.
1284 FlexArrayDiag = diag::err_flexible_array_init;
1285 } else if (!TopLevelObject) {
1286 // Disallow flexible array init on non-top-level object
1287 FlexArrayDiag = diag::err_flexible_array_init;
1288 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1289 // Disallow flexible array init on anything which is not a variable.
1290 FlexArrayDiag = diag::err_flexible_array_init;
1291 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1292 // Disallow flexible array init on local variables.
1293 FlexArrayDiag = diag::err_flexible_array_init;
1294 } else {
1295 // Allow other cases.
1296 FlexArrayDiag = diag::ext_flexible_array_init;
1297 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001298
1299 if (!VerifyOnly) {
1300 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1301 FlexArrayDiag)
1302 << InitExpr->getSourceRange().getBegin();
1303 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1304 << Field;
1305 }
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001306
1307 return FlexArrayDiag != diag::ext_flexible_array_init;
1308}
1309
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001310void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001311 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001312 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001313 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001314 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001315 unsigned &Index,
1316 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001317 unsigned &StructuredIndex,
1318 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001319 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Eli Friedmanb85f7072008-05-19 19:16:24 +00001321 // If the record is invalid, some of it's members are invalid. To avoid
1322 // confusion, we forgo checking the intializer for the entire record.
1323 if (structDecl->isInvalidDecl()) {
1324 hadError = true;
1325 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001326 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001327
1328 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001329 // Value-initialize the first named member of the union.
1330 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
1331 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
1332 Field != FieldEnd; ++Field) {
1333 if (Field->getDeclName()) {
1334 if (VerifyOnly)
1335 CheckValueInitializable(
1336 InitializedEntity::InitializeMember(*Field, &Entity));
1337 else
Sebastian Redl14b0c192011-09-24 17:48:00 +00001338 StructuredList->setInitializedFieldInUnion(*Field);
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001339 break;
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001340 }
1341 }
1342 return;
1343 }
1344
Douglas Gregor05c13a32009-01-22 00:58:24 +00001345 // If structDecl is a forward declaration, this loop won't do
1346 // anything except look at designated initializers; That's okay,
1347 // because an error should get printed out elsewhere. It might be
1348 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001349 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001350 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001351 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001352 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001353 while (Index < IList->getNumInits()) {
1354 Expr *Init = IList->getInit(Index);
1355
1356 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001357 // If we're not the subobject that matches up with the '{' for
1358 // the designator, we shouldn't be handling the
1359 // designator. Return immediately.
1360 if (!SubobjectIsDesignatorContext)
1361 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001362
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001363 // Handle this designated initializer. Field will be updated to
1364 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001365 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001366 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001367 StructuredList, StructuredIndex,
1368 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001369 hadError = true;
1370
Douglas Gregordfb5e592009-02-12 19:00:39 +00001371 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001372
1373 // Disable check for missing fields when designators are used.
1374 // This matches gcc behaviour.
1375 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001376 continue;
1377 }
1378
1379 if (Field == FieldEnd) {
1380 // We've run out of fields. We're done.
1381 break;
1382 }
1383
Douglas Gregordfb5e592009-02-12 19:00:39 +00001384 // We've already initialized a member of a union. We're done.
1385 if (InitializedSomething && DeclType->isUnionType())
1386 break;
1387
Douglas Gregor44b43212008-12-11 16:49:14 +00001388 // If we've hit the flexible array member at the end, we're done.
1389 if (Field->getType()->isIncompleteArrayType())
1390 break;
1391
Douglas Gregor0bb76892009-01-29 16:53:55 +00001392 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001393 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001394 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001395 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001396 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001397
Douglas Gregor54001c12011-06-29 21:51:31 +00001398 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001399 bool InvalidUse;
1400 if (VerifyOnly)
1401 InvalidUse = !SemaRef.CanUseDecl(*Field);
1402 else
1403 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field,
1404 IList->getInit(Index)->getLocStart());
1405 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001406 ++Index;
1407 ++Field;
1408 hadError = true;
1409 continue;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001410 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001411
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001412 InitializedEntity MemberEntity =
1413 InitializedEntity::InitializeMember(*Field, &Entity);
1414 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1415 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001416 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001417
Sebastian Redl14b0c192011-09-24 17:48:00 +00001418 if (DeclType->isUnionType() && !VerifyOnly) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001419 // Initialize the first field within the union.
1420 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001421 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001422
1423 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001424 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001425
John McCall80639de2010-03-11 19:32:38 +00001426 // Emit warnings for missing struct field initializers.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001427 if (!VerifyOnly && InitializedSomething && CheckForMissingFields &&
1428 Field != FieldEnd && !Field->getType()->isIncompleteArrayType() &&
1429 !DeclType->isUnionType()) {
John McCall80639de2010-03-11 19:32:38 +00001430 // It is possible we have one or more unnamed bitfields remaining.
1431 // Find first (if any) named field and emit warning.
1432 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1433 it != end; ++it) {
1434 if (!it->isUnnamedBitfield()) {
1435 SemaRef.Diag(IList->getSourceRange().getEnd(),
1436 diag::warn_missing_field_initializers) << it->getName();
1437 break;
1438 }
1439 }
1440 }
1441
Sebastian Redl3ff5c862011-10-16 18:19:20 +00001442 // Check that any remaining fields can be value-initialized.
1443 if (VerifyOnly && Field != FieldEnd && !DeclType->isUnionType() &&
1444 !Field->getType()->isIncompleteArrayType()) {
1445 // FIXME: Should check for holes left by designated initializers too.
1446 for (; Field != FieldEnd && !hadError; ++Field) {
1447 if (!Field->isUnnamedBitfield())
1448 CheckValueInitializable(
1449 InitializedEntity::InitializeMember(*Field, &Entity));
1450 }
1451 }
1452
Mike Stump1eb44332009-09-09 15:08:12 +00001453 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001454 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001455 return;
1456
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001457 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1458 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001459 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001460 ++Index;
1461 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001462 }
1463
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001464 InitializedEntity MemberEntity =
1465 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001467 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001469 StructuredList, StructuredIndex);
1470 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001471 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001472 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001473}
Steve Naroff0cca7492008-05-01 22:18:59 +00001474
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001475/// \brief Expand a field designator that refers to a member of an
1476/// anonymous struct or union into a series of field designators that
1477/// refers to the field within the appropriate subobject.
1478///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001479static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001480 DesignatedInitExpr *DIE,
1481 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001482 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001483 typedef DesignatedInitExpr::Designator Designator;
1484
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001485 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001486 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001487 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1488 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1489 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001490 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001491 DIE->getDesignator(DesigIdx)->getDotLoc(),
1492 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1493 else
1494 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1495 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001496 assert(isa<FieldDecl>(*PI));
1497 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001498 }
1499
1500 // Expand the current designator into the set of replacement
1501 // designators, so we have a full subobject path down to where the
1502 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001503 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001504 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001505}
Mike Stump1eb44332009-09-09 15:08:12 +00001506
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001507/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001508/// corresponds to FieldName.
1509static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1510 IdentifierInfo *FieldName) {
1511 assert(AnonField->isAnonymousStructOrUnion());
1512 Decl *NextDecl = AnonField->getNextDeclInContext();
1513 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1514 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1515 return IF;
1516 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001517 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001518 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001519}
1520
Sebastian Redl14b0c192011-09-24 17:48:00 +00001521static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
1522 DesignatedInitExpr *DIE) {
1523 unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
1524 SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
1525 for (unsigned I = 0; I < NumIndexExprs; ++I)
1526 IndexExprs[I] = DIE->getSubExpr(I + 1);
1527 return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators_begin(),
1528 DIE->size(), IndexExprs.data(),
1529 NumIndexExprs, DIE->getEqualOrColonLoc(),
1530 DIE->usesGNUSyntax(), DIE->getInit());
1531}
1532
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001533namespace {
1534
1535// Callback to only accept typo corrections that are for field members of
1536// the given struct or union.
1537class FieldInitializerValidatorCCC : public CorrectionCandidateCallback {
1538 public:
1539 explicit FieldInitializerValidatorCCC(RecordDecl *RD)
1540 : Record(RD) {}
1541
1542 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1543 FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
1544 return FD && FD->getDeclContext()->getRedeclContext()->Equals(Record);
1545 }
1546
1547 private:
1548 RecordDecl *Record;
1549};
1550
1551}
1552
Douglas Gregor05c13a32009-01-22 00:58:24 +00001553/// @brief Check the well-formedness of a C99 designated initializer.
1554///
1555/// Determines whether the designated initializer @p DIE, which
1556/// resides at the given @p Index within the initializer list @p
1557/// IList, is well-formed for a current object of type @p DeclType
1558/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001559/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001560/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001561///
1562/// @param IList The initializer list in which this designated
1563/// initializer occurs.
1564///
Douglas Gregor71199712009-04-15 04:56:10 +00001565/// @param DIE The designated initializer expression.
1566///
1567/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001568///
1569/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1570/// into which the designation in @p DIE should refer.
1571///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001572/// @param NextField If non-NULL and the first designator in @p DIE is
1573/// a field, this will be set to the field declaration corresponding
1574/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001575///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001576/// @param NextElementIndex If non-NULL and the first designator in @p
1577/// DIE is an array designator or GNU array-range designator, this
1578/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001579///
1580/// @param Index Index into @p IList where the designated initializer
1581/// @p DIE occurs.
1582///
Douglas Gregor4c678342009-01-28 21:54:33 +00001583/// @param StructuredList The initializer list expression that
1584/// describes all of the subobject initializers in the order they'll
1585/// actually be initialized.
1586///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001587/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001588bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001589InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001590 InitListExpr *IList,
Sebastian Redl14b0c192011-09-24 17:48:00 +00001591 DesignatedInitExpr *DIE,
1592 unsigned DesigIdx,
1593 QualType &CurrentObjectType,
1594 RecordDecl::field_iterator *NextField,
1595 llvm::APSInt *NextElementIndex,
1596 unsigned &Index,
1597 InitListExpr *StructuredList,
1598 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001599 bool FinishSubobjectInit,
1600 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001601 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001602 // Check the actual initialization for the designated object type.
1603 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001604
1605 // Temporarily remove the designator expression from the
1606 // initializer list that the child calls see, so that we don't try
1607 // to re-process the designator.
1608 unsigned OldIndex = Index;
1609 IList->setInit(OldIndex, DIE->getInit());
1610
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001611 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001612 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001613
1614 // Restore the designated initializer expression in the syntactic
1615 // form of the initializer list.
1616 if (IList->getInit(OldIndex) != DIE->getInit())
1617 DIE->setInit(IList->getInit(OldIndex));
1618 IList->setInit(OldIndex, DIE);
1619
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001620 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001621 }
1622
Douglas Gregor71199712009-04-15 04:56:10 +00001623 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Sebastian Redl14b0c192011-09-24 17:48:00 +00001624 bool IsFirstDesignator = (DesigIdx == 0);
1625 if (!VerifyOnly) {
1626 assert((IsFirstDesignator || StructuredList) &&
1627 "Need a non-designated initializer list to start from");
1628
1629 // Determine the structural initializer list that corresponds to the
1630 // current subobject.
1631 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
1632 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
1633 StructuredList, StructuredIndex,
1634 SourceRange(D->getStartLocation(),
1635 DIE->getSourceRange().getEnd()));
1636 assert(StructuredList && "Expected a structured initializer list");
1637 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001638
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001639 if (D->isFieldDesignator()) {
1640 // C99 6.7.8p7:
1641 //
1642 // If a designator has the form
1643 //
1644 // . identifier
1645 //
1646 // then the current object (defined below) shall have
1647 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001648 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001649 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001650 if (!RT) {
1651 SourceLocation Loc = D->getDotLoc();
1652 if (Loc.isInvalid())
1653 Loc = D->getFieldLoc();
Sebastian Redl14b0c192011-09-24 17:48:00 +00001654 if (!VerifyOnly)
1655 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1656 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001657 ++Index;
1658 return true;
1659 }
1660
Douglas Gregor4c678342009-01-28 21:54:33 +00001661 // Note: we perform a linear search of the fields here, despite
1662 // the fact that we have a faster lookup method, because we always
1663 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001664 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001665 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001666 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001667 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001668 Field = RT->getDecl()->field_begin(),
1669 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001670 for (; Field != FieldEnd; ++Field) {
1671 if (Field->isUnnamedBitfield())
1672 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001673
Francois Picheta0e27f02010-12-22 03:46:10 +00001674 // If we find a field representing an anonymous field, look in the
1675 // IndirectFieldDecl that follow for the designated initializer.
1676 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1677 if (IndirectFieldDecl *IF =
1678 FindIndirectFieldDesignator(*Field, FieldName)) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001679 // In verify mode, don't modify the original.
1680 if (VerifyOnly)
1681 DIE = CloneDesignatedInitExpr(SemaRef, DIE);
Francois Picheta0e27f02010-12-22 03:46:10 +00001682 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1683 D = DIE->getDesignator(DesigIdx);
1684 break;
1685 }
1686 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001687 if (KnownField && KnownField == *Field)
1688 break;
1689 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001690 break;
1691
1692 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001693 }
1694
Douglas Gregor4c678342009-01-28 21:54:33 +00001695 if (Field == FieldEnd) {
Benjamin Kramera41ee492011-09-25 02:41:26 +00001696 if (VerifyOnly) {
1697 ++Index;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001698 return true; // No typo correction when just trying this out.
Benjamin Kramera41ee492011-09-25 02:41:26 +00001699 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00001700
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001701 // There was no normal field in the struct with the designated
1702 // name. Perform another lookup for this name, which may find
1703 // something that we can't designate (e.g., a member function),
1704 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001705 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001706 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001707 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001708 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001709 // Name lookup didn't find anything. Determine whether this
1710 // was a typo for another field name.
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001711 FieldInitializerValidatorCCC Validator(RT->getDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001712 TypoCorrection Corrected = SemaRef.CorrectTypo(
1713 DeclarationNameInfo(FieldName, D->getFieldLoc()),
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001714 Sema::LookupMemberName, /*Scope=*/0, /*SS=*/0, &Validator,
1715 RT->getDecl());
1716 if (Corrected) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001717 std::string CorrectedStr(
1718 Corrected.getAsString(SemaRef.getLangOptions()));
1719 std::string CorrectedQuotedStr(
1720 Corrected.getQuoted(SemaRef.getLangOptions()));
Kaelyn Uhrain425d6312012-01-12 19:27:05 +00001721 ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001722 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001723 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001724 << FieldName << CurrentObjectType << CorrectedQuotedStr
1725 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001727 diag::note_previous_decl) << CorrectedQuotedStr;
Benjamin Kramera41ee492011-09-25 02:41:26 +00001728 hadError = true;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001729 } else {
1730 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1731 << FieldName << CurrentObjectType;
1732 ++Index;
1733 return true;
1734 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001735 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001736
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001737 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001738 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001739 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001740 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001741 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001742 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001743 ++Index;
1744 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001745 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001746
Francois Picheta0e27f02010-12-22 03:46:10 +00001747 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001748 // The replacement field comes from typo correction; find it
1749 // in the list of fields.
1750 FieldIndex = 0;
1751 Field = RT->getDecl()->field_begin();
1752 for (; Field != FieldEnd; ++Field) {
1753 if (Field->isUnnamedBitfield())
1754 continue;
1755
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001756 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001757 Field->getIdentifier() == ReplacementField->getIdentifier())
1758 break;
1759
1760 ++FieldIndex;
1761 }
1762 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001763 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001764
1765 // All of the fields of a union are located at the same place in
1766 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001767 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001768 FieldIndex = 0;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001769 if (!VerifyOnly)
1770 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001771 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001772
Douglas Gregor54001c12011-06-29 21:51:31 +00001773 // Make sure we can use this declaration.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001774 bool InvalidUse;
1775 if (VerifyOnly)
1776 InvalidUse = !SemaRef.CanUseDecl(*Field);
1777 else
1778 InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
1779 if (InvalidUse) {
Douglas Gregor54001c12011-06-29 21:51:31 +00001780 ++Index;
1781 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00001782 }
Douglas Gregor54001c12011-06-29 21:51:31 +00001783
Sebastian Redl14b0c192011-09-24 17:48:00 +00001784 if (!VerifyOnly) {
1785 // Update the designator with the field declaration.
1786 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Sebastian Redl14b0c192011-09-24 17:48:00 +00001788 // Make sure that our non-designated initializer list has space
1789 // for a subobject corresponding to this field.
1790 if (FieldIndex >= StructuredList->getNumInits())
1791 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
1792 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001793
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001794 // This designator names a flexible array member.
1795 if (Field->getType()->isIncompleteArrayType()) {
1796 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001797 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001798 // We can't designate an object within the flexible array
1799 // member (because GCC doesn't allow it).
Sebastian Redl14b0c192011-09-24 17:48:00 +00001800 if (!VerifyOnly) {
1801 DesignatedInitExpr::Designator *NextD
1802 = DIE->getDesignator(DesigIdx + 1);
1803 SemaRef.Diag(NextD->getStartLocation(),
1804 diag::err_designator_into_flexible_array_member)
1805 << SourceRange(NextD->getStartLocation(),
1806 DIE->getSourceRange().getEnd());
1807 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1808 << *Field;
1809 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001810 Invalid = true;
1811 }
1812
Chris Lattner9046c222010-10-10 17:49:49 +00001813 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1814 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001815 // The initializer is not an initializer list.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001816 if (!VerifyOnly) {
1817 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
1818 diag::err_flexible_array_init_needs_braces)
1819 << DIE->getInit()->getSourceRange();
1820 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1821 << *Field;
1822 }
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001823 Invalid = true;
1824 }
1825
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001826 // Check GNU flexible array initializer.
1827 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1828 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001829 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001830
1831 if (Invalid) {
1832 ++Index;
1833 return true;
1834 }
1835
1836 // Initialize the array.
1837 bool prevHadError = hadError;
1838 unsigned newStructuredIndex = FieldIndex;
1839 unsigned OldIndex = Index;
1840 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001841
1842 InitializedEntity MemberEntity =
1843 InitializedEntity::InitializeMember(*Field, &Entity);
1844 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001845 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001846
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001847 IList->setInit(OldIndex, DIE);
1848 if (hadError && !prevHadError) {
1849 ++Field;
1850 ++FieldIndex;
1851 if (NextField)
1852 *NextField = Field;
1853 StructuredIndex = FieldIndex;
1854 return true;
1855 }
1856 } else {
1857 // Recurse to check later designated subobjects.
1858 QualType FieldType = (*Field)->getType();
1859 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001860
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001861 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001862 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001863 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1864 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001865 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001866 true, false))
1867 return true;
1868 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001869
1870 // Find the position of the next field to be initialized in this
1871 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001872 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001873 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001874
1875 // If this the first designator, our caller will continue checking
1876 // the rest of this struct/class/union subobject.
1877 if (IsFirstDesignator) {
1878 if (NextField)
1879 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001880 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001881 return false;
1882 }
1883
Douglas Gregor34e79462009-01-28 23:36:17 +00001884 if (!FinishSubobjectInit)
1885 return false;
1886
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001887 // We've already initialized something in the union; we're done.
1888 if (RT->getDecl()->isUnion())
1889 return hadError;
1890
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001891 // Check the remaining fields within this class/struct/union subobject.
1892 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001893
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001894 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001895 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001896 return hadError && !prevHadError;
1897 }
1898
1899 // C99 6.7.8p6:
1900 //
1901 // If a designator has the form
1902 //
1903 // [ constant-expression ]
1904 //
1905 // then the current object (defined below) shall have array
1906 // type and the expression shall be an integer constant
1907 // expression. If the array is of unknown size, any
1908 // nonnegative value is valid.
1909 //
1910 // Additionally, cope with the GNU extension that permits
1911 // designators of the form
1912 //
1913 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001914 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001915 if (!AT) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00001916 if (!VerifyOnly)
1917 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
1918 << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001919 ++Index;
1920 return true;
1921 }
1922
1923 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001924 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1925 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001926 IndexExpr = DIE->getArrayIndex(*D);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001927 DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001928 DesignatedEndIndex = DesignatedStartIndex;
1929 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001930 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001931
Mike Stump1eb44332009-09-09 15:08:12 +00001932 DesignatedStartIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001933 DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001934 DesignatedEndIndex =
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001935 DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001936 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001937
Chris Lattnere0fd8322011-02-19 22:28:58 +00001938 // Codegen can't handle evaluating array range designators that have side
1939 // effects, because we replicate the AST value for each initialized element.
1940 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1941 // elements with something that has a side effect, so codegen can emit an
1942 // "error unsupported" error instead of miscompiling the app.
1943 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
Sebastian Redl14b0c192011-09-24 17:48:00 +00001944 DIE->getInit()->HasSideEffects(SemaRef.Context) && !VerifyOnly)
Douglas Gregora9c87802009-01-29 19:42:23 +00001945 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001946 }
1947
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001948 if (isa<ConstantArrayType>(AT)) {
1949 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001950 DesignatedStartIndex
1951 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001952 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001953 DesignatedEndIndex
1954 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001955 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1956 if (DesignatedEndIndex >= MaxElements) {
Eli Friedmana4e20e12011-09-26 18:53:43 +00001957 if (!VerifyOnly)
Sebastian Redl14b0c192011-09-24 17:48:00 +00001958 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
1959 diag::err_array_designator_too_large)
1960 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
1961 << IndexExpr->getSourceRange();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001962 ++Index;
1963 return true;
1964 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001965 } else {
1966 // Make sure the bit-widths and signedness match.
1967 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001968 DesignatedEndIndex
1969 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001970 else if (DesignatedStartIndex.getBitWidth() <
1971 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001972 DesignatedStartIndex
1973 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001974 DesignatedStartIndex.setIsUnsigned(true);
1975 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Douglas Gregor4c678342009-01-28 21:54:33 +00001978 // Make sure that our non-designated initializer list has space
1979 // for a subobject corresponding to this array element.
Sebastian Redl14b0c192011-09-24 17:48:00 +00001980 if (!VerifyOnly &&
1981 DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001982 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001983 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001984
Douglas Gregor34e79462009-01-28 23:36:17 +00001985 // Repeatedly perform subobject initializations in the range
1986 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001987
Douglas Gregor34e79462009-01-28 23:36:17 +00001988 // Move to the next designator
1989 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1990 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001991
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001992 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001993 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001994
Douglas Gregor34e79462009-01-28 23:36:17 +00001995 while (DesignatedStartIndex <= DesignatedEndIndex) {
1996 // Recurse to check later designated subobjects.
1997 QualType ElementType = AT->getElementType();
1998 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001999
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002000 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002001 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
2002 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00002003 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00002004 (DesignatedStartIndex == DesignatedEndIndex),
2005 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00002006 return true;
2007
2008 // Move to the next index in the array that we'll be initializing.
2009 ++DesignatedStartIndex;
2010 ElementIndex = DesignatedStartIndex.getZExtValue();
2011 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002012
2013 // If this the first designator, our caller will continue checking
2014 // the rest of this array subobject.
2015 if (IsFirstDesignator) {
2016 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00002017 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00002018 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002019 return false;
2020 }
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Douglas Gregor34e79462009-01-28 23:36:17 +00002022 if (!FinishSubobjectInit)
2023 return false;
2024
Douglas Gregor87f55cf2009-01-22 23:26:18 +00002025 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00002026 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002027 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00002028 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00002029 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002030 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002031}
2032
Douglas Gregor4c678342009-01-28 21:54:33 +00002033// Get the structured initializer list for a subobject of type
2034// @p CurrentObjectType.
2035InitListExpr *
2036InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
2037 QualType CurrentObjectType,
2038 InitListExpr *StructuredList,
2039 unsigned StructuredIndex,
2040 SourceRange InitRange) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00002041 if (VerifyOnly)
2042 return 0; // No structured list in verification-only mode.
Douglas Gregor4c678342009-01-28 21:54:33 +00002043 Expr *ExistingInit = 0;
2044 if (!StructuredList)
2045 ExistingInit = SyntacticToSemantic[IList];
2046 else if (StructuredIndex < StructuredList->getNumInits())
2047 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Douglas Gregor4c678342009-01-28 21:54:33 +00002049 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
2050 return Result;
2051
2052 if (ExistingInit) {
2053 // We are creating an initializer list that initializes the
2054 // subobjects of the current object, but there was already an
2055 // initialization that completely initialized the current
2056 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00002057 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002058 // struct X { int a, b; };
2059 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00002060 //
Douglas Gregor4c678342009-01-28 21:54:33 +00002061 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
2062 // designated initializer re-initializes the whole
2063 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002064 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00002065 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00002066 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00002067 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002068 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002069 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002070 << ExistingInit->getSourceRange();
2071 }
2072
Mike Stump1eb44332009-09-09 15:08:12 +00002073 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00002074 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
2075 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00002076 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00002077
Douglas Gregor63982352010-07-13 18:40:04 +00002078 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00002079
Douglas Gregorfa219202009-03-20 23:58:33 +00002080 // Pre-allocate storage for the structured initializer list.
2081 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00002082 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002083 bool GotNumInits = false;
2084 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00002085 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002086 GotNumInits = true;
2087 } else if (Index < IList->getNumInits()) {
2088 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00002089 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002090 GotNumInits = true;
2091 }
Douglas Gregor08457732009-03-21 18:13:52 +00002092 }
2093
Mike Stump1eb44332009-09-09 15:08:12 +00002094 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00002095 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
2096 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
2097 NumElements = CAType->getSize().getZExtValue();
2098 // Simple heuristic so that we don't allocate a very large
2099 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00002100 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00002101 NumElements = 0;
2102 }
John McCall183700f2009-09-21 23:43:11 +00002103 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00002104 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00002105 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00002106 RecordDecl *RDecl = RType->getDecl();
2107 if (RDecl->isUnion())
2108 NumElements = 1;
2109 else
Mike Stump1eb44332009-09-09 15:08:12 +00002110 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002111 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00002112 }
2113
Ted Kremenek709210f2010-04-13 23:39:13 +00002114 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00002115
Douglas Gregor4c678342009-01-28 21:54:33 +00002116 // Link this new initializer list into the structured initializer
2117 // lists.
2118 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00002119 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00002120 else {
2121 Result->setSyntacticForm(IList);
2122 SyntacticToSemantic[IList] = Result;
2123 }
2124
2125 return Result;
2126}
2127
2128/// Update the initializer at index @p StructuredIndex within the
2129/// structured initializer list to the value @p expr.
2130void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
2131 unsigned &StructuredIndex,
2132 Expr *expr) {
2133 // No structured initializer list to update
2134 if (!StructuredList)
2135 return;
2136
Ted Kremenek709210f2010-04-13 23:39:13 +00002137 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
2138 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00002139 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00002140 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002141 diag::warn_initializer_overrides)
2142 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002143 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002144 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00002145 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00002146 << PrevInit->getSourceRange();
2147 }
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Douglas Gregor4c678342009-01-28 21:54:33 +00002149 ++StructuredIndex;
2150}
2151
Douglas Gregor05c13a32009-01-22 00:58:24 +00002152/// Check that the given Index expression is a valid array designator
2153/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00002154/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00002155/// and produces a reasonable diagnostic if there is a
2156/// failure. Returns true if there was an error, false otherwise. If
2157/// everything went okay, Value will receive the value of the constant
2158/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00002159static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00002160CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002161 SourceLocation Loc = Index->getSourceRange().getBegin();
2162
2163 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00002164 if (S.VerifyIntegerConstantExpression(Index, &Value))
2165 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002166
Chris Lattner3bf68932009-04-25 21:59:05 +00002167 if (Value.isSigned() && Value.isNegative())
2168 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00002169 << Value.toString(10) << Index->getSourceRange();
2170
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00002171 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00002172 return false;
2173}
2174
John McCall60d7b3a2010-08-24 06:29:42 +00002175ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00002176 SourceLocation Loc,
2177 bool GNUSyntax,
2178 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002179 typedef DesignatedInitExpr::Designator ASTDesignator;
2180
2181 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002182 SmallVector<ASTDesignator, 32> Designators;
2183 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00002184
2185 // Build designators and check array designator expressions.
2186 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
2187 const Designator &D = Desig.getDesignator(Idx);
2188 switch (D.getKind()) {
2189 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00002190 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002191 D.getFieldLoc()));
2192 break;
2193
2194 case Designator::ArrayDesignator: {
2195 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
2196 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002197 if (!Index->isTypeDependent() &&
2198 !Index->isValueDependent() &&
2199 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002200 Invalid = true;
2201 else {
2202 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002203 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00002204 D.getRBracketLoc()));
2205 InitExpressions.push_back(Index);
2206 }
2207 break;
2208 }
2209
2210 case Designator::ArrayRangeDesignator: {
2211 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
2212 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
2213 llvm::APSInt StartValue;
2214 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00002215 bool StartDependent = StartIndex->isTypeDependent() ||
2216 StartIndex->isValueDependent();
2217 bool EndDependent = EndIndex->isTypeDependent() ||
2218 EndIndex->isValueDependent();
2219 if ((!StartDependent &&
2220 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
2221 (!EndDependent &&
2222 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00002223 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00002224 else {
2225 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00002226 if (StartDependent || EndDependent) {
2227 // Nothing to compute.
2228 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002229 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002230 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002231 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002232
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002233 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002234 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002235 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002236 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2237 Invalid = true;
2238 } else {
2239 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002240 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002241 D.getEllipsisLoc(),
2242 D.getRBracketLoc()));
2243 InitExpressions.push_back(StartIndex);
2244 InitExpressions.push_back(EndIndex);
2245 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002246 }
2247 break;
2248 }
2249 }
2250 }
2251
2252 if (Invalid || Init.isInvalid())
2253 return ExprError();
2254
2255 // Clear out the expressions within the designation.
2256 Desig.ClearExprs(*this);
2257
2258 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002259 = DesignatedInitExpr::Create(Context,
2260 Designators.data(), Designators.size(),
2261 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002262 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002263
Richard Smithd7c56e12011-12-29 21:57:33 +00002264 if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002265 Diag(DIE->getLocStart(), diag::ext_designated_init)
2266 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002267
Douglas Gregor05c13a32009-01-22 00:58:24 +00002268 return Owned(DIE);
2269}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002270
Douglas Gregor20093b42009-12-09 23:02:17 +00002271//===----------------------------------------------------------------------===//
2272// Initialization entity
2273//===----------------------------------------------------------------------===//
2274
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002275InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002276 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002277 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002278{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002279 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2280 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002281 Type = AT->getElementType();
Eli Friedman0c706c22011-09-19 23:17:44 +00002282 } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
Anders Carlssond3d824d2010-01-23 04:34:47 +00002283 Kind = EK_VectorElement;
Eli Friedman0c706c22011-09-19 23:17:44 +00002284 Type = VT->getElementType();
2285 } else {
2286 const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
2287 assert(CT && "Unexpected type");
2288 Kind = EK_ComplexElement;
2289 Type = CT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002290 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002291}
2292
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002293InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002294 CXXBaseSpecifier *Base,
2295 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002296{
2297 InitializedEntity Result;
2298 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002299 Result.Base = reinterpret_cast<uintptr_t>(Base);
2300 if (IsInheritedVirtualBase)
2301 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002302
Douglas Gregord6542d82009-12-22 15:35:07 +00002303 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002304 return Result;
2305}
2306
Douglas Gregor99a2e602009-12-16 01:38:02 +00002307DeclarationName InitializedEntity::getName() const {
2308 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002309 case EK_Parameter: {
2310 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2311 return (D ? D->getDeclName() : DeclarationName());
2312 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002313
2314 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002315 case EK_Member:
2316 return VariableOrMember->getDeclName();
2317
2318 case EK_Result:
2319 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002320 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002321 case EK_Temporary:
2322 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002323 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002324 case EK_ArrayElement:
2325 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002326 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002327 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002328 return DeclarationName();
2329 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002330
David Blaikie7530c032012-01-17 06:56:22 +00002331 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor99a2e602009-12-16 01:38:02 +00002332}
2333
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002334DeclaratorDecl *InitializedEntity::getDecl() const {
2335 switch (getKind()) {
2336 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002337 case EK_Member:
2338 return VariableOrMember;
2339
John McCallf85e1932011-06-15 23:02:42 +00002340 case EK_Parameter:
2341 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2342
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002343 case EK_Result:
2344 case EK_Exception:
2345 case EK_New:
2346 case EK_Temporary:
2347 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002348 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002349 case EK_ArrayElement:
2350 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002351 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002352 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002353 return 0;
2354 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002355
David Blaikie7530c032012-01-17 06:56:22 +00002356 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002357}
2358
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002359bool InitializedEntity::allowsNRVO() const {
2360 switch (getKind()) {
2361 case EK_Result:
2362 case EK_Exception:
2363 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002364
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002365 case EK_Variable:
2366 case EK_Parameter:
2367 case EK_Member:
2368 case EK_New:
2369 case EK_Temporary:
2370 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002371 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002372 case EK_ArrayElement:
2373 case EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00002374 case EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002375 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002376 break;
2377 }
2378
2379 return false;
2380}
2381
Douglas Gregor20093b42009-12-09 23:02:17 +00002382//===----------------------------------------------------------------------===//
2383// Initialization sequence
2384//===----------------------------------------------------------------------===//
2385
2386void InitializationSequence::Step::Destroy() {
2387 switch (Kind) {
2388 case SK_ResolveAddressOfOverloadedFunction:
2389 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002390 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002391 case SK_CastDerivedToBaseLValue:
2392 case SK_BindReference:
2393 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002394 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002395 case SK_UserConversion:
2396 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002397 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002398 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002399 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002400 case SK_ListConstructorCall:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002401 case SK_UnwrapInitList:
2402 case SK_RewrapInitList:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002403 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002404 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002405 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002406 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002407 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002408 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002409 case SK_PassByIndirectCopyRestore:
2410 case SK_PassByIndirectRestore:
2411 case SK_ProduceObjCObject:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002412 case SK_StdInitializerList:
Douglas Gregor20093b42009-12-09 23:02:17 +00002413 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002414
Douglas Gregor20093b42009-12-09 23:02:17 +00002415 case SK_ConversionSequence:
2416 delete ICS;
2417 }
2418}
2419
Douglas Gregorb70cf442010-03-26 20:14:36 +00002420bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002421 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002422}
2423
2424bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002425 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002426 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002427
Douglas Gregorb70cf442010-03-26 20:14:36 +00002428 switch (getFailureKind()) {
2429 case FK_TooManyInitsForReference:
2430 case FK_ArrayNeedsInitList:
2431 case FK_ArrayNeedsInitListOrStringLiteral:
2432 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2433 case FK_NonConstLValueReferenceBindingToTemporary:
2434 case FK_NonConstLValueReferenceBindingToUnrelated:
2435 case FK_RValueReferenceBindingToLValue:
2436 case FK_ReferenceInitDropsQualifiers:
2437 case FK_ReferenceInitFailed:
2438 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002439 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002440 case FK_TooManyInitsForScalar:
2441 case FK_ReferenceBindingToInitList:
2442 case FK_InitListBadDestinationType:
2443 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002444 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002445 case FK_ArrayTypeMismatch:
2446 case FK_NonConstantArrayInit:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00002447 case FK_ListInitializationFailed:
John McCall73076432012-01-05 00:13:19 +00002448 case FK_VariableLengthArrayHasInitializer:
John McCall5acb0c92011-10-17 18:40:02 +00002449 case FK_PlaceholderType:
Sebastian Redl2b916b82012-01-17 22:49:42 +00002450 case FK_InitListElementCopyFailure:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002451 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002452
Douglas Gregorb70cf442010-03-26 20:14:36 +00002453 case FK_ReferenceInitOverloadFailed:
2454 case FK_UserConversionOverloadFailed:
2455 case FK_ConstructorOverloadFailed:
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002456 case FK_ListConstructorOverloadFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002457 return FailedOverloadResult == OR_Ambiguous;
2458 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002459
David Blaikie7530c032012-01-17 06:56:22 +00002460 llvm_unreachable("Invalid EntityKind!");
Douglas Gregorb70cf442010-03-26 20:14:36 +00002461}
2462
Douglas Gregord6e44a32010-04-16 22:09:46 +00002463bool InitializationSequence::isConstructorInitialization() const {
2464 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2465}
2466
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002467bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2468 const Expr *Initializer,
2469 bool *isInitializerConstant,
2470 APValue *ConstantValue) const {
2471 if (Steps.empty() || Initializer->isValueDependent())
2472 return false;
2473
2474 const Step &LastStep = Steps.back();
2475 if (LastStep.Kind != SK_ConversionSequence)
2476 return false;
2477
2478 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2479 const StandardConversionSequence *SCS = NULL;
2480 switch (ICS.getKind()) {
2481 case ImplicitConversionSequence::StandardConversion:
2482 SCS = &ICS.Standard;
2483 break;
2484 case ImplicitConversionSequence::UserDefinedConversion:
2485 SCS = &ICS.UserDefined.After;
2486 break;
2487 case ImplicitConversionSequence::AmbiguousConversion:
2488 case ImplicitConversionSequence::EllipsisConversion:
2489 case ImplicitConversionSequence::BadConversion:
2490 return false;
2491 }
2492
2493 // Check if SCS represents a narrowing conversion, according to C++0x
2494 // [dcl.init.list]p7:
2495 //
2496 // A narrowing conversion is an implicit conversion ...
2497 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2498 QualType FromType = SCS->getToType(0);
2499 QualType ToType = SCS->getToType(1);
2500 switch (PossibleNarrowing) {
2501 // * from a floating-point type to an integer type, or
2502 //
2503 // * from an integer type or unscoped enumeration type to a floating-point
2504 // type, except where the source is a constant expression and the actual
2505 // value after conversion will fit into the target type and will produce
2506 // the original value when converted back to the original type, or
2507 case ICK_Floating_Integral:
2508 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2509 *isInitializerConstant = false;
2510 return true;
2511 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2512 llvm::APSInt IntConstantValue;
2513 if (Initializer &&
2514 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2515 // Convert the integer to the floating type.
2516 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2517 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2518 llvm::APFloat::rmNearestTiesToEven);
2519 // And back.
2520 llvm::APSInt ConvertedValue = IntConstantValue;
2521 bool ignored;
2522 Result.convertToInteger(ConvertedValue,
2523 llvm::APFloat::rmTowardZero, &ignored);
2524 // If the resulting value is different, this was a narrowing conversion.
2525 if (IntConstantValue != ConvertedValue) {
2526 *isInitializerConstant = true;
2527 *ConstantValue = APValue(IntConstantValue);
2528 return true;
2529 }
2530 } else {
2531 // Variables are always narrowings.
2532 *isInitializerConstant = false;
2533 return true;
2534 }
2535 }
2536 return false;
2537
2538 // * from long double to double or float, or from double to float, except
2539 // where the source is a constant expression and the actual value after
2540 // conversion is within the range of values that can be represented (even
2541 // if it cannot be represented exactly), or
2542 case ICK_Floating_Conversion:
2543 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2544 // FromType is larger than ToType.
2545 Expr::EvalResult InitializerValue;
2546 // FIXME: Check whether Initializer is a constant expression according
2547 // to C++0x [expr.const], rather than just whether it can be folded.
Richard Smith51f47082011-10-29 00:50:52 +00002548 if (Initializer->EvaluateAsRValue(InitializerValue, Ctx) &&
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002549 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2550 // Constant! (Except for FIXME above.)
2551 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2552 // Convert the source value into the target type.
2553 bool ignored;
2554 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2555 Ctx.getFloatTypeSemantics(ToType),
2556 llvm::APFloat::rmNearestTiesToEven, &ignored);
2557 // If there was no overflow, the source value is within the range of
2558 // values that can be represented.
2559 if (ConvertStatus & llvm::APFloat::opOverflow) {
2560 *isInitializerConstant = true;
2561 *ConstantValue = InitializerValue.Val;
2562 return true;
2563 }
2564 } else {
2565 *isInitializerConstant = false;
2566 return true;
2567 }
2568 }
2569 return false;
2570
2571 // * from an integer type or unscoped enumeration type to an integer type
2572 // that cannot represent all the values of the original type, except where
2573 // the source is a constant expression and the actual value after
2574 // conversion will fit into the target type and will produce the original
2575 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002576 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002577 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2578 // Boolean conversions can be from pointers and pointers to members
2579 // [conv.bool], and those aren't considered narrowing conversions.
2580 return false;
2581 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002582 case ICK_Integral_Conversion: {
2583 assert(FromType->isIntegralOrUnscopedEnumerationType());
2584 assert(ToType->isIntegralOrUnscopedEnumerationType());
2585 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2586 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2587 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2588 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2589
2590 if (FromWidth > ToWidth ||
2591 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2592 // Not all values of FromType can be represented in ToType.
2593 llvm::APSInt InitializerValue;
2594 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2595 *isInitializerConstant = true;
2596 *ConstantValue = APValue(InitializerValue);
2597
2598 // Add a bit to the InitializerValue so we don't have to worry about
2599 // signed vs. unsigned comparisons.
2600 InitializerValue = InitializerValue.extend(
2601 InitializerValue.getBitWidth() + 1);
2602 // Convert the initializer to and from the target width and signed-ness.
2603 llvm::APSInt ConvertedValue = InitializerValue;
2604 ConvertedValue = ConvertedValue.trunc(ToWidth);
2605 ConvertedValue.setIsSigned(ToSigned);
2606 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2607 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2608 // If the result is different, this was a narrowing conversion.
2609 return ConvertedValue != InitializerValue;
2610 } else {
2611 // Variables are always narrowings.
2612 *isInitializerConstant = false;
2613 return true;
2614 }
2615 }
2616 return false;
2617 }
2618
2619 default:
2620 // Other kinds of conversions are not narrowings.
2621 return false;
2622 }
2623}
2624
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002625void
2626InitializationSequence
2627::AddAddressOverloadResolutionStep(FunctionDecl *Function,
2628 DeclAccessPair Found,
2629 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002630 Step S;
2631 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2632 S.Type = Function->getType();
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002633 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002634 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002635 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002636 Steps.push_back(S);
2637}
2638
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002639void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002640 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002641 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002642 switch (VK) {
2643 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2644 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2645 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002646 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002647 S.Type = BaseType;
2648 Steps.push_back(S);
2649}
2650
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002651void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002652 bool BindingTemporary) {
2653 Step S;
2654 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2655 S.Type = T;
2656 Steps.push_back(S);
2657}
2658
Douglas Gregor523d46a2010-04-18 07:40:54 +00002659void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2660 Step S;
2661 S.Kind = SK_ExtraneousCopyToTemporary;
2662 S.Type = T;
2663 Steps.push_back(S);
2664}
2665
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002666void
2667InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
2668 DeclAccessPair FoundDecl,
2669 QualType T,
2670 bool HadMultipleCandidates) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002671 Step S;
2672 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002673 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002674 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002675 S.Function.Function = Function;
2676 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002677 Steps.push_back(S);
2678}
2679
2680void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002681 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002682 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002683 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002684 switch (VK) {
2685 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002686 S.Kind = SK_QualificationConversionRValue;
2687 break;
John McCall5baba9d2010-08-25 10:28:54 +00002688 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002689 S.Kind = SK_QualificationConversionXValue;
2690 break;
John McCall5baba9d2010-08-25 10:28:54 +00002691 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002692 S.Kind = SK_QualificationConversionLValue;
2693 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002694 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002695 S.Type = Ty;
2696 Steps.push_back(S);
2697}
2698
2699void InitializationSequence::AddConversionSequenceStep(
2700 const ImplicitConversionSequence &ICS,
2701 QualType T) {
2702 Step S;
2703 S.Kind = SK_ConversionSequence;
2704 S.Type = T;
2705 S.ICS = new ImplicitConversionSequence(ICS);
2706 Steps.push_back(S);
2707}
2708
Douglas Gregord87b61f2009-12-10 17:56:55 +00002709void InitializationSequence::AddListInitializationStep(QualType T) {
2710 Step S;
2711 S.Kind = SK_ListInitialization;
2712 S.Type = T;
2713 Steps.push_back(S);
2714}
2715
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002716void
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002717InitializationSequence
2718::AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
2719 AccessSpecifier Access,
2720 QualType T,
Sebastian Redl10f04a62011-12-22 14:44:04 +00002721 bool HadMultipleCandidates,
2722 bool FromInitList) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00002723 Step S;
Sebastian Redl10f04a62011-12-22 14:44:04 +00002724 S.Kind = FromInitList ? SK_ListConstructorCall : SK_ConstructorInitialization;
Douglas Gregor51c56d62009-12-14 20:49:26 +00002725 S.Type = T;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00002726 S.Function.HadMultipleCandidates = HadMultipleCandidates;
John McCall9aa472c2010-03-19 07:35:19 +00002727 S.Function.Function = Constructor;
2728 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002729 Steps.push_back(S);
2730}
2731
Douglas Gregor71d17402009-12-15 00:01:57 +00002732void InitializationSequence::AddZeroInitializationStep(QualType T) {
2733 Step S;
2734 S.Kind = SK_ZeroInitialization;
2735 S.Type = T;
2736 Steps.push_back(S);
2737}
2738
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002739void InitializationSequence::AddCAssignmentStep(QualType T) {
2740 Step S;
2741 S.Kind = SK_CAssignment;
2742 S.Type = T;
2743 Steps.push_back(S);
2744}
2745
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002746void InitializationSequence::AddStringInitStep(QualType T) {
2747 Step S;
2748 S.Kind = SK_StringInit;
2749 S.Type = T;
2750 Steps.push_back(S);
2751}
2752
Douglas Gregor569c3162010-08-07 11:51:51 +00002753void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2754 Step S;
2755 S.Kind = SK_ObjCObjectConversion;
2756 S.Type = T;
2757 Steps.push_back(S);
2758}
2759
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002760void InitializationSequence::AddArrayInitStep(QualType T) {
2761 Step S;
2762 S.Kind = SK_ArrayInit;
2763 S.Type = T;
2764 Steps.push_back(S);
2765}
2766
John McCallf85e1932011-06-15 23:02:42 +00002767void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2768 bool shouldCopy) {
2769 Step s;
2770 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2771 : SK_PassByIndirectRestore);
2772 s.Type = type;
2773 Steps.push_back(s);
2774}
2775
2776void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2777 Step S;
2778 S.Kind = SK_ProduceObjCObject;
2779 S.Type = T;
2780 Steps.push_back(S);
2781}
2782
Sebastian Redl2b916b82012-01-17 22:49:42 +00002783void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
2784 Step S;
2785 S.Kind = SK_StdInitializerList;
2786 S.Type = T;
2787 Steps.push_back(S);
2788}
2789
Sebastian Redl13dc8f92011-11-27 16:50:07 +00002790void InitializationSequence::RewrapReferenceInitList(QualType T,
2791 InitListExpr *Syntactic) {
2792 assert(Syntactic->getNumInits() == 1 &&
2793 "Can only rewrap trivial init lists.");
2794 Step S;
2795 S.Kind = SK_UnwrapInitList;
2796 S.Type = Syntactic->getInit(0)->getType();
2797 Steps.insert(Steps.begin(), S);
2798
2799 S.Kind = SK_RewrapInitList;
2800 S.Type = T;
2801 S.WrappingSyntacticList = Syntactic;
2802 Steps.push_back(S);
2803}
2804
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002806 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002807 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002808 this->Failure = Failure;
2809 this->FailedOverloadResult = Result;
2810}
2811
2812//===----------------------------------------------------------------------===//
2813// Attempt initialization
2814//===----------------------------------------------------------------------===//
2815
John McCallf85e1932011-06-15 23:02:42 +00002816static void MaybeProduceObjCObject(Sema &S,
2817 InitializationSequence &Sequence,
2818 const InitializedEntity &Entity) {
2819 if (!S.getLangOptions().ObjCAutoRefCount) return;
2820
2821 /// When initializing a parameter, produce the value if it's marked
2822 /// __attribute__((ns_consumed)).
2823 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2824 if (!Entity.isParameterConsumed())
2825 return;
2826
2827 assert(Entity.getType()->isObjCRetainableType() &&
2828 "consuming an object of unretainable type?");
2829 Sequence.AddProduceObjCObjectStep(Entity.getType());
2830
2831 /// When initializing a return value, if the return type is a
2832 /// retainable type, then returns need to immediately retain the
2833 /// object. If an autorelease is required, it will be done at the
2834 /// last instant.
2835 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2836 if (!Entity.getType()->isObjCRetainableType())
2837 return;
2838
2839 Sequence.AddProduceObjCObjectStep(Entity.getType());
2840 }
2841}
2842
Sebastian Redl10f04a62011-12-22 14:44:04 +00002843/// \brief When initializing from init list via constructor, deal with the
2844/// empty init list and std::initializer_list special cases.
2845///
2846/// \return True if this was a special case, false otherwise.
2847static bool TryListConstructionSpecialCases(Sema &S,
2848 Expr **Args, unsigned NumArgs,
2849 CXXRecordDecl *DestRecordDecl,
2850 QualType DestType,
2851 InitializationSequence &Sequence) {
Sebastian Redl2b916b82012-01-17 22:49:42 +00002852 // C++11 [dcl.init.list]p3:
Sebastian Redl10f04a62011-12-22 14:44:04 +00002853 // List-initialization of an object of type T is defined as follows:
2854 // - If the initializer list has no elements and T is a class type with
2855 // a default constructor, the object is value-initialized.
2856 if (NumArgs == 0) {
2857 if (CXXConstructorDecl *DefaultConstructor =
2858 S.LookupDefaultConstructor(DestRecordDecl)) {
2859 if (DefaultConstructor->isDeleted() ||
2860 S.isFunctionConsideredUnavailable(DefaultConstructor)) {
2861 // Fake an overload resolution failure.
2862 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2863 DeclAccessPair FoundDecl = DeclAccessPair::make(DefaultConstructor,
2864 DefaultConstructor->getAccess());
2865 if (FunctionTemplateDecl *ConstructorTmpl =
2866 dyn_cast<FunctionTemplateDecl>(DefaultConstructor))
2867 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2868 /*ExplicitArgs*/ 0,
2869 Args, NumArgs, CandidateSet,
2870 /*SuppressUserConversions*/ false);
2871 else
2872 S.AddOverloadCandidate(DefaultConstructor, FoundDecl,
2873 Args, NumArgs, CandidateSet,
2874 /*SuppressUserConversions*/ false);
2875 Sequence.SetOverloadFailure(
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002876 InitializationSequence::FK_ListConstructorOverloadFailed,
2877 OR_Deleted);
Sebastian Redl10f04a62011-12-22 14:44:04 +00002878 } else
2879 Sequence.AddConstructorInitializationStep(DefaultConstructor,
2880 DefaultConstructor->getAccess(),
2881 DestType,
2882 /*MultipleCandidates=*/false,
2883 /*FromInitList=*/true);
2884 return true;
2885 }
2886 }
2887
2888 // - Otherwise, if T is a specialization of std::initializer_list, [...]
Sebastian Redl2b916b82012-01-17 22:49:42 +00002889 QualType E;
2890 if (S.isStdInitializerList(DestType, &E)) {
2891 // Check that each individual element can be copy-constructed. But since we
2892 // have no place to store further information, we'll recalculate everything
2893 // later.
2894 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
2895 S.Context.getConstantArrayType(E,
2896 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),NumArgs),
2897 ArrayType::Normal, 0));
2898 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
2899 0, HiddenArray);
2900 for (unsigned i = 0; i < NumArgs; ++i) {
2901 Element.setElementIndex(i);
2902 if (!S.CanPerformCopyInitialization(Element, Args[i])) {
2903 Sequence.SetFailed(
2904 InitializationSequence::FK_InitListElementCopyFailure);
2905 return true;
2906 }
2907 }
2908 Sequence.AddStdInitializerListConstructionStep(DestType);
2909 return true;
2910 }
Sebastian Redl10f04a62011-12-22 14:44:04 +00002911
2912 // Not a special case.
2913 return false;
2914}
2915
2916/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
2917/// enumerates the constructors of the initialized entity and performs overload
2918/// resolution to select the best.
2919/// If FromInitList is true, this is list-initialization of a non-aggregate
2920/// class type.
2921static void TryConstructorInitialization(Sema &S,
2922 const InitializedEntity &Entity,
2923 const InitializationKind &Kind,
2924 Expr **Args, unsigned NumArgs,
2925 QualType DestType,
2926 InitializationSequence &Sequence,
2927 bool FromInitList = false) {
2928 // Check constructor arguments for self reference.
2929 if (DeclaratorDecl *DD = Entity.getDecl())
2930 // Parameters arguments are occassionially constructed with itself,
2931 // for instance, in recursive functions. Skip them.
2932 if (!isa<ParmVarDecl>(DD))
2933 for (unsigned i = 0; i < NumArgs; ++i)
2934 S.CheckSelfReference(DD, Args[i]);
2935
2936 // Build the candidate set directly in the initialization sequence
2937 // structure, so that it will persist if we fail.
2938 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2939 CandidateSet.clear();
2940
2941 // Determine whether we are allowed to call explicit constructors or
2942 // explicit conversion operators.
2943 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
2944 Kind.getKind() == InitializationKind::IK_Value ||
2945 Kind.getKind() == InitializationKind::IK_Default);
2946
2947 // The type we're constructing needs to be complete.
2948 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
2949 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
2950 }
2951
2952 const RecordType *DestRecordType = DestType->getAs<RecordType>();
2953 assert(DestRecordType && "Constructor initialization requires record type");
2954 CXXRecordDecl *DestRecordDecl
2955 = cast<CXXRecordDecl>(DestRecordType->getDecl());
2956
2957 if (FromInitList &&
2958 TryListConstructionSpecialCases(S, Args, NumArgs, DestRecordDecl,
2959 DestType, Sequence))
2960 return;
2961
2962 // - Otherwise, if T is a class type, constructors are considered. The
2963 // applicable constructors are enumerated, and the best one is chosen
2964 // through overload resolution.
2965 DeclContext::lookup_iterator Con, ConEnd;
2966 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
2967 Con != ConEnd; ++Con) {
2968 NamedDecl *D = *Con;
2969 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2970 bool SuppressUserConversions = false;
2971
2972 // Find the constructor (which may be a template).
2973 CXXConstructorDecl *Constructor = 0;
2974 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
2975 if (ConstructorTmpl)
2976 Constructor = cast<CXXConstructorDecl>(
2977 ConstructorTmpl->getTemplatedDecl());
2978 else {
2979 Constructor = cast<CXXConstructorDecl>(D);
2980
2981 // If we're performing copy initialization using a copy constructor, we
2982 // suppress user-defined conversions on the arguments.
2983 // FIXME: Move constructors?
2984 if (Kind.getKind() == InitializationKind::IK_Copy &&
2985 Constructor->isCopyConstructor())
2986 SuppressUserConversions = true;
2987 }
2988
2989 if (!Constructor->isInvalidDecl() &&
2990 (AllowExplicit || !Constructor->isExplicit())) {
2991 if (ConstructorTmpl)
2992 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2993 /*ExplicitArgs*/ 0,
2994 Args, NumArgs, CandidateSet,
2995 SuppressUserConversions);
2996 else
2997 S.AddOverloadCandidate(Constructor, FoundDecl,
2998 Args, NumArgs, CandidateSet,
2999 SuppressUserConversions);
3000 }
3001 }
3002
3003 SourceLocation DeclLoc = Kind.getLocation();
3004
3005 // Perform overload resolution. If it fails, return the failed result.
3006 OverloadCandidateSet::iterator Best;
3007 if (OverloadingResult Result
3008 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003009 Sequence.SetOverloadFailure(FromInitList ?
3010 InitializationSequence::FK_ListConstructorOverloadFailed :
3011 InitializationSequence::FK_ConstructorOverloadFailed,
Sebastian Redl10f04a62011-12-22 14:44:04 +00003012 Result);
3013 return;
3014 }
3015
3016 // C++0x [dcl.init]p6:
3017 // If a program calls for the default initialization of an object
3018 // of a const-qualified type T, T shall be a class type with a
3019 // user-provided default constructor.
3020 if (Kind.getKind() == InitializationKind::IK_Default &&
3021 Entity.getType().isConstQualified() &&
3022 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3023 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3024 return;
3025 }
3026
3027 // Add the constructor initialization step. Any cv-qualification conversion is
3028 // subsumed by the initialization.
3029 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3030 CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
3031 Sequence.AddConstructorInitializationStep(CtorDecl,
3032 Best->FoundDecl.getAccess(),
3033 DestType, HadMultipleCandidates,
3034 FromInitList);
3035}
3036
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003037static bool
3038ResolveOverloadedFunctionForReferenceBinding(Sema &S,
3039 Expr *Initializer,
3040 QualType &SourceType,
3041 QualType &UnqualifiedSourceType,
3042 QualType UnqualifiedTargetType,
3043 InitializationSequence &Sequence) {
3044 if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
3045 S.Context.OverloadTy) {
3046 DeclAccessPair Found;
3047 bool HadMultipleCandidates = false;
3048 if (FunctionDecl *Fn
3049 = S.ResolveAddressOfOverloadedFunction(Initializer,
3050 UnqualifiedTargetType,
3051 false, Found,
3052 &HadMultipleCandidates)) {
3053 Sequence.AddAddressOverloadResolutionStep(Fn, Found,
3054 HadMultipleCandidates);
3055 SourceType = Fn->getType();
3056 UnqualifiedSourceType = SourceType.getUnqualifiedType();
3057 } else if (!UnqualifiedTargetType->isRecordType()) {
3058 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3059 return true;
3060 }
3061 }
3062 return false;
3063}
3064
3065static void TryReferenceInitializationCore(Sema &S,
3066 const InitializedEntity &Entity,
3067 const InitializationKind &Kind,
3068 Expr *Initializer,
3069 QualType cv1T1, QualType T1,
3070 Qualifiers T1Quals,
3071 QualType cv2T2, QualType T2,
3072 Qualifiers T2Quals,
3073 InitializationSequence &Sequence);
3074
3075static void TryListInitialization(Sema &S,
3076 const InitializedEntity &Entity,
3077 const InitializationKind &Kind,
3078 InitListExpr *InitList,
3079 InitializationSequence &Sequence);
3080
3081/// \brief Attempt list initialization of a reference.
3082static void TryReferenceListInitialization(Sema &S,
3083 const InitializedEntity &Entity,
3084 const InitializationKind &Kind,
3085 InitListExpr *InitList,
3086 InitializationSequence &Sequence)
3087{
3088 // First, catch C++03 where this isn't possible.
3089 if (!S.getLangOptions().CPlusPlus0x) {
3090 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
3091 return;
3092 }
3093
3094 QualType DestType = Entity.getType();
3095 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3096 Qualifiers T1Quals;
3097 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
3098
3099 // Reference initialization via an initializer list works thus:
3100 // If the initializer list consists of a single element that is
3101 // reference-related to the referenced type, bind directly to that element
3102 // (possibly creating temporaries).
3103 // Otherwise, initialize a temporary with the initializer list and
3104 // bind to that.
3105 if (InitList->getNumInits() == 1) {
3106 Expr *Initializer = InitList->getInit(0);
3107 QualType cv2T2 = Initializer->getType();
3108 Qualifiers T2Quals;
3109 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
3110
3111 // If this fails, creating a temporary wouldn't work either.
3112 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3113 T1, Sequence))
3114 return;
3115
3116 SourceLocation DeclLoc = Initializer->getLocStart();
3117 bool dummy1, dummy2, dummy3;
3118 Sema::ReferenceCompareResult RefRelationship
3119 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, dummy1,
3120 dummy2, dummy3);
3121 if (RefRelationship >= Sema::Ref_Related) {
3122 // Try to bind the reference here.
3123 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3124 T1Quals, cv2T2, T2, T2Quals, Sequence);
3125 if (Sequence)
3126 Sequence.RewrapReferenceInitList(cv1T1, InitList);
3127 return;
3128 }
3129 }
3130
3131 // Not reference-related. Create a temporary and bind to that.
3132 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3133
3134 TryListInitialization(S, TempEntity, Kind, InitList, Sequence);
3135 if (Sequence) {
3136 if (DestType->isRValueReferenceType() ||
3137 (T1Quals.hasConst() && !T1Quals.hasVolatile()))
3138 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3139 else
3140 Sequence.SetFailed(
3141 InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
3142 }
3143}
3144
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003145/// \brief Attempt list initialization (C++0x [dcl.init.list])
3146static void TryListInitialization(Sema &S,
3147 const InitializedEntity &Entity,
3148 const InitializationKind &Kind,
3149 InitListExpr *InitList,
3150 InitializationSequence &Sequence) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003151 QualType DestType = Entity.getType();
3152
Sebastian Redl14b0c192011-09-24 17:48:00 +00003153 // C++ doesn't allow scalar initialization with more than one argument.
3154 // But C99 complex numbers are scalars and it makes sense there.
3155 if (S.getLangOptions().CPlusPlus && DestType->isScalarType() &&
3156 !DestType->isAnyComplexType() && InitList->getNumInits() > 1) {
3157 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
3158 return;
3159 }
Sebastian Redl14b0c192011-09-24 17:48:00 +00003160 if (DestType->isReferenceType()) {
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003161 TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence);
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003162 return;
Sebastian Redl14b0c192011-09-24 17:48:00 +00003163 }
3164 if (DestType->isRecordType() && !DestType->isAggregateType()) {
Sebastian Redl10f04a62011-12-22 14:44:04 +00003165 if (S.getLangOptions().CPlusPlus0x)
3166 TryConstructorInitialization(S, Entity, Kind, InitList->getInits(),
3167 InitList->getNumInits(), DestType, Sequence,
3168 /*FromInitList=*/true);
3169 else
3170 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003171 return;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003172 }
3173
Sebastian Redl14b0c192011-09-24 17:48:00 +00003174 InitListChecker CheckInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00003175 DestType, /*VerifyOnly=*/true,
3176 Kind.getKind() != InitializationKind::IK_Direct ||
3177 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00003178 if (CheckInitList.HadError()) {
3179 Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
3180 return;
3181 }
3182
3183 // Add the list initialization step with the built init list.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003184 Sequence.AddListInitializationStep(DestType);
3185}
Douglas Gregor20093b42009-12-09 23:02:17 +00003186
3187/// \brief Try a reference initialization that involves calling a conversion
3188/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00003189static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
3190 const InitializedEntity &Entity,
3191 const InitializationKind &Kind,
3192 Expr *Initializer,
3193 bool AllowRValues,
3194 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003195 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003196 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
3197 QualType T1 = cv1T1.getUnqualifiedType();
3198 QualType cv2T2 = Initializer->getType();
3199 QualType T2 = cv2T2.getUnqualifiedType();
3200
3201 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003202 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003203 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003204 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00003205 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003206 ObjCConversion,
3207 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00003208 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00003209 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00003210 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00003211 (void)ObjCLifetimeConversion;
3212
Douglas Gregor20093b42009-12-09 23:02:17 +00003213 // Build the candidate set directly in the initialization sequence
3214 // structure, so that it will persist if we fail.
3215 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3216 CandidateSet.clear();
3217
3218 // Determine whether we are allowed to call explicit constructors or
3219 // explicit conversion operators.
3220 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003221
Douglas Gregor20093b42009-12-09 23:02:17 +00003222 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003223 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
3224 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003225 // The type we're converting to is a class type. Enumerate its constructors
3226 // to see if there is a suitable conversion.
3227 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00003228
Douglas Gregor20093b42009-12-09 23:02:17 +00003229 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003230 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00003231 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003232 NamedDecl *D = *Con;
3233 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3234
Douglas Gregor20093b42009-12-09 23:02:17 +00003235 // Find the constructor (which may be a template).
3236 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003237 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00003238 if (ConstructorTmpl)
3239 Constructor = cast<CXXConstructorDecl>(
3240 ConstructorTmpl->getTemplatedDecl());
3241 else
John McCall9aa472c2010-03-19 07:35:19 +00003242 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003243
Douglas Gregor20093b42009-12-09 23:02:17 +00003244 if (!Constructor->isInvalidDecl() &&
3245 Constructor->isConvertingConstructor(AllowExplicit)) {
3246 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003247 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003248 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003249 &Initializer, 1, CandidateSet,
3250 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003251 else
John McCall9aa472c2010-03-19 07:35:19 +00003252 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00003253 &Initializer, 1, CandidateSet,
3254 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00003255 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003256 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003257 }
John McCall572fc622010-08-17 07:23:57 +00003258 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
3259 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00003261 const RecordType *T2RecordType = 0;
3262 if ((T2RecordType = T2->getAs<RecordType>()) &&
3263 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003264 // The type we're converting from is a class type, enumerate its conversion
3265 // functions.
3266 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
3267
John McCalleec51cf2010-01-20 00:46:10 +00003268 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00003269 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003270 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
3271 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003272 NamedDecl *D = *I;
3273 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3274 if (isa<UsingShadowDecl>(D))
3275 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003276
Douglas Gregor20093b42009-12-09 23:02:17 +00003277 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3278 CXXConversionDecl *Conv;
3279 if (ConvTemplate)
3280 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3281 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003282 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003283
Douglas Gregor20093b42009-12-09 23:02:17 +00003284 // If the conversion function doesn't return a reference type,
3285 // it can't be considered for this conversion unless we're allowed to
3286 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003287 // FIXME: Do we need to make sure that we only consider conversion
3288 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00003289 // break recursion.
3290 if ((AllowExplicit || !Conv->isExplicit()) &&
3291 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
3292 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003293 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003294 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00003295 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003296 else
John McCall9aa472c2010-03-19 07:35:19 +00003297 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00003298 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00003299 }
3300 }
3301 }
John McCall572fc622010-08-17 07:23:57 +00003302 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
3303 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003304
Douglas Gregor20093b42009-12-09 23:02:17 +00003305 SourceLocation DeclLoc = Initializer->getLocStart();
3306
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003307 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00003308 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003309 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003310 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00003311 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00003312
Douglas Gregor20093b42009-12-09 23:02:17 +00003313 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00003314
Chandler Carruth25ca4212011-02-25 19:41:05 +00003315 // This is the overload that will actually be used for the initialization, so
3316 // mark it as used.
3317 S.MarkDeclarationReferenced(DeclLoc, Function);
3318
Eli Friedman03981012009-12-11 02:42:07 +00003319 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00003320 if (isa<CXXConversionDecl>(Function))
3321 T2 = Function->getResultType();
3322 else
3323 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00003324
3325 // Add the user-defined conversion step.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003326 bool HadMultipleCandidates = (CandidateSet.size() > 1);
John McCall9aa472c2010-03-19 07:35:19 +00003327 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003328 T2.getNonLValueExprType(S.Context),
3329 HadMultipleCandidates);
Eli Friedman03981012009-12-11 02:42:07 +00003330
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003331 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00003332 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00003333 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003334 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00003335 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003336 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00003337 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00003338
Douglas Gregor20093b42009-12-09 23:02:17 +00003339 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003340 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003341 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00003342 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003343 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00003344 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00003345 NewDerivedToBase, NewObjCConversion,
3346 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00003347 if (NewRefRelationship == Sema::Ref_Incompatible) {
3348 // If the type we've converted to is not reference-related to the
3349 // type we're looking for, then there is another conversion step
3350 // we need to perform to produce a temporary of the right type
3351 // that we'll be binding to.
3352 ImplicitConversionSequence ICS;
3353 ICS.setStandard();
3354 ICS.Standard = Best->FinalConversion;
3355 T2 = ICS.Standard.getToType(2);
3356 Sequence.AddConversionSequenceStep(ICS, T2);
3357 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00003358 Sequence.AddDerivedToBaseCastStep(
3359 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00003361 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00003362 else if (NewObjCConversion)
3363 Sequence.AddObjCObjectConversionStep(
3364 S.Context.getQualifiedType(T1,
3365 T2.getNonReferenceType().getQualifiers()));
3366
Douglas Gregor20093b42009-12-09 23:02:17 +00003367 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00003368 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369
Douglas Gregor20093b42009-12-09 23:02:17 +00003370 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
3371 return OR_Success;
3372}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003373
Richard Smith83da2e72011-10-19 16:55:56 +00003374static void CheckCXX98CompatAccessibleCopy(Sema &S,
3375 const InitializedEntity &Entity,
3376 Expr *CurInitExpr);
3377
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003378/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
3379static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003380 const InitializedEntity &Entity,
3381 const InitializationKind &Kind,
3382 Expr *Initializer,
3383 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003384 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003385 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003386 Qualifiers T1Quals;
3387 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00003388 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00003389 Qualifiers T2Quals;
3390 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003391
Douglas Gregor20093b42009-12-09 23:02:17 +00003392 // If the initializer is the address of an overloaded function, try
3393 // to resolve the overloaded function. If all goes well, T2 is the
3394 // type of the resulting function.
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003395 if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
3396 T1, Sequence))
3397 return;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003398
Sebastian Redl13dc8f92011-11-27 16:50:07 +00003399 // Delegate everything else to a subfunction.
3400 TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
3401 T1Quals, cv2T2, T2, T2Quals, Sequence);
3402}
3403
3404/// \brief Reference initialization without resolving overloaded functions.
3405static void TryReferenceInitializationCore(Sema &S,
3406 const InitializedEntity &Entity,
3407 const InitializationKind &Kind,
3408 Expr *Initializer,
3409 QualType cv1T1, QualType T1,
3410 Qualifiers T1Quals,
3411 QualType cv2T2, QualType T2,
3412 Qualifiers T2Quals,
3413 InitializationSequence &Sequence) {
3414 QualType DestType = Entity.getType();
3415 SourceLocation DeclLoc = Initializer->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00003416 // Compute some basic properties of the types and the initializer.
3417 bool isLValueRef = DestType->isLValueReferenceType();
3418 bool isRValueRef = !isLValueRef;
3419 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003420 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003421 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003422 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00003423 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003424 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003425 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003426
Douglas Gregor20093b42009-12-09 23:02:17 +00003427 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003428 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00003429 // "cv2 T2" as follows:
3430 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003431 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00003432 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00003433 // Note the analogous bullet points for rvlaue refs to functions. Because
3434 // there are no function rvalues in C++, rvalue refs to functions are treated
3435 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00003436 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003437 bool T1Function = T1->isFunctionType();
3438 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003439 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003440 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003441 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003442 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003443 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00003444 // reference-compatible with "cv2 T2," or
3445 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003446 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003447 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003448 // can occur. However, we do pay attention to whether it is a bit-field
3449 // to decide whether we're actually binding to a temporary created from
3450 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00003451 if (DerivedToBase)
3452 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003453 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00003454 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00003455 else if (ObjCConversion)
3456 Sequence.AddObjCObjectConversionStep(
3457 S.Context.getQualifiedType(T1, T2Quals));
3458
Chandler Carruth5535c382010-01-12 20:32:25 +00003459 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00003460 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003461 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00003462 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00003463 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00003464 return;
3465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003466
3467 // - has a class type (i.e., T2 is a class type), where T1 is not
3468 // reference-related to T2, and can be implicitly converted to an
3469 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
3470 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00003471 // applicable conversion functions (13.3.1.6) and choosing the best
3472 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00003473 // If we have an rvalue ref to function type here, the rhs must be
3474 // an rvalue.
3475 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
3476 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003477 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00003478 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00003479 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00003480 Sequence);
3481 if (ConvOvlResult == OR_Success)
3482 return;
John McCall1d318332010-01-12 00:44:57 +00003483 if (ConvOvlResult != OR_No_Viable_Function) {
3484 Sequence.SetOverloadFailure(
3485 InitializationSequence::FK_ReferenceInitOverloadFailed,
3486 ConvOvlResult);
3487 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003488 }
3489 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003490
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003491 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00003492 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00003493 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003494 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00003495 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3496 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
3497 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00003498 Sequence.SetOverloadFailure(
3499 InitializationSequence::FK_ReferenceInitOverloadFailed,
3500 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003501 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00003502 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00003503 ? (RefRelationship == Sema::Ref_Related
3504 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
3505 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
3506 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003507
Douglas Gregor20093b42009-12-09 23:02:17 +00003508 return;
3509 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00003510
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003511 // - If the initializer expression
3512 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
3513 // "cv1 T1" is reference-compatible with "cv2 T2"
3514 // Note: functions are handled below.
3515 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003516 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003517 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003518 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003519 (InitCategory.isXValue() ||
3520 (InitCategory.isPRValue() && T2->isRecordType()) ||
3521 (InitCategory.isPRValue() && T2->isArrayType()))) {
3522 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
3523 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00003524 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
3525 // compiler the freedom to perform a copy here or bind to the
3526 // object, while C++0x requires that we bind directly to the
3527 // object. Hence, we always bind to the object without making an
3528 // extra copy. However, in C++03 requires that we check for the
3529 // presence of a suitable copy constructor:
3530 //
3531 // The constructor that would be used to make the copy shall
3532 // be callable whether or not the copy is actually done.
Francois Pichet62ec1f22011-09-17 17:15:52 +00003533 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt)
Douglas Gregor523d46a2010-04-18 07:40:54 +00003534 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Richard Smith83da2e72011-10-19 16:55:56 +00003535 else if (S.getLangOptions().CPlusPlus0x)
3536 CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
Douglas Gregor20093b42009-12-09 23:02:17 +00003537 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003538
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003539 if (DerivedToBase)
3540 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
3541 ValueKind);
3542 else if (ObjCConversion)
3543 Sequence.AddObjCObjectConversionStep(
3544 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003545
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003546 if (T1Quals != T2Quals)
3547 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003548 Sequence.AddReferenceBindingStep(cv1T1,
Peter Collingbourne65bfd682011-11-13 00:51:30 +00003549 /*bindingTemporary=*/InitCategory.isPRValue());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003550 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003551 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003552
3553 // - has a class type (i.e., T2 is a class type), where T1 is not
3554 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003555 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
3556 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00003557 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003558 if (RefRelationship == Sema::Ref_Incompatible) {
3559 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
3560 Kind, Initializer,
3561 /*AllowRValues=*/true,
3562 Sequence);
3563 if (ConvOvlResult)
3564 Sequence.SetOverloadFailure(
3565 InitializationSequence::FK_ReferenceInitOverloadFailed,
3566 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003567
Douglas Gregor20093b42009-12-09 23:02:17 +00003568 return;
3569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003570
Douglas Gregor20093b42009-12-09 23:02:17 +00003571 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3572 return;
3573 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003574
3575 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003576 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003577 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003578 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003579
Douglas Gregor20093b42009-12-09 23:02:17 +00003580 // Determine whether we are allowed to call explicit constructors or
3581 // explicit conversion operators.
3582 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003583
3584 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3585
John McCallf85e1932011-06-15 23:02:42 +00003586 ImplicitConversionSequence ICS
3587 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003588 /*SuppressUserConversions*/ false,
3589 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003590 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003591 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3592 /*AllowObjCWritebackConversion=*/false);
3593
3594 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003595 // FIXME: Use the conversion function set stored in ICS to turn
3596 // this into an overloading ambiguity diagnostic. However, we need
3597 // to keep that set as an OverloadCandidateSet rather than as some
3598 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003599 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3600 Sequence.SetOverloadFailure(
3601 InitializationSequence::FK_ReferenceInitOverloadFailed,
3602 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003603 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3604 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003605 else
3606 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003607 return;
John McCallf85e1932011-06-15 23:02:42 +00003608 } else {
3609 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003610 }
3611
3612 // [...] If T1 is reference-related to T2, cv1 must be the
3613 // same cv-qualification as, or greater cv-qualification
3614 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003615 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3616 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003617 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003618 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003619 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3620 return;
3621 }
3622
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003623 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003624 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003625 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003626 InitCategory.isLValue()) {
3627 Sequence.SetFailed(
3628 InitializationSequence::FK_RValueReferenceBindingToLValue);
3629 return;
3630 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003631
Douglas Gregor20093b42009-12-09 23:02:17 +00003632 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3633 return;
3634}
3635
3636/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003637/// (C++ [dcl.init.string], C99 6.7.8).
3638static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003639 const InitializedEntity &Entity,
3640 const InitializationKind &Kind,
3641 Expr *Initializer,
3642 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003643 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003644}
3645
Douglas Gregor71d17402009-12-15 00:01:57 +00003646/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003647static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003648 const InitializedEntity &Entity,
3649 const InitializationKind &Kind,
3650 InitializationSequence &Sequence) {
3651 // C++ [dcl.init]p5:
3652 //
3653 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003654 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003655
Douglas Gregor71d17402009-12-15 00:01:57 +00003656 // -- if T is an array type, then each element is value-initialized;
3657 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3658 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003659
Douglas Gregor71d17402009-12-15 00:01:57 +00003660 if (const RecordType *RT = T->getAs<RecordType>()) {
3661 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3662 // -- if T is a class type (clause 9) with a user-declared
3663 // constructor (12.1), then the default constructor for T is
3664 // called (and the initialization is ill-formed if T has no
3665 // accessible default constructor);
3666 //
3667 // FIXME: we really want to refer to a single subobject of the array,
3668 // but Entity doesn't have a way to capture that (yet).
3669 if (ClassDecl->hasUserDeclaredConstructor())
3670 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003671
Douglas Gregor16006c92009-12-16 18:50:27 +00003672 // -- if T is a (possibly cv-qualified) non-union class type
3673 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003674 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003675 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003676 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003677 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003678 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003679 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003680 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003681 }
3682 }
3683
Douglas Gregord6542d82009-12-22 15:35:07 +00003684 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003685}
3686
Douglas Gregor99a2e602009-12-16 01:38:02 +00003687/// \brief Attempt default initialization (C++ [dcl.init]p6).
3688static void TryDefaultInitialization(Sema &S,
3689 const InitializedEntity &Entity,
3690 const InitializationKind &Kind,
3691 InitializationSequence &Sequence) {
3692 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003693
Douglas Gregor99a2e602009-12-16 01:38:02 +00003694 // C++ [dcl.init]p6:
3695 // To default-initialize an object of type T means:
3696 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003697 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3698
Douglas Gregor99a2e602009-12-16 01:38:02 +00003699 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3700 // constructor for T is called (and the initialization is ill-formed if
3701 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003702 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003703 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3704 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003705 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003706
Douglas Gregor99a2e602009-12-16 01:38:02 +00003707 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003708
Douglas Gregor99a2e602009-12-16 01:38:02 +00003709 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003710 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003711 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003712 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003713 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003714 return;
3715 }
3716
3717 // If the destination type has a lifetime property, zero-initialize it.
3718 if (DestType.getQualifiers().hasObjCLifetime()) {
3719 Sequence.AddZeroInitializationStep(Entity.getType());
3720 return;
3721 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003722}
3723
Douglas Gregor20093b42009-12-09 23:02:17 +00003724/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3725/// which enumerates all conversion functions and performs overload resolution
3726/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003727static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003728 const InitializedEntity &Entity,
3729 const InitializationKind &Kind,
3730 Expr *Initializer,
3731 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003732 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003733 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3734 QualType SourceType = Initializer->getType();
3735 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3736 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003737
Douglas Gregor4a520a22009-12-14 17:27:33 +00003738 // Build the candidate set directly in the initialization sequence
3739 // structure, so that it will persist if we fail.
3740 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3741 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003742
Douglas Gregor4a520a22009-12-14 17:27:33 +00003743 // Determine whether we are allowed to call explicit constructors or
3744 // explicit conversion operators.
3745 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003746
Douglas Gregor4a520a22009-12-14 17:27:33 +00003747 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3748 // The type we're converting to is a class type. Enumerate its constructors
3749 // to see if there is a suitable conversion.
3750 CXXRecordDecl *DestRecordDecl
3751 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003752
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003753 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003754 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003755 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003756 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003757 Con != ConEnd; ++Con) {
3758 NamedDecl *D = *Con;
3759 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003760
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003761 // Find the constructor (which may be a template).
3762 CXXConstructorDecl *Constructor = 0;
3763 FunctionTemplateDecl *ConstructorTmpl
3764 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003765 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003766 Constructor = cast<CXXConstructorDecl>(
3767 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003768 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003769 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003771 if (!Constructor->isInvalidDecl() &&
3772 Constructor->isConvertingConstructor(AllowExplicit)) {
3773 if (ConstructorTmpl)
3774 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3775 /*ExplicitArgs*/ 0,
3776 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003777 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003778 else
3779 S.AddOverloadCandidate(Constructor, FoundDecl,
3780 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003781 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003782 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003783 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003784 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003785 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003786
3787 SourceLocation DeclLoc = Initializer->getLocStart();
3788
Douglas Gregor4a520a22009-12-14 17:27:33 +00003789 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3790 // The type we're converting from is a class type, enumerate its conversion
3791 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003792
Eli Friedman33c2da92009-12-20 22:12:03 +00003793 // We can only enumerate the conversion functions for a complete type; if
3794 // the type isn't complete, simply skip this step.
3795 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3796 CXXRecordDecl *SourceRecordDecl
3797 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003798
John McCalleec51cf2010-01-20 00:46:10 +00003799 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003800 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003801 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003802 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003803 I != E; ++I) {
3804 NamedDecl *D = *I;
3805 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3806 if (isa<UsingShadowDecl>(D))
3807 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003808
Eli Friedman33c2da92009-12-20 22:12:03 +00003809 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3810 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003811 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003812 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003813 else
John McCall32daa422010-03-31 01:36:47 +00003814 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003815
Eli Friedman33c2da92009-12-20 22:12:03 +00003816 if (AllowExplicit || !Conv->isExplicit()) {
3817 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003818 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003819 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003820 CandidateSet);
3821 else
John McCall9aa472c2010-03-19 07:35:19 +00003822 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003823 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003824 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003825 }
3826 }
3827 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003828
3829 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003830 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003831 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003832 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003833 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003834 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003835 Result);
3836 return;
3837 }
John McCall1d318332010-01-12 00:44:57 +00003838
Douglas Gregor4a520a22009-12-14 17:27:33 +00003839 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003840 S.MarkDeclarationReferenced(DeclLoc, Function);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003841 bool HadMultipleCandidates = (CandidateSet.size() > 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842
Douglas Gregor4a520a22009-12-14 17:27:33 +00003843 if (isa<CXXConstructorDecl>(Function)) {
3844 // Add the user-defined conversion step. Any cv-qualification conversion is
3845 // subsumed by the initialization.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003846 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3847 HadMultipleCandidates);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003848 return;
3849 }
3850
3851 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003852 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003853 if (ConvType->getAs<RecordType>()) {
3854 // If we're converting to a class type, there may be an copy if
3855 // the resulting temporary object (possible to create an object of
3856 // a base class type). That copy is not a separate conversion, so
3857 // we just make a note of the actual destination type (possibly a
3858 // base class of the type returned by the conversion function) and
3859 // let the user-defined conversion step handle the conversion.
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003860 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType,
3861 HadMultipleCandidates);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003862 return;
3863 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003864
Abramo Bagnara22c107b2011-11-19 11:44:21 +00003865 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType,
3866 HadMultipleCandidates);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003867
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003868 // If the conversion following the call to the conversion function
3869 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003870 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3871 Best->FinalConversion.Third) {
3872 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003873 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003874 ICS.Standard = Best->FinalConversion;
3875 Sequence.AddConversionSequenceStep(ICS, DestType);
3876 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003877}
3878
John McCallf85e1932011-06-15 23:02:42 +00003879/// The non-zero enum values here are indexes into diagnostic alternatives.
3880enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3881
3882/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003883static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3884 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003885 // Skip parens.
3886 e = e->IgnoreParens();
3887
3888 // Skip address-of nodes.
3889 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3890 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003891 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003892
3893 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003894 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3895 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003896 case CK_Dependent:
3897 case CK_BitCast:
3898 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003899 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003900 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003901
3902 case CK_ArrayToPointerDecay:
3903 return IIK_nonscalar;
3904
3905 case CK_NullToPointer:
3906 return IIK_okay;
3907
3908 default:
3909 break;
3910 }
3911
3912 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003913 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3914 if (!isAddressOf) return IIK_nonlocal;
3915
3916 VarDecl *var;
3917 if (isa<DeclRefExpr>(e)) {
3918 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3919 if (!var) return IIK_nonlocal;
3920 } else {
3921 var = cast<BlockDeclRefExpr>(e)->getDecl();
3922 }
3923
3924 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003925
3926 // If we have a conditional operator, check both sides.
3927 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003928 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003929 return iik;
3930
John McCallc03fa492011-06-27 23:59:58 +00003931 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003932
3933 // These are never scalar.
3934 } else if (isa<ArraySubscriptExpr>(e)) {
3935 return IIK_nonscalar;
3936
3937 // Otherwise, it needs to be a null pointer constant.
3938 } else {
3939 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3940 ? IIK_okay : IIK_nonlocal);
3941 }
3942
3943 return IIK_nonlocal;
3944}
3945
3946/// Check whether the given expression is a valid operand for an
3947/// indirect copy/restore.
3948static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3949 assert(src->isRValue());
3950
John McCallc03fa492011-06-27 23:59:58 +00003951 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003952 if (iik == IIK_okay) return;
3953
3954 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3955 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3956 << src->getSourceRange();
3957}
3958
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003959/// \brief Determine whether we have compatible array types for the
3960/// purposes of GNU by-copy array initialization.
3961static bool hasCompatibleArrayTypes(ASTContext &Context,
3962 const ArrayType *Dest,
3963 const ArrayType *Source) {
3964 // If the source and destination array types are equivalent, we're
3965 // done.
3966 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3967 return true;
3968
3969 // Make sure that the element types are the same.
3970 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3971 return false;
3972
3973 // The only mismatch we allow is when the destination is an
3974 // incomplete array type and the source is a constant array type.
3975 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3976}
3977
John McCallf85e1932011-06-15 23:02:42 +00003978static bool tryObjCWritebackConversion(Sema &S,
3979 InitializationSequence &Sequence,
3980 const InitializedEntity &Entity,
3981 Expr *Initializer) {
3982 bool ArrayDecay = false;
3983 QualType ArgType = Initializer->getType();
3984 QualType ArgPointee;
3985 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3986 ArrayDecay = true;
3987 ArgPointee = ArgArrayType->getElementType();
3988 ArgType = S.Context.getPointerType(ArgPointee);
3989 }
3990
3991 // Handle write-back conversion.
3992 QualType ConvertedArgType;
3993 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3994 ConvertedArgType))
3995 return false;
3996
3997 // We should copy unless we're passing to an argument explicitly
3998 // marked 'out'.
3999 bool ShouldCopy = true;
4000 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4001 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4002
4003 // Do we need an lvalue conversion?
4004 if (ArrayDecay || Initializer->isGLValue()) {
4005 ImplicitConversionSequence ICS;
4006 ICS.setStandard();
4007 ICS.Standard.setAsIdentityConversion();
4008
4009 QualType ResultType;
4010 if (ArrayDecay) {
4011 ICS.Standard.First = ICK_Array_To_Pointer;
4012 ResultType = S.Context.getPointerType(ArgPointee);
4013 } else {
4014 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4015 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
4016 }
4017
4018 Sequence.AddConversionSequenceStep(ICS, ResultType);
4019 }
4020
4021 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
4022 return true;
4023}
4024
Douglas Gregor20093b42009-12-09 23:02:17 +00004025InitializationSequence::InitializationSequence(Sema &S,
4026 const InitializedEntity &Entity,
4027 const InitializationKind &Kind,
4028 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00004029 unsigned NumArgs)
4030 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004031 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004032
Douglas Gregor20093b42009-12-09 23:02:17 +00004033 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004034 // The semantics of initializers are as follows. The destination type is
4035 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00004036 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004037 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00004038 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004039 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004040
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004041 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00004042 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
4043 SequenceKind = DependentSequence;
4044 return;
4045 }
4046
Sebastian Redl7491c492011-06-05 13:59:11 +00004047 // Almost everything is a normal sequence.
4048 setSequenceKind(NormalSequence);
4049
John McCall241d5582010-12-07 22:54:16 +00004050 for (unsigned I = 0; I != NumArgs; ++I)
John McCall32509f12011-11-15 01:35:18 +00004051 if (Args[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall5acb0c92011-10-17 18:40:02 +00004052 // FIXME: should we be doing this here?
John McCall32509f12011-11-15 01:35:18 +00004053 ExprResult result = S.CheckPlaceholderExpr(Args[I]);
4054 if (result.isInvalid()) {
4055 SetFailed(FK_PlaceholderType);
4056 return;
John McCall5acb0c92011-10-17 18:40:02 +00004057 }
John McCall32509f12011-11-15 01:35:18 +00004058 Args[I] = result.take();
John Wiegley429bb272011-04-08 18:41:53 +00004059 }
John McCall241d5582010-12-07 22:54:16 +00004060
John McCall5acb0c92011-10-17 18:40:02 +00004061
Douglas Gregor20093b42009-12-09 23:02:17 +00004062 QualType SourceType;
4063 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00004064 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004065 Initializer = Args[0];
4066 if (!isa<InitListExpr>(Initializer))
4067 SourceType = Initializer->getType();
4068 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004069
4070 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00004071 // list-initialized (8.5.4).
4072 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004073 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004074 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00004075 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004076
Douglas Gregor20093b42009-12-09 23:02:17 +00004077 // - If the destination type is a reference type, see 8.5.3.
4078 if (DestType->isReferenceType()) {
4079 // C++0x [dcl.init.ref]p1:
4080 // A variable declared to be a T& or T&&, that is, "reference to type T"
4081 // (8.3.2), shall be initialized by an object, or function, of type T or
4082 // by an object that can be converted into a T.
4083 // (Therefore, multiple arguments are not permitted.)
4084 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004085 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00004086 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004087 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004088 return;
4089 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004090
Douglas Gregor20093b42009-12-09 23:02:17 +00004091 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004092 if (Kind.getKind() == InitializationKind::IK_Value ||
4093 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004094 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004095 return;
4096 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004097
Douglas Gregor99a2e602009-12-16 01:38:02 +00004098 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00004099 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004100 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004101 return;
4102 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004103
John McCallce6c9b72011-02-21 07:22:22 +00004104 // - If the destination type is an array of characters, an array of
4105 // char16_t, an array of char32_t, or an array of wchar_t, and the
4106 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004107 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00004108 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004109 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
John McCall73076432012-01-05 00:13:19 +00004110 if (Initializer && isa<VariableArrayType>(DestAT)) {
4111 SetFailed(FK_VariableLengthArrayHasInitializer);
4112 return;
4113 }
4114
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004115 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004116 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00004117 return;
4118 }
4119
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004120 // Note: as an GNU C extension, we allow initialization of an
4121 // array from a compound literal that creates an array of the same
4122 // type, so long as the initializer has no side effects.
4123 if (!S.getLangOptions().CPlusPlus && Initializer &&
4124 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
4125 Initializer->getType()->isArrayType()) {
4126 const ArrayType *SourceAT
4127 = Context.getAsArrayType(Initializer->getType());
4128 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004129 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004130 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004131 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004132 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004133 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004134 }
4135 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004136 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00004137 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004138 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004139
Douglas Gregor20093b42009-12-09 23:02:17 +00004140 return;
4141 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004142
John McCallf85e1932011-06-15 23:02:42 +00004143 // Determine whether we should consider writeback conversions for
4144 // Objective-C ARC.
4145 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
4146 Entity.getKind() == InitializedEntity::EK_Parameter;
4147
4148 // We're at the end of the line for C: it's either a write-back conversion
4149 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004150 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00004151 // If allowed, check whether this is an Objective-C writeback conversion.
4152 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004153 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00004154 return;
4155 }
4156
4157 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004158 AddCAssignmentStep(DestType);
4159 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004160 return;
4161 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004162
John McCallf85e1932011-06-15 23:02:42 +00004163 assert(S.getLangOptions().CPlusPlus);
4164
Douglas Gregor20093b42009-12-09 23:02:17 +00004165 // - If the destination type is a (possibly cv-qualified) class type:
4166 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004167 // - If the initialization is direct-initialization, or if it is
4168 // copy-initialization where the cv-unqualified version of the
4169 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00004170 // class of the destination, constructors are considered. [...]
4171 if (Kind.getKind() == InitializationKind::IK_Direct ||
4172 (Kind.getKind() == InitializationKind::IK_Copy &&
4173 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
4174 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004175 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004176 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004177 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00004178 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004179 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00004180 // used) to a derived class thereof are enumerated as described in
4181 // 13.3.1.4, and the best one is chosen through overload resolution
4182 // (13.3).
4183 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004184 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00004185 return;
4186 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004187
Douglas Gregor99a2e602009-12-16 01:38:02 +00004188 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004189 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00004190 return;
4191 }
4192 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004193
4194 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00004195 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00004196 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004197 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
4198 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004199 return;
4200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004201
Douglas Gregor20093b42009-12-09 23:02:17 +00004202 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00004203 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00004204 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004205 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00004206 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00004207
4208 ImplicitConversionSequence ICS
4209 = S.TryImplicitConversion(Initializer, Entity.getType(),
4210 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00004211 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004212 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00004213 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
4214 allowObjCWritebackConversion);
4215
4216 if (ICS.isStandard() &&
4217 ICS.Standard.Second == ICK_Writeback_Conversion) {
4218 // Objective-C ARC writeback conversion.
4219
4220 // We should copy unless we're passing to an argument explicitly
4221 // marked 'out'.
4222 bool ShouldCopy = true;
4223 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
4224 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
4225
4226 // If there was an lvalue adjustment, add it as a separate conversion.
4227 if (ICS.Standard.First == ICK_Array_To_Pointer ||
4228 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4229 ImplicitConversionSequence LvalueICS;
4230 LvalueICS.setStandard();
4231 LvalueICS.Standard.setAsIdentityConversion();
4232 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
4233 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004234 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00004235 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004236
4237 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00004238 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004239 DeclAccessPair dap;
4240 if (Initializer->getType() == Context.OverloadTy &&
4241 !S.ResolveAddressOfOverloadedFunction(Initializer
4242 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004243 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00004244 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004245 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00004246 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004247 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00004248
Rafael Espindola12ce0a02011-07-14 22:58:04 +00004249 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00004250 }
Douglas Gregor20093b42009-12-09 23:02:17 +00004251}
4252
4253InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004254 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004255 StepEnd = Steps.end();
4256 Step != StepEnd; ++Step)
4257 Step->Destroy();
4258}
4259
4260//===----------------------------------------------------------------------===//
4261// Perform initialization
4262//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004264getAssignmentAction(const InitializedEntity &Entity) {
4265 switch(Entity.getKind()) {
4266 case InitializedEntity::EK_Variable:
4267 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00004268 case InitializedEntity::EK_Exception:
4269 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004270 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004271 return Sema::AA_Initializing;
4272
4273 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00004275 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
4276 return Sema::AA_Sending;
4277
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004278 return Sema::AA_Passing;
4279
4280 case InitializedEntity::EK_Result:
4281 return Sema::AA_Returning;
4282
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004283 case InitializedEntity::EK_Temporary:
4284 // FIXME: Can we tell apart casting vs. converting?
4285 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004286
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004287 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004288 case InitializedEntity::EK_ArrayElement:
4289 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004290 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004291 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004292 return Sema::AA_Initializing;
4293 }
4294
David Blaikie7530c032012-01-17 06:56:22 +00004295 llvm_unreachable("Invalid EntityKind!");
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004296}
4297
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004298/// \brief Whether we should binding a created object as a temporary when
4299/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00004300static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004301 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004302 case InitializedEntity::EK_ArrayElement:
4303 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00004304 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004305 case InitializedEntity::EK_New:
4306 case InitializedEntity::EK_Variable:
4307 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004308 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00004309 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004310 case InitializedEntity::EK_ComplexElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00004311 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004312 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004313 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004314
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004315 case InitializedEntity::EK_Parameter:
4316 case InitializedEntity::EK_Temporary:
4317 return true;
4318 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004319
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004320 llvm_unreachable("missed an InitializedEntity kind?");
4321}
4322
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004323/// \brief Whether the given entity, when initialized with an object
4324/// created for that initialization, requires destruction.
4325static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
4326 switch (Entity.getKind()) {
4327 case InitializedEntity::EK_Member:
4328 case InitializedEntity::EK_Result:
4329 case InitializedEntity::EK_New:
4330 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00004331 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004332 case InitializedEntity::EK_VectorElement:
Eli Friedman0c706c22011-09-19 23:17:44 +00004333 case InitializedEntity::EK_ComplexElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00004334 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004335 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004336
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004337 case InitializedEntity::EK_Variable:
4338 case InitializedEntity::EK_Parameter:
4339 case InitializedEntity::EK_Temporary:
4340 case InitializedEntity::EK_ArrayElement:
4341 case InitializedEntity::EK_Exception:
4342 return true;
4343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004344
4345 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004346}
4347
Richard Smith83da2e72011-10-19 16:55:56 +00004348/// \brief Look for copy and move constructors and constructor templates, for
4349/// copying an object via direct-initialization (per C++11 [dcl.init]p16).
4350static void LookupCopyAndMoveConstructors(Sema &S,
4351 OverloadCandidateSet &CandidateSet,
4352 CXXRecordDecl *Class,
4353 Expr *CurInitExpr) {
4354 DeclContext::lookup_iterator Con, ConEnd;
4355 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
4356 Con != ConEnd; ++Con) {
4357 CXXConstructorDecl *Constructor = 0;
4358
4359 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
4360 // Handle copy/moveconstructors, only.
4361 if (!Constructor || Constructor->isInvalidDecl() ||
4362 !Constructor->isCopyOrMoveConstructor() ||
4363 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4364 continue;
4365
4366 DeclAccessPair FoundDecl
4367 = DeclAccessPair::make(Constructor, Constructor->getAccess());
4368 S.AddOverloadCandidate(Constructor, FoundDecl,
4369 &CurInitExpr, 1, CandidateSet);
4370 continue;
4371 }
4372
4373 // Handle constructor templates.
4374 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
4375 if (ConstructorTmpl->isInvalidDecl())
4376 continue;
4377
4378 Constructor = cast<CXXConstructorDecl>(
4379 ConstructorTmpl->getTemplatedDecl());
4380 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
4381 continue;
4382
4383 // FIXME: Do we need to limit this to copy-constructor-like
4384 // candidates?
4385 DeclAccessPair FoundDecl
4386 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
4387 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
4388 &CurInitExpr, 1, CandidateSet, true);
4389 }
4390}
4391
4392/// \brief Get the location at which initialization diagnostics should appear.
4393static SourceLocation getInitializationLoc(const InitializedEntity &Entity,
4394 Expr *Initializer) {
4395 switch (Entity.getKind()) {
4396 case InitializedEntity::EK_Result:
4397 return Entity.getReturnLoc();
4398
4399 case InitializedEntity::EK_Exception:
4400 return Entity.getThrowLoc();
4401
4402 case InitializedEntity::EK_Variable:
4403 return Entity.getDecl()->getLocation();
4404
4405 case InitializedEntity::EK_ArrayElement:
4406 case InitializedEntity::EK_Member:
4407 case InitializedEntity::EK_Parameter:
4408 case InitializedEntity::EK_Temporary:
4409 case InitializedEntity::EK_New:
4410 case InitializedEntity::EK_Base:
4411 case InitializedEntity::EK_Delegating:
4412 case InitializedEntity::EK_VectorElement:
4413 case InitializedEntity::EK_ComplexElement:
4414 case InitializedEntity::EK_BlockElement:
4415 return Initializer->getLocStart();
4416 }
4417 llvm_unreachable("missed an InitializedEntity kind?");
4418}
4419
Douglas Gregor523d46a2010-04-18 07:40:54 +00004420/// \brief Make a (potentially elidable) temporary copy of the object
4421/// provided by the given initializer by calling the appropriate copy
4422/// constructor.
4423///
4424/// \param S The Sema object used for type-checking.
4425///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00004426/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00004427/// the type of the initializer expression or a superclass thereof.
4428///
4429/// \param Enter The entity being initialized.
4430///
4431/// \param CurInit The initializer expression.
4432///
4433/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
4434/// is permitted in C++03 (but not C++0x) when binding a reference to
4435/// an rvalue.
4436///
4437/// \returns An expression that copies the initializer expression into
4438/// a temporary object, or an error expression if a copy could not be
4439/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00004440static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004441 QualType T,
4442 const InitializedEntity &Entity,
4443 ExprResult CurInit,
4444 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004445 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00004446 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004447 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00004448 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00004449 Class = cast<CXXRecordDecl>(Record->getDecl());
4450 if (!Class)
4451 return move(CurInit);
4452
Douglas Gregorf5d8f462011-01-21 18:05:27 +00004453 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00004454 // When certain criteria are met, an implementation is allowed to
4455 // omit the copy/move construction of a class object, even if the
4456 // copy/move constructor and/or destructor for the object have
4457 // side effects. [...]
4458 // - when a temporary class object that has not been bound to a
4459 // reference (12.2) would be copied/moved to a class object
4460 // with the same cv-unqualified type, the copy/move operation
4461 // can be omitted by constructing the temporary object
4462 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004463 //
Douglas Gregor2f599792010-04-02 18:24:57 +00004464 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004465 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004466 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004467 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00004468 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Richard Smith83da2e72011-10-19 16:55:56 +00004469 SourceLocation Loc = getInitializationLoc(Entity, CurInit.get());
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004470
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004471 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00004472 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
4473 return move(CurInit);
4474
Douglas Gregorcc15f012011-01-21 19:38:21 +00004475 // Perform overload resolution using the class's copy/move constructors.
Richard Smith83da2e72011-10-19 16:55:56 +00004476 // Only consider constructors and constructor templates. Per
4477 // C++0x [dcl.init]p16, second bullet to class types, this initialization
4478 // is direct-initialization.
John McCall5769d612010-02-08 23:07:23 +00004479 OverloadCandidateSet CandidateSet(Loc);
Richard Smith83da2e72011-10-19 16:55:56 +00004480 LookupCopyAndMoveConstructors(S, CandidateSet, Class, CurInitExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004481
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004482 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4483
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004484 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00004485 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004486 case OR_Success:
4487 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004488
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004489 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004490 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
4491 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
4492 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004493 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004494 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004495 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004496 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00004497 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004498 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004499
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004500 case OR_Ambiguous:
4501 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004502 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004503 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004504 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004505 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004506
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004507 case OR_Deleted:
4508 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004509 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004510 << CurInitExpr->getSourceRange();
4511 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004512 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004513 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004514 }
4515
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004516 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004517 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004518 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004519
Anders Carlsson9a68a672010-04-21 18:47:17 +00004520 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004521 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004522
4523 if (IsExtraneousCopy) {
4524 // If this is a totally extraneous copy for C++03 reference
4525 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004526 // expression. We don't generate an (elided) copy operation here
4527 // because doing so would require us to pass down a flag to avoid
4528 // infinite recursion, where each step adds another extraneous,
4529 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004530
Douglas Gregor2559a702010-04-18 07:57:34 +00004531 // Instantiate the default arguments of any extra parameters in
4532 // the selected copy constructor, as if we were going to create a
4533 // proper call to the copy constructor.
4534 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4535 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4536 if (S.RequireCompleteType(Loc, Parm->getType(),
4537 S.PDiag(diag::err_call_incomplete_argument)))
4538 break;
4539
4540 // Build the default argument expression; we don't actually care
4541 // if this succeeds or not, because this routine will complain
4542 // if there was a problem.
4543 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4544 }
4545
Douglas Gregor523d46a2010-04-18 07:40:54 +00004546 return S.Owned(CurInitExpr);
4547 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004548
Chandler Carruth25ca4212011-02-25 19:41:05 +00004549 S.MarkDeclarationReferenced(Loc, Constructor);
4550
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004551 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004552 // constructor call (we might have derived-to-base conversions, or
4553 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004554 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004555 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004556 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004557
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004558 // Actually perform the constructor call.
4559 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004560 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004561 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00004562 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004563 CXXConstructExpr::CK_Complete,
4564 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004566 // If we're supposed to bind temporaries, do so.
4567 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4568 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4569 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004570}
Douglas Gregor20093b42009-12-09 23:02:17 +00004571
Richard Smith83da2e72011-10-19 16:55:56 +00004572/// \brief Check whether elidable copy construction for binding a reference to
4573/// a temporary would have succeeded if we were building in C++98 mode, for
4574/// -Wc++98-compat.
4575static void CheckCXX98CompatAccessibleCopy(Sema &S,
4576 const InitializedEntity &Entity,
4577 Expr *CurInitExpr) {
4578 assert(S.getLangOptions().CPlusPlus0x);
4579
4580 const RecordType *Record = CurInitExpr->getType()->getAs<RecordType>();
4581 if (!Record)
4582 return;
4583
4584 SourceLocation Loc = getInitializationLoc(Entity, CurInitExpr);
4585 if (S.Diags.getDiagnosticLevel(diag::warn_cxx98_compat_temp_copy, Loc)
4586 == DiagnosticsEngine::Ignored)
4587 return;
4588
4589 // Find constructors which would have been considered.
4590 OverloadCandidateSet CandidateSet(Loc);
4591 LookupCopyAndMoveConstructors(
4592 S, CandidateSet, cast<CXXRecordDecl>(Record->getDecl()), CurInitExpr);
4593
4594 // Perform overload resolution.
4595 OverloadCandidateSet::iterator Best;
4596 OverloadingResult OR = CandidateSet.BestViableFunction(S, Loc, Best);
4597
4598 PartialDiagnostic Diag = S.PDiag(diag::warn_cxx98_compat_temp_copy)
4599 << OR << (int)Entity.getKind() << CurInitExpr->getType()
4600 << CurInitExpr->getSourceRange();
4601
4602 switch (OR) {
4603 case OR_Success:
4604 S.CheckConstructorAccess(Loc, cast<CXXConstructorDecl>(Best->Function),
4605 Best->FoundDecl.getAccess(), Diag);
4606 // FIXME: Check default arguments as far as that's possible.
4607 break;
4608
4609 case OR_No_Viable_Function:
4610 S.Diag(Loc, Diag);
4611 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
4612 break;
4613
4614 case OR_Ambiguous:
4615 S.Diag(Loc, Diag);
4616 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
4617 break;
4618
4619 case OR_Deleted:
4620 S.Diag(Loc, Diag);
4621 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
4622 << 1 << Best->Function->isDeleted();
4623 break;
4624 }
4625}
4626
Douglas Gregora41a8c52010-04-22 00:20:18 +00004627void InitializationSequence::PrintInitLocationNote(Sema &S,
4628 const InitializedEntity &Entity) {
4629 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4630 if (Entity.getDecl()->getLocation().isInvalid())
4631 return;
4632
4633 if (Entity.getDecl()->getDeclName())
4634 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4635 << Entity.getDecl()->getDeclName();
4636 else
4637 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4638 }
4639}
4640
Sebastian Redl3b802322011-07-14 19:07:55 +00004641static bool isReferenceBinding(const InitializationSequence::Step &s) {
4642 return s.Kind == InitializationSequence::SK_BindReference ||
4643 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4644}
4645
Sebastian Redl10f04a62011-12-22 14:44:04 +00004646static ExprResult
4647PerformConstructorInitialization(Sema &S,
4648 const InitializedEntity &Entity,
4649 const InitializationKind &Kind,
4650 MultiExprArg Args,
4651 const InitializationSequence::Step& Step,
4652 bool &ConstructorInitRequiresZeroInit) {
4653 unsigned NumArgs = Args.size();
4654 CXXConstructorDecl *Constructor
4655 = cast<CXXConstructorDecl>(Step.Function.Function);
4656 bool HadMultipleCandidates = Step.Function.HadMultipleCandidates;
4657
4658 // Build a call to the selected constructor.
4659 ASTOwningVector<Expr*> ConstructorArgs(S);
4660 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4661 ? Kind.getEqualLoc()
4662 : Kind.getLocation();
4663
4664 if (Kind.getKind() == InitializationKind::IK_Default) {
4665 // Force even a trivial, implicit default constructor to be
4666 // semantically checked. We do this explicitly because we don't build
4667 // the definition for completely trivial constructors.
4668 CXXRecordDecl *ClassDecl = Constructor->getParent();
4669 assert(ClassDecl && "No parent class for constructor.");
4670 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
4671 ClassDecl->hasTrivialDefaultConstructor() &&
4672 !Constructor->isUsed(false))
4673 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4674 }
4675
4676 ExprResult CurInit = S.Owned((Expr *)0);
4677
4678 // Determine the arguments required to actually perform the constructor
4679 // call.
4680 if (S.CompleteConstructorCall(Constructor, move(Args),
4681 Loc, ConstructorArgs))
4682 return ExprError();
4683
4684
4685 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
4686 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
4687 (Kind.getKind() == InitializationKind::IK_Direct ||
4688 Kind.getKind() == InitializationKind::IK_Value)) {
4689 // An explicitly-constructed temporary, e.g., X(1, 2).
4690 unsigned NumExprs = ConstructorArgs.size();
4691 Expr **Exprs = (Expr **)ConstructorArgs.take();
4692 S.MarkDeclarationReferenced(Loc, Constructor);
4693 S.DiagnoseUseOfDecl(Constructor, Loc);
4694
4695 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4696 if (!TSInfo)
4697 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
4698
4699 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4700 Constructor,
4701 TSInfo,
4702 Exprs,
4703 NumExprs,
4704 Kind.getParenRange(),
4705 HadMultipleCandidates,
4706 ConstructorInitRequiresZeroInit));
4707 } else {
4708 CXXConstructExpr::ConstructionKind ConstructKind =
4709 CXXConstructExpr::CK_Complete;
4710
4711 if (Entity.getKind() == InitializedEntity::EK_Base) {
4712 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
4713 CXXConstructExpr::CK_VirtualBase :
4714 CXXConstructExpr::CK_NonVirtualBase;
4715 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
4716 ConstructKind = CXXConstructExpr::CK_Delegating;
4717 }
4718
4719 // Only get the parenthesis range if it is a direct construction.
4720 SourceRange parenRange =
4721 Kind.getKind() == InitializationKind::IK_Direct ?
4722 Kind.getParenRange() : SourceRange();
4723
4724 // If the entity allows NRVO, mark the construction as elidable
4725 // unconditionally.
4726 if (Entity.allowsNRVO())
4727 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4728 Constructor, /*Elidable=*/true,
4729 move_arg(ConstructorArgs),
4730 HadMultipleCandidates,
4731 ConstructorInitRequiresZeroInit,
4732 ConstructKind,
4733 parenRange);
4734 else
4735 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4736 Constructor,
4737 move_arg(ConstructorArgs),
4738 HadMultipleCandidates,
4739 ConstructorInitRequiresZeroInit,
4740 ConstructKind,
4741 parenRange);
4742 }
4743 if (CurInit.isInvalid())
4744 return ExprError();
4745
4746 // Only check access if all of that succeeded.
4747 S.CheckConstructorAccess(Loc, Constructor, Entity,
4748 Step.Function.FoundDecl.getAccess());
4749 S.DiagnoseUseOfDecl(Step.Function.FoundDecl, Loc);
4750
4751 if (shouldBindAsTemporary(Entity))
4752 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4753
4754 return move(CurInit);
4755}
4756
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004757ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004758InitializationSequence::Perform(Sema &S,
4759 const InitializedEntity &Entity,
4760 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004761 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004762 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004763 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004764 unsigned NumArgs = Args.size();
4765 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004766 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004767 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004768
Sebastian Redl7491c492011-06-05 13:59:11 +00004769 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004770 // If the declaration is a non-dependent, incomplete array type
4771 // that has an initializer, then its type will be completed once
4772 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004773 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004774 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004775 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004776 if (const IncompleteArrayType *ArrayT
4777 = S.Context.getAsIncompleteArrayType(DeclType)) {
4778 // FIXME: We don't currently have the ability to accurately
4779 // compute the length of an initializer list without
4780 // performing full type-checking of the initializer list
4781 // (since we have to determine where braces are implicitly
4782 // introduced and such). So, we fall back to making the array
4783 // type a dependently-sized array type with no specified
4784 // bound.
4785 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4786 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004787
Douglas Gregord87b61f2009-12-10 17:56:55 +00004788 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004789 if (DeclaratorDecl *DD = Entity.getDecl()) {
4790 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4791 TypeLoc TL = TInfo->getTypeLoc();
4792 if (IncompleteArrayTypeLoc *ArrayLoc
4793 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4794 Brackets = ArrayLoc->getBracketsRange();
4795 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004796 }
4797
4798 *ResultType
4799 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4800 /*NumElts=*/0,
4801 ArrayT->getSizeModifier(),
4802 ArrayT->getIndexTypeCVRQualifiers(),
4803 Brackets);
4804 }
4805
4806 }
4807 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004808 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4809 Kind.isExplicitCast());
4810 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004811 }
4812
Sebastian Redl7491c492011-06-05 13:59:11 +00004813 // No steps means no initialization.
4814 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004815 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004816
Douglas Gregord6542d82009-12-22 15:35:07 +00004817 QualType DestType = Entity.getType().getNonReferenceType();
4818 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004819 // the same as Entity.getDecl()->getType() in cases involving type merging,
4820 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004821 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004822 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004823 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004824
John McCall60d7b3a2010-08-24 06:29:42 +00004825 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004826
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004827 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004828 // grab the only argument out the Args and place it into the "current"
4829 // initializer.
4830 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004831 case SK_ResolveAddressOfOverloadedFunction:
4832 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004833 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004834 case SK_CastDerivedToBaseLValue:
4835 case SK_BindReference:
4836 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004837 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004838 case SK_UserConversion:
4839 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004840 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004841 case SK_QualificationConversionRValue:
4842 case SK_ConversionSequence:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00004843 case SK_ListConstructorCall:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004844 case SK_ListInitialization:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00004845 case SK_UnwrapInitList:
4846 case SK_RewrapInitList:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004847 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004848 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004849 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004850 case SK_ArrayInit:
4851 case SK_PassByIndirectCopyRestore:
4852 case SK_PassByIndirectRestore:
Sebastian Redl2b916b82012-01-17 22:49:42 +00004853 case SK_ProduceObjCObject:
4854 case SK_StdInitializerList: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004855 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004856 CurInit = Args.get()[0];
4857 if (!CurInit.get()) return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004858 break;
John McCallf6a16482010-12-04 03:47:34 +00004859 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004860
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004861 case SK_ConstructorInitialization:
4862 case SK_ZeroInitialization:
4863 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004864 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004865
4866 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004867 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004868 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004869 for (step_iterator Step = step_begin(), StepEnd = step_end();
4870 Step != StepEnd; ++Step) {
4871 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004872 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004873
John Wiegley429bb272011-04-08 18:41:53 +00004874 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004875
Douglas Gregor20093b42009-12-09 23:02:17 +00004876 switch (Step->Kind) {
4877 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004878 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004879 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004880 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004881 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004882 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004883 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004884 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004885 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004886
Douglas Gregor20093b42009-12-09 23:02:17 +00004887 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004888 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004889 case SK_CastDerivedToBaseLValue: {
4890 // We have a derived-to-base cast that produces either an rvalue or an
4891 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004892
John McCallf871d0c2010-08-07 06:22:56 +00004893 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004894
Douglas Gregor20093b42009-12-09 23:02:17 +00004895 // Casts to inaccessible base classes are allowed with C-style casts.
4896 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4897 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004898 CurInit.get()->getLocStart(),
4899 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004900 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004901 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004902
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004903 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4904 QualType T = SourceType;
4905 if (const PointerType *Pointer = T->getAs<PointerType>())
4906 T = Pointer->getPointeeType();
4907 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004908 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004909 cast<CXXRecordDecl>(RecordTy->getDecl()));
4910 }
4911
John McCall5baba9d2010-08-25 10:28:54 +00004912 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004913 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004914 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004915 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004916 VK_XValue :
4917 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004918 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4919 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004920 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004921 CurInit.get(),
4922 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004923 break;
4924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004925
Douglas Gregor20093b42009-12-09 23:02:17 +00004926 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004927 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004928 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4929 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004930 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004931 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004932 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004933 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004934 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004935 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004936
John Wiegley429bb272011-04-08 18:41:53 +00004937 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004938 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004939 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4940 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004941 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004942 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004943 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004944 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004945
Douglas Gregor20093b42009-12-09 23:02:17 +00004946 // Reference binding does not have any corresponding ASTs.
4947
4948 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004949 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004950 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004951
Douglas Gregor20093b42009-12-09 23:02:17 +00004952 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004953
Douglas Gregor20093b42009-12-09 23:02:17 +00004954 case SK_BindReferenceToTemporary:
4955 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004956 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004957 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004958
Douglas Gregor03e80032011-06-21 17:03:29 +00004959 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004960 CurInit = new (S.Context) MaterializeTemporaryExpr(
4961 Entity.getType().getNonReferenceType(),
4962 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004963 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004964
4965 // If we're binding to an Objective-C object that has lifetime, we
4966 // need cleanups.
4967 if (S.getLangOptions().ObjCAutoRefCount &&
4968 CurInit.get()->getType()->isObjCLifetimeType())
4969 S.ExprNeedsCleanups = true;
4970
Douglas Gregor20093b42009-12-09 23:02:17 +00004971 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004972
Douglas Gregor523d46a2010-04-18 07:40:54 +00004973 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004974 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004975 /*IsExtraneousCopy=*/true);
4976 break;
4977
Douglas Gregor20093b42009-12-09 23:02:17 +00004978 case SK_UserConversion: {
4979 // We have a user-defined conversion that invokes either a constructor
4980 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004981 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004982 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004983 FunctionDecl *Fn = Step->Function.Function;
4984 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004985 bool HadMultipleCandidates = Step->Function.HadMultipleCandidates;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004986 bool CreatedObject = false;
John McCallb13b7372010-02-01 03:16:54 +00004987 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004988 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004989 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004990 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004991 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004992
Douglas Gregor20093b42009-12-09 23:02:17 +00004993 // Determine the arguments required to actually perform the constructor
4994 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004995 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004996 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004997 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004998 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004999 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005000
Douglas Gregor20093b42009-12-09 23:02:17 +00005001 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005002 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00005003 move_arg(ConstructorArgs),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005004 HadMultipleCandidates,
John McCall7a1fad32010-08-24 07:32:53 +00005005 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00005006 CXXConstructExpr::CK_Complete,
5007 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00005008 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005009 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00005010
Anders Carlsson9a68a672010-04-21 18:47:17 +00005011 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00005012 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00005013 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005014
John McCall2de56d12010-08-25 11:45:40 +00005015 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005016 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
5017 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
5018 S.IsDerivedFrom(SourceType, Class))
5019 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005020
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005021 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00005022 } else {
5023 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00005024 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
John Wiegley429bb272011-04-08 18:41:53 +00005025 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00005026 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00005027 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005028
5029 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00005030 // derived-to-base conversion? I believe the answer is "no", because
5031 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00005032 ExprResult CurInitExprRes =
5033 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
5034 FoundFn, Conversion);
5035 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005036 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005037 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005038
Douglas Gregor20093b42009-12-09 23:02:17 +00005039 // Build the actual call to the conversion function.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005040 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion,
5041 HadMultipleCandidates);
Douglas Gregor20093b42009-12-09 23:02:17 +00005042 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00005043 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005044
John McCall2de56d12010-08-25 11:45:40 +00005045 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005046
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005047 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005048 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005049
Sebastian Redl3b802322011-07-14 19:07:55 +00005050 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Abramo Bagnara960809e2011-11-16 22:46:05 +00005051 bool MaybeBindToTemp = RequiresCopy || shouldBindAsTemporary(Entity);
5052
5053 if (!MaybeBindToTemp && CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00005054 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005055 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005056 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00005057 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00005058 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005059 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00005060 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
5061 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00005062 }
5063 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005064
John McCallf871d0c2010-08-07 06:22:56 +00005065 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00005066 CurInit.get()->getType(),
5067 CastKind, CurInit.get(), 0,
Eli Friedman104be6f2011-09-27 01:11:35 +00005068 CurInit.get()->getValueKind()));
Abramo Bagnara960809e2011-11-16 22:46:05 +00005069 if (MaybeBindToTemp)
5070 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor2f599792010-04-02 18:24:57 +00005071 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00005072 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
5073 move(CurInit), /*IsExtraneousCopy=*/false);
Douglas Gregor20093b42009-12-09 23:02:17 +00005074 break;
5075 }
Sebastian Redl906082e2010-07-20 04:20:21 +00005076
Douglas Gregor20093b42009-12-09 23:02:17 +00005077 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00005078 case SK_QualificationConversionXValue:
5079 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00005080 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00005081 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00005082 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005083 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00005084 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00005085 VK_XValue :
5086 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00005087 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00005088 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005089 }
5090
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005091 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00005092 Sema::CheckedConversionKind CCK
5093 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
5094 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
Richard Smithc8d7f582011-11-29 22:48:16 +00005095 : Kind.isExplicitCast()? Sema::CCK_OtherCast
John McCallf85e1932011-06-15 23:02:42 +00005096 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00005097 ExprResult CurInitExprRes =
5098 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00005099 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00005100 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00005101 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00005102 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00005103 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00005104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005105
Douglas Gregord87b61f2009-12-10 17:56:55 +00005106 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00005107 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005108 // Hack: We must pass *ResultType if available in order to set the type
5109 // of arrays, e.g. in 'int ar[] = {1, 2, 3};'.
5110 // But in 'const X &x = {1, 2, 3};' we're supposed to initialize a
5111 // temporary, not a reference, so we should pass Ty.
5112 // Worst case: 'const int (&arref)[] = {1, 2, 3};'.
5113 // Since this step is never used for a reference directly, we explicitly
5114 // unwrap references here and rewrap them afterwards.
5115 // We also need to create a InitializeTemporary entity for this.
5116 QualType Ty = ResultType ? ResultType->getNonReferenceType() : Step->Type;
5117 bool IsTemporary = ResultType && (*ResultType)->isReferenceType();
5118 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(Ty);
5119 InitListChecker PerformInitList(S, IsTemporary ? TempEntity : Entity,
5120 InitList, Ty, /*VerifyOnly=*/false,
Sebastian Redlc2235182011-10-16 18:19:28 +00005121 Kind.getKind() != InitializationKind::IK_Direct ||
5122 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005123 if (PerformInitList.HadError())
John McCallf312b1e2010-08-26 23:41:50 +00005124 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005125
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005126 if (ResultType) {
5127 if ((*ResultType)->isRValueReferenceType())
5128 Ty = S.Context.getRValueReferenceType(Ty);
5129 else if ((*ResultType)->isLValueReferenceType())
5130 Ty = S.Context.getLValueReferenceType(Ty,
5131 (*ResultType)->getAs<LValueReferenceType>()->isSpelledAsLValue());
5132 *ResultType = Ty;
5133 }
5134
5135 InitListExpr *StructuredInitList =
5136 PerformInitList.getFullyStructuredList();
Douglas Gregord87b61f2009-12-10 17:56:55 +00005137 CurInit.release();
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005138 CurInit = S.Owned(StructuredInitList);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005139 break;
5140 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005141
Sebastian Redl10f04a62011-12-22 14:44:04 +00005142 case SK_ListConstructorCall: {
5143 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
5144 MultiExprArg Arg(InitList->getInits(), InitList->getNumInits());
5145 CurInit = PerformConstructorInitialization(S, Entity, Kind,
5146 move(Arg), *Step,
5147 ConstructorInitRequiresZeroInit);
5148 break;
5149 }
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005150
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005151 case SK_UnwrapInitList:
5152 CurInit = S.Owned(cast<InitListExpr>(CurInit.take())->getInit(0));
5153 break;
5154
5155 case SK_RewrapInitList: {
5156 Expr *E = CurInit.take();
5157 InitListExpr *Syntactic = Step->WrappingSyntacticList;
5158 InitListExpr *ILE = new (S.Context) InitListExpr(S.Context,
5159 Syntactic->getLBraceLoc(), &E, 1, Syntactic->getRBraceLoc());
5160 ILE->setSyntacticForm(Syntactic);
5161 ILE->setType(E->getType());
5162 ILE->setValueKind(E->getValueKind());
5163 CurInit = S.Owned(ILE);
5164 break;
5165 }
5166
Sebastian Redl10f04a62011-12-22 14:44:04 +00005167 case SK_ConstructorInitialization:
5168 CurInit = PerformConstructorInitialization(S, Entity, Kind, move(Args),
5169 *Step,
5170 ConstructorInitRequiresZeroInit);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005171 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005172
Douglas Gregor71d17402009-12-15 00:01:57 +00005173 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00005174 step_iterator NextStep = Step;
5175 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005176 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00005177 NextStep->Kind == SK_ConstructorInitialization) {
5178 // The need for zero-initialization is recorded directly into
5179 // the call to the object's constructor within the next step.
5180 ConstructorInitRequiresZeroInit = true;
5181 } else if (Kind.getKind() == InitializationKind::IK_Value &&
5182 S.getLangOptions().CPlusPlus &&
5183 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00005184 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
5185 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005186 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00005187 Kind.getRange().getBegin());
5188
5189 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
5190 TSInfo->getType().getNonLValueExprType(S.Context),
5191 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00005192 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00005193 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00005194 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00005195 }
Douglas Gregor71d17402009-12-15 00:01:57 +00005196 break;
5197 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005198
5199 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00005200 QualType SourceType = CurInit.get()->getType();
5201 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005202 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00005203 S.CheckSingleAssignmentConstraints(Step->Type, Result);
5204 if (Result.isInvalid())
5205 return ExprError();
5206 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00005207
5208 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00005209 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00005210 if (ConvTy != Sema::Compatible &&
5211 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00005212 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00005213 == Sema::Compatible)
5214 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00005215 if (CurInitExprRes.isInvalid())
5216 return ExprError();
5217 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00005218
Douglas Gregora41a8c52010-04-22 00:20:18 +00005219 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005220 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
5221 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00005222 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00005223 getAssignmentAction(Entity),
5224 &Complained)) {
5225 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00005226 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00005227 } else if (Complained)
5228 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005229 break;
5230 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005231
5232 case SK_StringInit: {
5233 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00005234 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00005235 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00005236 break;
5237 }
Douglas Gregor569c3162010-08-07 11:51:51 +00005238
5239 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00005240 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00005241 CK_ObjCObjectLValueCast,
Eli Friedmanc1c0dfb2011-09-27 21:58:52 +00005242 CurInit.get()->getValueKind());
Douglas Gregor569c3162010-08-07 11:51:51 +00005243 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005244
5245 case SK_ArrayInit:
5246 // Okay: we checked everything before creating this step. Note that
5247 // this is a GNU extension.
5248 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00005249 << Step->Type << CurInit.get()->getType()
5250 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005251
5252 // If the destination type is an incomplete array type, update the
5253 // type accordingly.
5254 if (ResultType) {
5255 if (const IncompleteArrayType *IncompleteDest
5256 = S.Context.getAsIncompleteArrayType(Step->Type)) {
5257 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00005258 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005259 *ResultType = S.Context.getConstantArrayType(
5260 IncompleteDest->getElementType(),
5261 ConstantSource->getSize(),
5262 ArrayType::Normal, 0);
5263 }
5264 }
5265 }
John McCallf85e1932011-06-15 23:02:42 +00005266 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005267
John McCallf85e1932011-06-15 23:02:42 +00005268 case SK_PassByIndirectCopyRestore:
5269 case SK_PassByIndirectRestore:
5270 checkIndirectCopyRestoreSource(S, CurInit.get());
5271 CurInit = S.Owned(new (S.Context)
5272 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
5273 Step->Kind == SK_PassByIndirectCopyRestore));
5274 break;
5275
5276 case SK_ProduceObjCObject:
5277 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
John McCall33e56f32011-09-10 06:18:15 +00005278 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00005279 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005280 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005281
5282 case SK_StdInitializerList: {
5283 QualType Dest = Step->Type;
5284 QualType E;
5285 bool Success = S.isStdInitializerList(Dest, &E);
5286 (void)Success;
5287 assert(Success && "Destination type changed?");
5288 InitListExpr *ILE = cast<InitListExpr>(CurInit.take());
5289 unsigned NumInits = ILE->getNumInits();
5290 SmallVector<Expr*, 16> Converted(NumInits);
5291 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5292 S.Context.getConstantArrayType(E,
5293 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5294 NumInits),
5295 ArrayType::Normal, 0));
5296 InitializedEntity Element =InitializedEntity::InitializeElement(S.Context,
5297 0, HiddenArray);
5298 for (unsigned i = 0; i < NumInits; ++i) {
5299 Element.setElementIndex(i);
5300 ExprResult Init = S.Owned(ILE->getInit(i));
5301 ExprResult Res = S.PerformCopyInitialization(Element,
5302 Init.get()->getExprLoc(),
5303 Init);
5304 assert(!Res.isInvalid() && "Result changed since try phase.");
5305 Converted[i] = Res.take();
5306 }
5307 InitListExpr *Semantic = new (S.Context)
5308 InitListExpr(S.Context, ILE->getLBraceLoc(),
5309 Converted.data(), NumInits, ILE->getRBraceLoc());
5310 Semantic->setSyntacticForm(ILE);
5311 Semantic->setType(Dest);
5312 CurInit = S.Owned(Semantic);
5313 break;
5314 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005315 }
5316 }
John McCall15d7d122010-11-11 03:21:53 +00005317
5318 // Diagnose non-fatal problems with the completed initialization.
5319 if (Entity.getKind() == InitializedEntity::EK_Member &&
5320 cast<FieldDecl>(Entity.getDecl())->isBitField())
5321 S.CheckBitFieldInitialization(Kind.getLocation(),
5322 cast<FieldDecl>(Entity.getDecl()),
5323 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005324
Douglas Gregor20093b42009-12-09 23:02:17 +00005325 return move(CurInit);
5326}
5327
5328//===----------------------------------------------------------------------===//
5329// Diagnose initialization failures
5330//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005331bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00005332 const InitializedEntity &Entity,
5333 const InitializationKind &Kind,
5334 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00005335 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00005336 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005337
Douglas Gregord6542d82009-12-22 15:35:07 +00005338 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00005339 switch (Failure) {
5340 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005341 // FIXME: Customize for the initialized entity?
5342 if (NumArgs == 0)
5343 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
5344 << DestType.getNonReferenceType();
5345 else // FIXME: diagnostic below could be better!
5346 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
5347 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00005348 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005349
Douglas Gregor20093b42009-12-09 23:02:17 +00005350 case FK_ArrayNeedsInitList:
5351 case FK_ArrayNeedsInitListOrStringLiteral:
5352 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
5353 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
5354 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005355
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005356 case FK_ArrayTypeMismatch:
5357 case FK_NonConstantArrayInit:
5358 S.Diag(Kind.getLocation(),
5359 (Failure == FK_ArrayTypeMismatch
5360 ? diag::err_array_init_different_type
5361 : diag::err_array_init_non_constant_array))
5362 << DestType.getNonReferenceType()
5363 << Args[0]->getType()
5364 << Args[0]->getSourceRange();
5365 break;
5366
John McCall73076432012-01-05 00:13:19 +00005367 case FK_VariableLengthArrayHasInitializer:
5368 S.Diag(Kind.getLocation(), diag::err_variable_object_no_init)
5369 << Args[0]->getSourceRange();
5370 break;
5371
John McCall6bb80172010-03-30 21:47:33 +00005372 case FK_AddressOfOverloadFailed: {
5373 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005374 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00005375 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00005376 true,
5377 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00005378 break;
John McCall6bb80172010-03-30 21:47:33 +00005379 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005380
Douglas Gregor20093b42009-12-09 23:02:17 +00005381 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00005382 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00005383 switch (FailedOverloadResult) {
5384 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005385 if (Failure == FK_UserConversionOverloadFailed)
5386 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
5387 << Args[0]->getType() << DestType
5388 << Args[0]->getSourceRange();
5389 else
5390 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
5391 << DestType << Args[0]->getType()
5392 << Args[0]->getSourceRange();
5393
John McCall120d63c2010-08-24 20:38:10 +00005394 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005395 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005396
Douglas Gregor20093b42009-12-09 23:02:17 +00005397 case OR_No_Viable_Function:
5398 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
5399 << Args[0]->getType() << DestType.getNonReferenceType()
5400 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00005401 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00005402 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005403
Douglas Gregor20093b42009-12-09 23:02:17 +00005404 case OR_Deleted: {
5405 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
5406 << Args[0]->getType() << DestType.getNonReferenceType()
5407 << Args[0]->getSourceRange();
5408 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005409 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005410 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
5411 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00005412 if (Ovl == OR_Deleted) {
5413 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005414 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00005415 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005416 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00005417 }
5418 break;
5419 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005420
Douglas Gregor20093b42009-12-09 23:02:17 +00005421 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005422 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00005423 }
5424 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005425
Douglas Gregor20093b42009-12-09 23:02:17 +00005426 case FK_NonConstLValueReferenceBindingToTemporary:
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005427 if (isa<InitListExpr>(Args[0])) {
5428 S.Diag(Kind.getLocation(),
5429 diag::err_lvalue_reference_bind_to_initlist)
5430 << DestType.getNonReferenceType().isVolatileQualified()
5431 << DestType.getNonReferenceType()
5432 << Args[0]->getSourceRange();
5433 break;
5434 }
5435 // Intentional fallthrough
5436
Douglas Gregor20093b42009-12-09 23:02:17 +00005437 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005438 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00005439 Failure == FK_NonConstLValueReferenceBindingToTemporary
5440 ? diag::err_lvalue_reference_bind_to_temporary
5441 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00005442 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00005443 << DestType.getNonReferenceType()
5444 << Args[0]->getType()
5445 << Args[0]->getSourceRange();
5446 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005447
Douglas Gregor20093b42009-12-09 23:02:17 +00005448 case FK_RValueReferenceBindingToLValue:
5449 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00005450 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00005451 << Args[0]->getSourceRange();
5452 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005453
Douglas Gregor20093b42009-12-09 23:02:17 +00005454 case FK_ReferenceInitDropsQualifiers:
5455 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
5456 << DestType.getNonReferenceType()
5457 << Args[0]->getType()
5458 << Args[0]->getSourceRange();
5459 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005460
Douglas Gregor20093b42009-12-09 23:02:17 +00005461 case FK_ReferenceInitFailed:
5462 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
5463 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00005464 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00005465 << Args[0]->getType()
5466 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00005467 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5468 Args[0]->getType()->isObjCObjectPointerType())
5469 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00005470 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005471
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005472 case FK_ConversionFailed: {
5473 QualType FromType = Args[0]->getType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005474 PartialDiagnostic PDiag = S.PDiag(diag::err_init_conversion_failed)
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005475 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00005476 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00005477 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005478 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00005479 << Args[0]->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00005480 S.HandleFunctionTypeMismatch(PDiag, FromType, DestType);
5481 S.Diag(Kind.getLocation(), PDiag);
Douglas Gregor926df6c2011-06-11 01:09:30 +00005482 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
5483 Args[0]->getType()->isObjCObjectPointerType())
5484 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00005485 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00005486 }
John Wiegley429bb272011-04-08 18:41:53 +00005487
5488 case FK_ConversionFromPropertyFailed:
5489 // No-op. This error has already been reported.
5490 break;
5491
Douglas Gregord87b61f2009-12-10 17:56:55 +00005492 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00005493 SourceRange R;
5494
5495 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00005496 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00005497 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005498 else
Douglas Gregor19311e72010-09-08 21:40:08 +00005499 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00005500
Douglas Gregor19311e72010-09-08 21:40:08 +00005501 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
5502 if (Kind.isCStyleOrFunctionalCast())
5503 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
5504 << R;
5505 else
5506 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
5507 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00005508 break;
5509 }
5510
5511 case FK_ReferenceBindingToInitList:
5512 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
5513 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
5514 break;
5515
5516 case FK_InitListBadDestinationType:
5517 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
5518 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
5519 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005520
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005521 case FK_ListConstructorOverloadFailed:
Douglas Gregor51c56d62009-12-14 20:49:26 +00005522 case FK_ConstructorOverloadFailed: {
5523 SourceRange ArgsRange;
5524 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005525 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00005526 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005527
Sebastian Redlcf15cef2011-12-22 18:58:38 +00005528 if (Failure == FK_ListConstructorOverloadFailed) {
5529 assert(NumArgs == 1 && "List construction from other than 1 argument.");
5530 InitListExpr *InitList = cast<InitListExpr>(Args[0]);
5531 Args = InitList->getInits();
5532 NumArgs = InitList->getNumInits();
5533 }
5534
Douglas Gregor51c56d62009-12-14 20:49:26 +00005535 // FIXME: Using "DestType" for the entity we're printing is probably
5536 // bad.
5537 switch (FailedOverloadResult) {
5538 case OR_Ambiguous:
5539 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
5540 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005541 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
5542 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005543 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005544
Douglas Gregor51c56d62009-12-14 20:49:26 +00005545 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005546 if (Kind.getKind() == InitializationKind::IK_Default &&
5547 (Entity.getKind() == InitializedEntity::EK_Base ||
5548 Entity.getKind() == InitializedEntity::EK_Member) &&
5549 isa<CXXConstructorDecl>(S.CurContext)) {
5550 // This is implicit default initialization of a member or
5551 // base within a constructor. If no viable function was
5552 // found, notify the user that she needs to explicitly
5553 // initialize this base/member.
5554 CXXConstructorDecl *Constructor
5555 = cast<CXXConstructorDecl>(S.CurContext);
5556 if (Entity.getKind() == InitializedEntity::EK_Base) {
5557 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5558 << Constructor->isImplicit()
5559 << S.Context.getTypeDeclType(Constructor->getParent())
5560 << /*base=*/0
5561 << Entity.getType();
5562
5563 RecordDecl *BaseDecl
5564 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
5565 ->getDecl();
5566 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
5567 << S.Context.getTagDeclType(BaseDecl);
5568 } else {
5569 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
5570 << Constructor->isImplicit()
5571 << S.Context.getTypeDeclType(Constructor->getParent())
5572 << /*member=*/1
5573 << Entity.getName();
5574 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
5575
5576 if (const RecordType *Record
5577 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005578 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005579 diag::note_previous_decl)
5580 << S.Context.getTagDeclType(Record->getDecl());
5581 }
5582 break;
5583 }
5584
Douglas Gregor51c56d62009-12-14 20:49:26 +00005585 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
5586 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00005587 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005588 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005589
Douglas Gregor51c56d62009-12-14 20:49:26 +00005590 case OR_Deleted: {
5591 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
5592 << true << DestType << ArgsRange;
5593 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00005594 OverloadingResult Ovl
5595 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00005596 if (Ovl == OR_Deleted) {
5597 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00005598 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00005599 } else {
5600 llvm_unreachable("Inconsistent overload resolution?");
5601 }
5602 break;
5603 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005604
Douglas Gregor51c56d62009-12-14 20:49:26 +00005605 case OR_Success:
5606 llvm_unreachable("Conversion did not fail!");
Douglas Gregor51c56d62009-12-14 20:49:26 +00005607 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00005608 }
David Blaikie9fdefb32012-01-17 08:24:58 +00005609 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005610
Douglas Gregor99a2e602009-12-16 01:38:02 +00005611 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00005612 if (Entity.getKind() == InitializedEntity::EK_Member &&
5613 isa<CXXConstructorDecl>(S.CurContext)) {
5614 // This is implicit default-initialization of a const member in
5615 // a constructor. Complain that it needs to be explicitly
5616 // initialized.
5617 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
5618 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
5619 << Constructor->isImplicit()
5620 << S.Context.getTypeDeclType(Constructor->getParent())
5621 << /*const=*/1
5622 << Entity.getName();
5623 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
5624 << Entity.getName();
5625 } else {
5626 S.Diag(Kind.getLocation(), diag::err_default_init_const)
5627 << DestType << (bool)DestType->getAs<RecordType>();
5628 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00005629 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005630
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005631 case FK_Incomplete:
5632 S.RequireCompleteType(Kind.getLocation(), DestType,
5633 diag::err_init_incomplete_type);
5634 break;
5635
Sebastian Redl14b0c192011-09-24 17:48:00 +00005636 case FK_ListInitializationFailed: {
5637 // Run the init list checker again to emit diagnostics.
5638 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5639 QualType DestType = Entity.getType();
5640 InitListChecker DiagnoseInitList(S, Entity, InitList,
Sebastian Redlc2235182011-10-16 18:19:28 +00005641 DestType, /*VerifyOnly=*/false,
5642 Kind.getKind() != InitializationKind::IK_Direct ||
5643 !S.getLangOptions().CPlusPlus0x);
Sebastian Redl14b0c192011-09-24 17:48:00 +00005644 assert(DiagnoseInitList.HadError() &&
5645 "Inconsistent init list check result.");
5646 break;
5647 }
John McCall5acb0c92011-10-17 18:40:02 +00005648
5649 case FK_PlaceholderType: {
5650 // FIXME: Already diagnosed!
5651 break;
5652 }
Sebastian Redl2b916b82012-01-17 22:49:42 +00005653
5654 case FK_InitListElementCopyFailure: {
5655 // Try to perform all copies again.
5656 InitListExpr* InitList = cast<InitListExpr>(Args[0]);
5657 unsigned NumInits = InitList->getNumInits();
5658 QualType DestType = Entity.getType();
5659 QualType E;
5660 bool Success = S.isStdInitializerList(DestType, &E);
5661 (void)Success;
5662 assert(Success && "Where did the std::initializer_list go?");
5663 InitializedEntity HiddenArray = InitializedEntity::InitializeTemporary(
5664 S.Context.getConstantArrayType(E,
5665 llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
5666 NumInits),
5667 ArrayType::Normal, 0));
5668 InitializedEntity Element = InitializedEntity::InitializeElement(S.Context,
5669 0, HiddenArray);
5670 // Show at most 3 errors. Otherwise, you'd get a lot of errors for errors
5671 // where the init list type is wrong, e.g.
5672 // std::initializer_list<void*> list = { 1, 2, 3, 4, 5, 6, 7, 8 };
5673 // FIXME: Emit a note if we hit the limit?
5674 int ErrorCount = 0;
5675 for (unsigned i = 0; i < NumInits && ErrorCount < 3; ++i) {
5676 Element.setElementIndex(i);
5677 ExprResult Init = S.Owned(InitList->getInit(i));
5678 if (S.PerformCopyInitialization(Element, Init.get()->getExprLoc(), Init)
5679 .isInvalid())
5680 ++ErrorCount;
5681 }
5682 break;
5683 }
Douglas Gregor20093b42009-12-09 23:02:17 +00005684 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005685
Douglas Gregora41a8c52010-04-22 00:20:18 +00005686 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00005687 return true;
5688}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005689
Chris Lattner5f9e2722011-07-23 10:55:15 +00005690void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005691 switch (SequenceKind) {
5692 case FailedSequence: {
5693 OS << "Failed sequence: ";
5694 switch (Failure) {
5695 case FK_TooManyInitsForReference:
5696 OS << "too many initializers for reference";
5697 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005698
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005699 case FK_ArrayNeedsInitList:
5700 OS << "array requires initializer list";
5701 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005702
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005703 case FK_ArrayNeedsInitListOrStringLiteral:
5704 OS << "array requires initializer list or string literal";
5705 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005706
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005707 case FK_ArrayTypeMismatch:
5708 OS << "array type mismatch";
5709 break;
5710
5711 case FK_NonConstantArrayInit:
5712 OS << "non-constant array initializer";
5713 break;
5714
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005715 case FK_AddressOfOverloadFailed:
5716 OS << "address of overloaded function failed";
5717 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005718
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005719 case FK_ReferenceInitOverloadFailed:
5720 OS << "overload resolution for reference initialization failed";
5721 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005722
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005723 case FK_NonConstLValueReferenceBindingToTemporary:
5724 OS << "non-const lvalue reference bound to temporary";
5725 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005726
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005727 case FK_NonConstLValueReferenceBindingToUnrelated:
5728 OS << "non-const lvalue reference bound to unrelated type";
5729 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005730
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005731 case FK_RValueReferenceBindingToLValue:
5732 OS << "rvalue reference bound to an lvalue";
5733 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005734
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005735 case FK_ReferenceInitDropsQualifiers:
5736 OS << "reference initialization drops qualifiers";
5737 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005738
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005739 case FK_ReferenceInitFailed:
5740 OS << "reference initialization failed";
5741 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005742
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005743 case FK_ConversionFailed:
5744 OS << "conversion failed";
5745 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005746
John Wiegley429bb272011-04-08 18:41:53 +00005747 case FK_ConversionFromPropertyFailed:
5748 OS << "conversion from property failed";
5749 break;
5750
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005751 case FK_TooManyInitsForScalar:
5752 OS << "too many initializers for scalar";
5753 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005754
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005755 case FK_ReferenceBindingToInitList:
5756 OS << "referencing binding to initializer list";
5757 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005758
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005759 case FK_InitListBadDestinationType:
5760 OS << "initializer list for non-aggregate, non-scalar type";
5761 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005762
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005763 case FK_UserConversionOverloadFailed:
5764 OS << "overloading failed for user-defined conversion";
5765 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005766
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005767 case FK_ConstructorOverloadFailed:
5768 OS << "constructor overloading failed";
5769 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005770
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005771 case FK_DefaultInitOfConst:
5772 OS << "default initialization of a const variable";
5773 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005774
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005775 case FK_Incomplete:
5776 OS << "initialization of incomplete type";
5777 break;
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005778
5779 case FK_ListInitializationFailed:
Sebastian Redl14b0c192011-09-24 17:48:00 +00005780 OS << "list initialization checker failure";
John McCall5acb0c92011-10-17 18:40:02 +00005781 break;
5782
John McCall73076432012-01-05 00:13:19 +00005783 case FK_VariableLengthArrayHasInitializer:
5784 OS << "variable length array has an initializer";
5785 break;
5786
John McCall5acb0c92011-10-17 18:40:02 +00005787 case FK_PlaceholderType:
5788 OS << "initializer expression isn't contextually valid";
5789 break;
Nick Lewyckyb0c6c332011-12-22 20:21:32 +00005790
5791 case FK_ListConstructorOverloadFailed:
5792 OS << "list constructor overloading failed";
5793 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005794
5795 case FK_InitListElementCopyFailure:
5796 OS << "copy construction of initializer list element failed";
5797 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005798 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005799 OS << '\n';
5800 return;
5801 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005802
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005803 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005804 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005805 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005806
Sebastian Redl7491c492011-06-05 13:59:11 +00005807 case NormalSequence:
5808 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005809 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005810 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005811
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005812 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5813 if (S != step_begin()) {
5814 OS << " -> ";
5815 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005816
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005817 switch (S->Kind) {
5818 case SK_ResolveAddressOfOverloadedFunction:
5819 OS << "resolve address of overloaded function";
5820 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005821
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005822 case SK_CastDerivedToBaseRValue:
5823 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5824 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005825
Sebastian Redl906082e2010-07-20 04:20:21 +00005826 case SK_CastDerivedToBaseXValue:
5827 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5828 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005829
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005830 case SK_CastDerivedToBaseLValue:
5831 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5832 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005833
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005834 case SK_BindReference:
5835 OS << "bind reference to lvalue";
5836 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005837
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005838 case SK_BindReferenceToTemporary:
5839 OS << "bind reference to a temporary";
5840 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005841
Douglas Gregor523d46a2010-04-18 07:40:54 +00005842 case SK_ExtraneousCopyToTemporary:
5843 OS << "extraneous C++03 copy to temporary";
5844 break;
5845
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005846 case SK_UserConversion:
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005847 OS << "user-defined conversion via " << *S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005848 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005849
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005850 case SK_QualificationConversionRValue:
5851 OS << "qualification conversion (rvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005852 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005853
Sebastian Redl906082e2010-07-20 04:20:21 +00005854 case SK_QualificationConversionXValue:
5855 OS << "qualification conversion (xvalue)";
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005856 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005857
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005858 case SK_QualificationConversionLValue:
5859 OS << "qualification conversion (lvalue)";
5860 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005861
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005862 case SK_ConversionSequence:
5863 OS << "implicit conversion sequence (";
5864 S->ICS->DebugPrint(); // FIXME: use OS
5865 OS << ")";
5866 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005867
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005868 case SK_ListInitialization:
Sebastian Redl8713d4e2011-09-24 17:47:52 +00005869 OS << "list aggregate initialization";
5870 break;
5871
5872 case SK_ListConstructorCall:
5873 OS << "list initialization via constructor";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005874 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005875
Sebastian Redl13dc8f92011-11-27 16:50:07 +00005876 case SK_UnwrapInitList:
5877 OS << "unwrap reference initializer list";
5878 break;
5879
5880 case SK_RewrapInitList:
5881 OS << "rewrap reference initializer list";
5882 break;
5883
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005884 case SK_ConstructorInitialization:
5885 OS << "constructor initialization";
5886 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005887
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005888 case SK_ZeroInitialization:
5889 OS << "zero initialization";
5890 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005891
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005892 case SK_CAssignment:
5893 OS << "C assignment";
5894 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005895
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005896 case SK_StringInit:
5897 OS << "string initialization";
5898 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005899
5900 case SK_ObjCObjectConversion:
5901 OS << "Objective-C object conversion";
5902 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005903
5904 case SK_ArrayInit:
5905 OS << "array initialization";
5906 break;
John McCallf85e1932011-06-15 23:02:42 +00005907
5908 case SK_PassByIndirectCopyRestore:
5909 OS << "pass by indirect copy and restore";
5910 break;
5911
5912 case SK_PassByIndirectRestore:
5913 OS << "pass by indirect restore";
5914 break;
5915
5916 case SK_ProduceObjCObject:
5917 OS << "Objective-C object retension";
5918 break;
Sebastian Redl2b916b82012-01-17 22:49:42 +00005919
5920 case SK_StdInitializerList:
5921 OS << "std::initializer_list from initializer list";
5922 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005923 }
5924 }
5925}
5926
5927void InitializationSequence::dump() const {
5928 dump(llvm::errs());
5929}
5930
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005931static void DiagnoseNarrowingInInitList(
5932 Sema& S, QualType EntityType, const Expr *InitE,
5933 bool Constant, const APValue &ConstantValue) {
5934 if (Constant) {
5935 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005936 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005937 ? diag::err_init_list_constant_narrowing
5938 : diag::warn_init_list_constant_narrowing)
5939 << InitE->getSourceRange()
Richard Smith08d6e032011-12-16 19:06:07 +00005940 << ConstantValue.getAsString(S.getASTContext(), EntityType)
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005941 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005942 } else
5943 S.Diag(InitE->getLocStart(),
Francois Pichet62ec1f22011-09-17 17:15:52 +00005944 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().MicrosoftExt
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005945 ? diag::err_init_list_variable_narrowing
5946 : diag::warn_init_list_variable_narrowing)
5947 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005948 << InitE->getType().getLocalUnqualifiedType()
5949 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005950
5951 llvm::SmallString<128> StaticCast;
5952 llvm::raw_svector_ostream OS(StaticCast);
5953 OS << "static_cast<";
5954 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5955 // It's important to use the typedef's name if there is one so that the
5956 // fixit doesn't break code using types like int64_t.
5957 //
5958 // FIXME: This will break if the typedef requires qualification. But
5959 // getQualifiedNameAsString() includes non-machine-parsable components.
Benjamin Kramerb8989f22011-10-14 18:45:37 +00005960 OS << *TT->getDecl();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005961 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5962 OS << BT->getName(S.getLangOptions());
5963 else {
5964 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5965 // with a broken cast.
5966 return;
5967 }
5968 OS << ">(";
5969 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5970 << InitE->getSourceRange()
5971 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5972 << FixItHint::CreateInsertion(
5973 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5974}
5975
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005976//===----------------------------------------------------------------------===//
5977// Initialization helper functions
5978//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005979bool
5980Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5981 ExprResult Init) {
5982 if (Init.isInvalid())
5983 return false;
5984
5985 Expr *InitE = Init.get();
5986 assert(InitE && "No initialization expression");
5987
5988 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5989 SourceLocation());
5990 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005991 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005992}
5993
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005994ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005995Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5996 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005997 ExprResult Init,
5998 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005999 if (Init.isInvalid())
6000 return ExprError();
6001
John McCall15d7d122010-11-11 03:21:53 +00006002 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006003 assert(InitE && "No initialization expression?");
6004
6005 if (EqualLoc.isInvalid())
6006 EqualLoc = InitE->getLocStart();
6007
6008 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
6009 EqualLoc);
6010 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
6011 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00006012
6013 bool Constant = false;
6014 APValue Result;
6015 if (TopLevelOfInitList &&
6016 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
6017 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
6018 Constant, Result);
6019 }
John McCallf312b1e2010-08-26 23:41:50 +00006020 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00006021}