blob: 06d530f007bc01dc2ee235476798acda2125efb4 [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//
Rafael Espindola12ce0a02011-07-14 22:58:04 +000010// This file implements semantic analysis for initializers. The main entry
11// point is Sema::CheckInitList(), but all of the work is performed
12// within the InitListChecker class.
Chris Lattnerdd8e0062009-02-24 22:27:37 +000013//
Steve Naroff0cca7492008-05-01 22:18:59 +000014//===----------------------------------------------------------------------===//
15
John McCall19510852010-08-20 18:27:03 +000016#include "clang/Sema/Designator.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
John McCall2d887082010-08-25 22:03:47 +000019#include "clang/Sema/SemaInternal.h"
Tanya Lattner1e1d3962010-03-07 04:17:15 +000020#include "clang/Lex/Preprocessor.h"
Steve Naroff0cca7492008-05-01 22:18:59 +000021#include "clang/AST/ASTContext.h"
John McCall7cd088e2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson2078bb92009-05-27 16:10:08 +000023#include "clang/AST/ExprCXX.h"
Chris Lattner79e079d2009-02-24 23:10:27 +000024#include "clang/AST/ExprObjC.h"
Douglas Gregord6542d82009-12-22 15:35:07 +000025#include "clang/AST/TypeLoc.h"
Douglas Gregor20093b42009-12-09 23:02:17 +000026#include "llvm/Support/ErrorHandling.h"
Jeffrey Yasskin19159132011-07-26 23:20:30 +000027#include "llvm/Support/raw_ostream.h"
Douglas Gregorc34ee5e2009-01-29 00:45:39 +000028#include <map>
Douglas Gregor05c13a32009-01-22 00:58:24 +000029using namespace clang;
Steve Naroff0cca7492008-05-01 22:18:59 +000030
Chris Lattnerdd8e0062009-02-24 22:27:37 +000031//===----------------------------------------------------------------------===//
32// Sema Initialization Checking
33//===----------------------------------------------------------------------===//
34
John McCallce6c9b72011-02-21 07:22:22 +000035static Expr *IsStringInit(Expr *Init, const ArrayType *AT,
36 ASTContext &Context) {
Eli Friedman8718a6a2009-05-29 18:22:49 +000037 if (!isa<ConstantArrayType>(AT) && !isa<IncompleteArrayType>(AT))
38 return 0;
39
Chris Lattner8879e3b2009-02-26 23:26:43 +000040 // See if this is a string literal or @encode.
41 Init = Init->IgnoreParens();
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner8879e3b2009-02-26 23:26:43 +000043 // Handle @encode, which is a narrow string.
44 if (isa<ObjCEncodeExpr>(Init) && AT->getElementType()->isCharType())
45 return Init;
46
47 // Otherwise we can only handle string literals.
48 StringLiteral *SL = dyn_cast<StringLiteral>(Init);
Chris Lattner220b6362009-02-26 23:42:47 +000049 if (SL == 0) return 0;
Eli Friedmanbb6415c2009-05-31 10:54:53 +000050
51 QualType ElemTy = Context.getCanonicalType(AT->getElementType());
Douglas Gregor5cee1192011-07-27 05:40:30 +000052
53 switch (SL->getKind()) {
54 case StringLiteral::Ascii:
55 case StringLiteral::UTF8:
56 // char array can be initialized with a narrow string.
57 // Only allow char x[] = "foo"; not char x[] = L"foo";
Eli Friedmanbb6415c2009-05-31 10:54:53 +000058 return ElemTy->isCharType() ? Init : 0;
Douglas Gregor5cee1192011-07-27 05:40:30 +000059 case StringLiteral::UTF16:
60 return ElemTy->isChar16Type() ? Init : 0;
61 case StringLiteral::UTF32:
62 return ElemTy->isChar32Type() ? Init : 0;
63 case StringLiteral::Wide:
64 // wchar_t array can be initialized with a wide string: C99 6.7.8p15 (with
65 // correction from DR343): "An array with element type compatible with a
66 // qualified or unqualified version of wchar_t may be initialized by a wide
67 // string literal, optionally enclosed in braces."
68 if (Context.typesAreCompatible(Context.getWCharType(),
69 ElemTy.getUnqualifiedType()))
70 return Init;
Chris Lattner8879e3b2009-02-26 23:26:43 +000071
Douglas Gregor5cee1192011-07-27 05:40:30 +000072 return 0;
73 }
Mike Stump1eb44332009-09-09 15:08:12 +000074
Douglas Gregor5cee1192011-07-27 05:40:30 +000075 llvm_unreachable("missed a StringLiteral kind?");
Chris Lattnerdd8e0062009-02-24 22:27:37 +000076}
77
John McCallce6c9b72011-02-21 07:22:22 +000078static Expr *IsStringInit(Expr *init, QualType declType, ASTContext &Context) {
79 const ArrayType *arrayType = Context.getAsArrayType(declType);
80 if (!arrayType) return 0;
81
82 return IsStringInit(init, arrayType, Context);
83}
84
John McCallfef8b342011-02-21 07:57:55 +000085static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
86 Sema &S) {
Chris Lattner79e079d2009-02-24 23:10:27 +000087 // Get the length of the string as parsed.
88 uint64_t StrLength =
89 cast<ConstantArrayType>(Str->getType())->getSize().getZExtValue();
90
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattnerdd8e0062009-02-24 22:27:37 +000092 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Mike Stump1eb44332009-09-09 15:08:12 +000093 // C99 6.7.8p14. We have an array of character type with unknown size
Chris Lattnerdd8e0062009-02-24 22:27:37 +000094 // being initialized to a string literal.
95 llvm::APSInt ConstVal(32);
Chris Lattner19da8cd2009-02-24 23:01:39 +000096 ConstVal = StrLength;
Chris Lattnerdd8e0062009-02-24 22:27:37 +000097 // Return a new array type (C99 6.7.8p22).
John McCall46a617a2009-10-16 00:14:28 +000098 DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
99 ConstVal,
100 ArrayType::Normal, 0);
Chris Lattner19da8cd2009-02-24 23:01:39 +0000101 return;
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000102 }
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Eli Friedman8718a6a2009-05-29 18:22:49 +0000104 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Mike Stump1eb44332009-09-09 15:08:12 +0000105
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000106 // We have an array of character type with known size. However,
Eli Friedman8718a6a2009-05-29 18:22:49 +0000107 // the size may be smaller or larger than the string we are initializing.
108 // FIXME: Avoid truncation for 64-bit length strings.
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000109 if (S.getLangOptions().CPlusPlus) {
Anders Carlssonb8fc45f2011-04-14 00:41:11 +0000110 if (StringLiteral *SL = dyn_cast<StringLiteral>(Str)) {
111 // For Pascal strings it's OK to strip off the terminating null character,
112 // so the example below is valid:
113 //
114 // unsigned char a[2] = "\pa";
115 if (SL->isPascal())
116 StrLength--;
117 }
118
Eli Friedmanbc34b1d2011-04-11 00:23:45 +0000119 // [dcl.init.string]p2
120 if (StrLength > CAT->getSize().getZExtValue())
121 S.Diag(Str->getSourceRange().getBegin(),
122 diag::err_initializer_string_for_char_array_too_long)
123 << Str->getSourceRange();
124 } else {
125 // C99 6.7.8p14.
126 if (StrLength-1 > CAT->getSize().getZExtValue())
127 S.Diag(Str->getSourceRange().getBegin(),
128 diag::warn_initializer_string_for_char_array_too_long)
129 << Str->getSourceRange();
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Eli Friedman8718a6a2009-05-29 18:22:49 +0000132 // Set the type to the actual size that we are initializing. If we have
133 // something like:
134 // char x[1] = "foo";
135 // then this will set the string literal's type to char[1].
136 Str->setType(DeclT);
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000137}
138
Chris Lattnerdd8e0062009-02-24 22:27:37 +0000139//===----------------------------------------------------------------------===//
140// Semantic checking for initializer lists.
141//===----------------------------------------------------------------------===//
142
Douglas Gregor9e80f722009-01-29 01:05:33 +0000143/// @brief Semantic checking for initializer lists.
144///
145/// The InitListChecker class contains a set of routines that each
146/// handle the initialization of a certain kind of entity, e.g.,
147/// arrays, vectors, struct/union types, scalars, etc. The
148/// InitListChecker itself performs a recursive walk of the subobject
149/// structure of the type to be initialized, while stepping through
150/// the initializer list one element at a time. The IList and Index
151/// parameters to each of the Check* routines contain the active
152/// (syntactic) initializer list and the index into that initializer
153/// list that represents the current initializer. Each routine is
154/// responsible for moving that Index forward as it consumes elements.
155///
156/// Each Check* routine also has a StructuredList/StructuredIndex
Abramo Bagnara63e7d252011-01-27 19:55:10 +0000157/// arguments, which contains the current "structured" (semantic)
Douglas Gregor9e80f722009-01-29 01:05:33 +0000158/// initializer list and the index into that initializer list where we
159/// are copying initializers as we map them over to the semantic
160/// list. Once we have completed our recursive walk of the subobject
161/// structure, we will have constructed a full semantic initializer
162/// list.
163///
164/// C99 designators cause changes in the initializer list traversal,
165/// because they make the initialization "jump" into a specific
166/// subobject and then continue the initialization from that
167/// point. CheckDesignatedInitializer() recursively steps into the
168/// designated subobject and manages backing out the recursion to
169/// initialize the subobjects after the one designated.
Chris Lattner8b419b92009-02-24 22:48:58 +0000170namespace {
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000171class InitListChecker {
Chris Lattner08202542009-02-24 22:50:46 +0000172 Sema &SemaRef;
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000173 bool hadError;
174 std::map<InitListExpr *, InitListExpr *> SyntacticToSemantic;
175 InitListExpr *FullyStructuredList;
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000177 void CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000178 InitListExpr *ParentIList, QualType T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000179 unsigned &Index, InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000180 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000181 void CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000182 InitListExpr *IList, QualType &T,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000183 unsigned &Index, InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000184 unsigned &StructuredIndex,
185 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000186 void CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000187 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000188 bool SubobjectIsDesignatorContext,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000189 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000190 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000191 unsigned &StructuredIndex,
192 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000193 void CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000194 InitListExpr *IList, QualType ElemType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000195 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000196 InitListExpr *StructuredList,
197 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000198 void CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000199 InitListExpr *IList, QualType DeclType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000200 unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000201 InitListExpr *StructuredList,
202 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000203 void CheckReferenceType(const InitializedEntity &Entity,
204 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000205 unsigned &Index,
206 InitListExpr *StructuredList,
207 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000208 void CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000209 InitListExpr *IList, QualType DeclType, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000210 InitListExpr *StructuredList,
211 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000212 void CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000213 InitListExpr *IList, QualType DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000214 RecordDecl::field_iterator Field,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000215 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000216 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000217 unsigned &StructuredIndex,
218 bool TopLevelObject = false);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000219 void CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +0000220 InitListExpr *IList, QualType &DeclType,
Mike Stump1eb44332009-09-09 15:08:12 +0000221 llvm::APSInt elementIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000222 bool SubobjectIsDesignatorContext, unsigned &Index,
Douglas Gregor9e80f722009-01-29 01:05:33 +0000223 InitListExpr *StructuredList,
224 unsigned &StructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000225 bool CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +0000226 InitListExpr *IList, DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +0000227 unsigned DesigIdx,
Mike Stump1eb44332009-09-09 15:08:12 +0000228 QualType &CurrentObjectType,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000229 RecordDecl::field_iterator *NextField,
230 llvm::APSInt *NextElementIndex,
231 unsigned &Index,
232 InitListExpr *StructuredList,
233 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000234 bool FinishSubobjectInit,
235 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000236 InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
237 QualType CurrentObjectType,
238 InitListExpr *StructuredList,
239 unsigned StructuredIndex,
240 SourceRange InitRange);
Douglas Gregor9e80f722009-01-29 01:05:33 +0000241 void UpdateStructuredListElement(InitListExpr *StructuredList,
242 unsigned &StructuredIndex,
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000243 Expr *expr);
244 int numArrayElements(QualType DeclType);
245 int numStructUnionElements(QualType DeclType);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000246
Douglas Gregord6d37de2009-12-22 00:05:34 +0000247 void FillInValueInitForField(unsigned Init, FieldDecl *Field,
248 const InitializedEntity &ParentEntity,
249 InitListExpr *ILE, bool &RequiresSecondPass);
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000250 void FillInValueInitializations(const InitializedEntity &Entity,
251 InitListExpr *ILE, bool &RequiresSecondPass);
Eli Friedmanf40fd6b2011-08-23 22:24:57 +0000252 bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
253 Expr *InitExpr, FieldDecl *Field,
254 bool TopLevelObject);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000255public:
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000256 InitListChecker(Sema &S, const InitializedEntity &Entity,
257 InitListExpr *IL, QualType &T);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +0000258 bool HadError() { return hadError; }
259
260 // @brief Retrieves the fully-structured initializer list used for
261 // semantic analysis and code generation.
262 InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
263};
Chris Lattner8b419b92009-02-24 22:48:58 +0000264} // end anonymous namespace
Chris Lattner68355a52009-01-29 05:10:57 +0000265
Douglas Gregord6d37de2009-12-22 00:05:34 +0000266void InitListChecker::FillInValueInitForField(unsigned Init, FieldDecl *Field,
267 const InitializedEntity &ParentEntity,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000268 InitListExpr *ILE,
Douglas Gregord6d37de2009-12-22 00:05:34 +0000269 bool &RequiresSecondPass) {
270 SourceLocation Loc = ILE->getSourceRange().getBegin();
271 unsigned NumInits = ILE->getNumInits();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000272 InitializedEntity MemberEntity
Douglas Gregord6d37de2009-12-22 00:05:34 +0000273 = InitializedEntity::InitializeMember(Field, &ParentEntity);
274 if (Init >= NumInits || !ILE->getInit(Init)) {
275 // FIXME: We probably don't need to handle references
276 // specially here, since value-initialization of references is
277 // handled in InitializationSequence.
278 if (Field->getType()->isReferenceType()) {
279 // C++ [dcl.init.aggr]p9:
280 // If an incomplete or empty initializer-list leaves a
281 // member of reference type uninitialized, the program is
282 // ill-formed.
283 SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
284 << Field->getType()
285 << ILE->getSyntacticForm()->getSourceRange();
286 SemaRef.Diag(Field->getLocation(),
287 diag::note_uninit_reference_member);
288 hadError = true;
289 return;
290 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000291
Douglas Gregord6d37de2009-12-22 00:05:34 +0000292 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
293 true);
294 InitializationSequence InitSeq(SemaRef, MemberEntity, Kind, 0, 0);
295 if (!InitSeq) {
296 InitSeq.Diagnose(SemaRef, MemberEntity, Kind, 0, 0);
297 hadError = true;
298 return;
299 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000300
John McCall60d7b3a2010-08-24 06:29:42 +0000301 ExprResult MemberInit
John McCallf312b1e2010-08-26 23:41:50 +0000302 = InitSeq.Perform(SemaRef, MemberEntity, Kind, MultiExprArg());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000303 if (MemberInit.isInvalid()) {
304 hadError = true;
305 return;
306 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000307
Douglas Gregord6d37de2009-12-22 00:05:34 +0000308 if (hadError) {
309 // Do nothing
310 } else if (Init < NumInits) {
311 ILE->setInit(Init, MemberInit.takeAs<Expr>());
Sebastian Redl7491c492011-06-05 13:59:11 +0000312 } else if (InitSeq.isConstructorInitialization()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000313 // Value-initialization requires a constructor call, so
314 // extend the initializer list to include the constructor
315 // call and make a note that we'll need to take another pass
316 // through the initializer list.
Ted Kremenek709210f2010-04-13 23:39:13 +0000317 ILE->updateInit(SemaRef.Context, Init, MemberInit.takeAs<Expr>());
Douglas Gregord6d37de2009-12-22 00:05:34 +0000318 RequiresSecondPass = true;
319 }
320 } else if (InitListExpr *InnerILE
321 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000322 FillInValueInitializations(MemberEntity, InnerILE,
323 RequiresSecondPass);
Douglas Gregord6d37de2009-12-22 00:05:34 +0000324}
325
Douglas Gregor4c678342009-01-28 21:54:33 +0000326/// Recursively replaces NULL values within the given initializer list
327/// with expressions that perform value-initialization of the
328/// appropriate type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000329void
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000330InitListChecker::FillInValueInitializations(const InitializedEntity &Entity,
331 InitListExpr *ILE,
332 bool &RequiresSecondPass) {
Mike Stump1eb44332009-09-09 15:08:12 +0000333 assert((ILE->getType() != SemaRef.Context.VoidTy) &&
Douglas Gregor930d8b52009-01-30 22:09:00 +0000334 "Should not have void type");
Douglas Gregor87fd7032009-02-02 17:43:21 +0000335 SourceLocation Loc = ILE->getSourceRange().getBegin();
336 if (ILE->getSyntacticForm())
337 Loc = ILE->getSyntacticForm()->getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremenek6217b802009-07-29 21:53:49 +0000339 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
Douglas Gregord6d37de2009-12-22 00:05:34 +0000340 if (RType->getDecl()->isUnion() &&
341 ILE->getInitializedFieldInUnion())
342 FillInValueInitForField(0, ILE->getInitializedFieldInUnion(),
343 Entity, ILE, RequiresSecondPass);
344 else {
345 unsigned Init = 0;
346 for (RecordDecl::field_iterator
347 Field = RType->getDecl()->field_begin(),
348 FieldEnd = RType->getDecl()->field_end();
349 Field != FieldEnd; ++Field) {
350 if (Field->isUnnamedBitfield())
351 continue;
Douglas Gregor4c678342009-01-28 21:54:33 +0000352
Douglas Gregord6d37de2009-12-22 00:05:34 +0000353 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000354 return;
Douglas Gregord6d37de2009-12-22 00:05:34 +0000355
356 FillInValueInitForField(Init, *Field, Entity, ILE, RequiresSecondPass);
357 if (hadError)
Douglas Gregor87fd7032009-02-02 17:43:21 +0000358 return;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000359
Douglas Gregord6d37de2009-12-22 00:05:34 +0000360 ++Init;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000361
Douglas Gregord6d37de2009-12-22 00:05:34 +0000362 // Only look at the first initialization of a union.
363 if (RType->getDecl()->isUnion())
364 break;
365 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000366 }
367
368 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000369 }
Douglas Gregor4c678342009-01-28 21:54:33 +0000370
371 QualType ElementType;
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000373 InitializedEntity ElementEntity = Entity;
Douglas Gregor87fd7032009-02-02 17:43:21 +0000374 unsigned NumInits = ILE->getNumInits();
375 unsigned NumElements = NumInits;
Chris Lattner08202542009-02-24 22:50:46 +0000376 if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000377 ElementType = AType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000378 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType))
379 NumElements = CAType->getSize().getZExtValue();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000380 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000381 0, Entity);
John McCall183700f2009-09-21 23:43:11 +0000382 } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
Douglas Gregor4c678342009-01-28 21:54:33 +0000383 ElementType = VType->getElementType();
Douglas Gregor87fd7032009-02-02 17:43:21 +0000384 NumElements = VType->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000385 ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000386 0, Entity);
Mike Stump1eb44332009-09-09 15:08:12 +0000387 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000388 ElementType = ILE->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000389
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390
Douglas Gregor87fd7032009-02-02 17:43:21 +0000391 for (unsigned Init = 0; Init != NumElements; ++Init) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000392 if (hadError)
393 return;
394
Anders Carlssond3d824d2010-01-23 04:34:47 +0000395 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
396 ElementEntity.getKind() == InitializedEntity::EK_VectorElement)
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000397 ElementEntity.setElementIndex(Init);
398
Douglas Gregor87fd7032009-02-02 17:43:21 +0000399 if (Init >= NumInits || !ILE->getInit(Init)) {
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000400 InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
401 true);
402 InitializationSequence InitSeq(SemaRef, ElementEntity, Kind, 0, 0);
403 if (!InitSeq) {
404 InitSeq.Diagnose(SemaRef, ElementEntity, Kind, 0, 0);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000405 hadError = true;
406 return;
407 }
408
John McCall60d7b3a2010-08-24 06:29:42 +0000409 ExprResult ElementInit
John McCallf312b1e2010-08-26 23:41:50 +0000410 = InitSeq.Perform(SemaRef, ElementEntity, Kind, MultiExprArg());
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000411 if (ElementInit.isInvalid()) {
Douglas Gregor16006c92009-12-16 18:50:27 +0000412 hadError = true;
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000413 return;
414 }
415
416 if (hadError) {
417 // Do nothing
418 } else if (Init < NumInits) {
Argyrios Kyrtzidis3e8dc2a2011-04-21 20:03:38 +0000419 // For arrays, just set the expression used for value-initialization
420 // of the "holes" in the array.
421 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
422 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
423 else
424 ILE->setInit(Init, ElementInit.takeAs<Expr>());
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000425 } else {
426 // For arrays, just set the expression used for value-initialization
427 // of the rest of elements and exit.
428 if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
429 ILE->setArrayFiller(ElementInit.takeAs<Expr>());
430 return;
431 }
432
Sebastian Redl7491c492011-06-05 13:59:11 +0000433 if (InitSeq.isConstructorInitialization()) {
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000434 // Value-initialization requires a constructor call, so
435 // extend the initializer list to include the constructor
436 // call and make a note that we'll need to take another pass
437 // through the initializer list.
438 ILE->updateInit(SemaRef.Context, Init, ElementInit.takeAs<Expr>());
439 RequiresSecondPass = true;
440 }
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000441 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000442 } else if (InitListExpr *InnerILE
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000443 = dyn_cast<InitListExpr>(ILE->getInit(Init)))
444 FillInValueInitializations(ElementEntity, InnerILE, RequiresSecondPass);
Douglas Gregor4c678342009-01-28 21:54:33 +0000445 }
446}
447
Chris Lattner68355a52009-01-29 05:10:57 +0000448
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000449InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
450 InitListExpr *IL, QualType &T)
Chris Lattner08202542009-02-24 22:50:46 +0000451 : SemaRef(S) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000452 hadError = false;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000453
Eli Friedmanb85f7072008-05-19 19:16:24 +0000454 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000455 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000456 FullyStructuredList
Douglas Gregored8a93d2009-03-01 17:12:46 +0000457 = getStructuredSubobjectInit(IL, newIndex, T, 0, 0, IL->getSourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000458 CheckExplicitInitList(Entity, IL, T, newIndex,
Anders Carlsson46f46592010-01-23 19:55:29 +0000459 FullyStructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000460 /*TopLevelObject=*/true);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000461
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000462 if (!hadError) {
463 bool RequiresSecondPass = false;
464 FillInValueInitializations(Entity, FullyStructuredList, RequiresSecondPass);
Douglas Gregor16006c92009-12-16 18:50:27 +0000465 if (RequiresSecondPass && !hadError)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000466 FillInValueInitializations(Entity, FullyStructuredList,
Douglas Gregorcb57fb92009-12-16 06:35:08 +0000467 RequiresSecondPass);
468 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000469}
470
471int InitListChecker::numArrayElements(QualType DeclType) {
Eli Friedman638e1442008-05-25 13:22:35 +0000472 // FIXME: use a proper constant
473 int maxElements = 0x7FFFFFFF;
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000474 if (const ConstantArrayType *CAT =
Chris Lattner08202542009-02-24 22:50:46 +0000475 SemaRef.Context.getAsConstantArrayType(DeclType)) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000476 maxElements = static_cast<int>(CAT->getSize().getZExtValue());
477 }
478 return maxElements;
479}
480
481int InitListChecker::numStructUnionElements(QualType DeclType) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000482 RecordDecl *structDecl = DeclType->getAs<RecordType>()->getDecl();
Douglas Gregor4c678342009-01-28 21:54:33 +0000483 int InitializableMembers = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000484 for (RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000485 Field = structDecl->field_begin(),
486 FieldEnd = structDecl->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +0000487 Field != FieldEnd; ++Field) {
488 if ((*Field)->getIdentifier() || !(*Field)->isBitField())
489 ++InitializableMembers;
490 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +0000491 if (structDecl->isUnion())
Eli Friedmanf84eda32008-05-25 14:03:31 +0000492 return std::min(InitializableMembers, 1);
493 return InitializableMembers - structDecl->hasFlexibleArrayMember();
Steve Naroff0cca7492008-05-01 22:18:59 +0000494}
495
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000496void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000497 InitListExpr *ParentIList,
Douglas Gregor4c678342009-01-28 21:54:33 +0000498 QualType T, unsigned &Index,
499 InitListExpr *StructuredList,
Eli Friedman629f1182011-08-23 20:17:13 +0000500 unsigned &StructuredIndex) {
Steve Naroff0cca7492008-05-01 22:18:59 +0000501 int maxElements = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Steve Naroff0cca7492008-05-01 22:18:59 +0000503 if (T->isArrayType())
504 maxElements = numArrayElements(T);
Douglas Gregorfb87b892010-04-26 21:31:17 +0000505 else if (T->isRecordType())
Steve Naroff0cca7492008-05-01 22:18:59 +0000506 maxElements = numStructUnionElements(T);
Eli Friedmanb85f7072008-05-19 19:16:24 +0000507 else if (T->isVectorType())
John McCall183700f2009-09-21 23:43:11 +0000508 maxElements = T->getAs<VectorType>()->getNumElements();
Steve Naroff0cca7492008-05-01 22:18:59 +0000509 else
510 assert(0 && "CheckImplicitInitList(): Illegal type");
Eli Friedmanb85f7072008-05-19 19:16:24 +0000511
Eli Friedman402256f2008-05-25 13:49:22 +0000512 if (maxElements == 0) {
Chris Lattner08202542009-02-24 22:50:46 +0000513 SemaRef.Diag(ParentIList->getInit(Index)->getLocStart(),
Eli Friedman402256f2008-05-25 13:49:22 +0000514 diag::err_implicit_empty_initializer);
Douglas Gregor4c678342009-01-28 21:54:33 +0000515 ++Index;
Eli Friedman402256f2008-05-25 13:49:22 +0000516 hadError = true;
517 return;
518 }
519
Douglas Gregor4c678342009-01-28 21:54:33 +0000520 // Build a structured initializer list corresponding to this subobject.
521 InitListExpr *StructuredSubobjectInitList
Mike Stump1eb44332009-09-09 15:08:12 +0000522 = getStructuredSubobjectInit(ParentIList, Index, T, StructuredList,
523 StructuredIndex,
Douglas Gregored8a93d2009-03-01 17:12:46 +0000524 SourceRange(ParentIList->getInit(Index)->getSourceRange().getBegin(),
525 ParentIList->getSourceRange().getEnd()));
Douglas Gregor4c678342009-01-28 21:54:33 +0000526 unsigned StructuredSubobjectInitIndex = 0;
Eli Friedmanb85f7072008-05-19 19:16:24 +0000527
Douglas Gregor4c678342009-01-28 21:54:33 +0000528 // Check the element types and build the structural subobject.
Douglas Gregor87fd7032009-02-02 17:43:21 +0000529 unsigned StartIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000530 CheckListElementTypes(Entity, ParentIList, T,
Anders Carlsson987dc6a2010-01-23 20:47:59 +0000531 /*SubobjectIsDesignatorContext=*/false, Index,
Mike Stump1eb44332009-09-09 15:08:12 +0000532 StructuredSubobjectInitList,
Eli Friedman629f1182011-08-23 20:17:13 +0000533 StructuredSubobjectInitIndex);
Douglas Gregor87fd7032009-02-02 17:43:21 +0000534 unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1);
Douglas Gregora6457962009-03-20 00:32:56 +0000535 StructuredSubobjectInitList->setType(T);
536
Douglas Gregored8a93d2009-03-01 17:12:46 +0000537 // Update the structured sub-object initializer so that it's ending
Douglas Gregor87fd7032009-02-02 17:43:21 +0000538 // range corresponds with the end of the last initializer it used.
539 if (EndIndex < ParentIList->getNumInits()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000540 SourceLocation EndLoc
Douglas Gregor87fd7032009-02-02 17:43:21 +0000541 = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
542 StructuredSubobjectInitList->setRBraceLoc(EndLoc);
543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000544
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000545 // Warn about missing braces.
546 if (T->isArrayType() || T->isRecordType()) {
Tanya Lattner47f164e2010-03-07 04:40:06 +0000547 SemaRef.Diag(StructuredSubobjectInitList->getLocStart(),
548 diag::warn_missing_braces)
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000549 << StructuredSubobjectInitList->getSourceRange()
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550 << FixItHint::CreateInsertion(StructuredSubobjectInitList->getLocStart(),
Douglas Gregor849b2432010-03-31 17:46:05 +0000551 "{")
552 << FixItHint::CreateInsertion(SemaRef.PP.getLocForEndOfToken(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000553 StructuredSubobjectInitList->getLocEnd()),
Douglas Gregor849b2432010-03-31 17:46:05 +0000554 "}");
Tanya Lattner1e1d3962010-03-07 04:17:15 +0000555 }
Steve Naroff0cca7492008-05-01 22:18:59 +0000556}
557
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000558void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000559 InitListExpr *IList, QualType &T,
Douglas Gregor4c678342009-01-28 21:54:33 +0000560 unsigned &Index,
561 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000562 unsigned &StructuredIndex,
563 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000564 assert(IList->isExplicit() && "Illegal Implicit InitListExpr");
Douglas Gregor4c678342009-01-28 21:54:33 +0000565 SyntacticToSemantic[IList] = StructuredList;
566 StructuredList->setSyntacticForm(IList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567 CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
Anders Carlsson46f46592010-01-23 19:55:29 +0000568 Index, StructuredList, StructuredIndex, TopLevelObject);
Douglas Gregor63982352010-07-13 18:40:04 +0000569 QualType ExprTy = T.getNonLValueExprType(SemaRef.Context);
570 IList->setType(ExprTy);
571 StructuredList->setType(ExprTy);
Eli Friedman638e1442008-05-25 13:22:35 +0000572 if (hadError)
573 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000574
Eli Friedman638e1442008-05-25 13:22:35 +0000575 if (Index < IList->getNumInits()) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000576 // We have leftover initializers
Eli Friedmane5408582009-05-29 20:20:05 +0000577 if (StructuredIndex == 1 &&
578 IsStringInit(StructuredList->getInit(0), T, SemaRef.Context)) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000579 unsigned DK = diag::warn_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000580 if (SemaRef.getLangOptions().CPlusPlus) {
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000581 DK = diag::err_excess_initializers_in_char_array_initializer;
Eli Friedmane5408582009-05-29 20:20:05 +0000582 hadError = true;
583 }
Eli Friedmanbb504d32008-05-19 20:12:18 +0000584 // Special-case
Chris Lattner08202542009-02-24 22:50:46 +0000585 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000586 << IList->getInit(Index)->getSourceRange();
Eli Friedmand8dc2102008-05-20 05:25:56 +0000587 } else if (!T->isIncompleteType()) {
Douglas Gregorb574e562009-01-30 22:26:29 +0000588 // Don't complain for incomplete types, since we'll get an error
589 // elsewhere
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000590 QualType CurrentObjectType = StructuredList->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000591 int initKind =
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000592 CurrentObjectType->isArrayType()? 0 :
593 CurrentObjectType->isVectorType()? 1 :
594 CurrentObjectType->isScalarType()? 2 :
595 CurrentObjectType->isUnionType()? 3 :
596 4;
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000597
598 unsigned DK = diag::warn_excess_initializers;
Eli Friedmane5408582009-05-29 20:20:05 +0000599 if (SemaRef.getLangOptions().CPlusPlus) {
600 DK = diag::err_excess_initializers;
601 hadError = true;
602 }
Nate Begeman08634522009-07-07 21:53:06 +0000603 if (SemaRef.getLangOptions().OpenCL && initKind == 1) {
604 DK = diag::err_excess_initializers;
605 hadError = true;
606 }
Douglas Gregor7c53ca62009-02-18 22:23:55 +0000607
Chris Lattner08202542009-02-24 22:50:46 +0000608 SemaRef.Diag(IList->getInit(Index)->getLocStart(), DK)
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000609 << initKind << IList->getInit(Index)->getSourceRange();
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000610 }
611 }
Eli Friedmancda25a92008-05-19 20:20:43 +0000612
Eli Friedman759f2522009-05-16 11:45:48 +0000613 if (T->isScalarType() && !TopLevelObject)
Chris Lattner08202542009-02-24 22:50:46 +0000614 SemaRef.Diag(IList->getLocStart(), diag::warn_braces_around_scalar_init)
Douglas Gregora3a83512009-04-01 23:51:29 +0000615 << IList->getSourceRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000616 << FixItHint::CreateRemoval(IList->getLocStart())
617 << FixItHint::CreateRemoval(IList->getLocEnd());
Steve Naroff0cca7492008-05-01 22:18:59 +0000618}
619
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000620void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000621 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000622 QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000623 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +0000624 unsigned &Index,
625 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000626 unsigned &StructuredIndex,
627 bool TopLevelObject) {
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000628 if (DeclType->isScalarType()) {
Anders Carlsson46f46592010-01-23 19:55:29 +0000629 CheckScalarType(Entity, IList, DeclType, Index,
630 StructuredList, StructuredIndex);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000631 } else if (DeclType->isVectorType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000632 CheckVectorType(Entity, IList, DeclType, Index,
Anders Carlsson46f46592010-01-23 19:55:29 +0000633 StructuredList, StructuredIndex);
Douglas Gregord7eb8462009-01-30 17:31:00 +0000634 } else if (DeclType->isAggregateType()) {
635 if (DeclType->isRecordType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000636 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Anders Carlsson2bbae5d2010-01-23 20:20:40 +0000637 CheckStructUnionTypes(Entity, IList, DeclType, RD->field_begin(),
Douglas Gregor4c678342009-01-28 21:54:33 +0000638 SubobjectIsDesignatorContext, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000639 StructuredList, StructuredIndex,
640 TopLevelObject);
Douglas Gregor87f55cf2009-01-22 23:26:18 +0000641 } else if (DeclType->isArrayType()) {
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000642 llvm::APSInt Zero(
Chris Lattner08202542009-02-24 22:50:46 +0000643 SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
Douglas Gregorf6c717c2009-01-23 16:54:12 +0000644 false);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000645 CheckArrayType(Entity, IList, DeclType, Zero,
Anders Carlsson784f6992010-01-23 20:13:41 +0000646 SubobjectIsDesignatorContext, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000647 StructuredList, StructuredIndex);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000648 } else
Douglas Gregor4c678342009-01-28 21:54:33 +0000649 assert(0 && "Aggregate that isn't a structure or array?!");
Steve Naroff61353522008-08-10 16:05:48 +0000650 } else if (DeclType->isVoidType() || DeclType->isFunctionType()) {
651 // This type is invalid, issue a diagnostic.
Douglas Gregor4c678342009-01-28 21:54:33 +0000652 ++Index;
Chris Lattner08202542009-02-24 22:50:46 +0000653 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000654 << DeclType;
Eli Friedmand8dc2102008-05-20 05:25:56 +0000655 hadError = true;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000656 } else if (DeclType->isRecordType()) {
657 // C++ [dcl.init]p14:
658 // [...] If the class is an aggregate (8.5.1), and the initializer
659 // is a brace-enclosed list, see 8.5.1.
660 //
661 // Note: 8.5.1 is handled below; here, we diagnose the case where
662 // we have an initializer list and a destination type that is not
663 // an aggregate.
664 // FIXME: In C++0x, this is yet another form of initialization.
Chris Lattner08202542009-02-24 22:50:46 +0000665 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000666 << DeclType << IList->getSourceRange();
667 hadError = true;
668 } else if (DeclType->isReferenceType()) {
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000669 CheckReferenceType(Entity, IList, DeclType, Index,
670 StructuredList, StructuredIndex);
John McCallc12c5bb2010-05-15 11:32:37 +0000671 } else if (DeclType->isObjCObjectType()) {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000672 SemaRef.Diag(IList->getLocStart(), diag::err_init_objc_class)
673 << DeclType;
674 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000675 } else {
Douglas Gregor4d9e7382010-05-03 18:24:37 +0000676 SemaRef.Diag(IList->getLocStart(), diag::err_illegal_initializer_type)
677 << DeclType;
678 hadError = true;
Steve Naroff0cca7492008-05-01 22:18:59 +0000679 }
680}
681
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000682void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000683 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +0000684 QualType ElemType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000685 unsigned &Index,
686 InitListExpr *StructuredList,
687 unsigned &StructuredIndex) {
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000688 Expr *expr = IList->getInit(Index);
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000689 if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
690 unsigned newIndex = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +0000691 unsigned newStructuredIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000692 InitListExpr *newStructuredList
Douglas Gregor4c678342009-01-28 21:54:33 +0000693 = getStructuredSubobjectInit(IList, Index, ElemType,
694 StructuredList, StructuredIndex,
695 SubInitList->getSourceRange());
Anders Carlsson46f46592010-01-23 19:55:29 +0000696 CheckExplicitInitList(Entity, SubInitList, ElemType, newIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +0000697 newStructuredList, newStructuredIndex);
698 ++StructuredIndex;
699 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000700 return;
Eli Friedmanc9c0ea62008-05-19 20:00:43 +0000701 } else if (ElemType->isScalarType()) {
John McCallfef8b342011-02-21 07:57:55 +0000702 return CheckScalarType(Entity, IList, ElemType, Index,
703 StructuredList, StructuredIndex);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000704 } else if (ElemType->isReferenceType()) {
John McCallfef8b342011-02-21 07:57:55 +0000705 return CheckReferenceType(Entity, IList, ElemType, Index,
706 StructuredList, StructuredIndex);
707 }
Anders Carlssond28b4282009-08-27 17:18:13 +0000708
John McCallfef8b342011-02-21 07:57:55 +0000709 if (const ArrayType *arrayType = SemaRef.Context.getAsArrayType(ElemType)) {
710 // arrayType can be incomplete if we're initializing a flexible
711 // array member. There's nothing we can do with the completed
712 // type here, though.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000713
John McCallfef8b342011-02-21 07:57:55 +0000714 if (Expr *Str = IsStringInit(expr, arrayType, SemaRef.Context)) {
715 CheckStringInit(Str, ElemType, arrayType, SemaRef);
716 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Douglas Gregor930d8b52009-01-30 22:09:00 +0000717 ++Index;
John McCallfef8b342011-02-21 07:57:55 +0000718 return;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000719 }
John McCallfef8b342011-02-21 07:57:55 +0000720
721 // Fall through for subaggregate initialization.
722
723 } else if (SemaRef.getLangOptions().CPlusPlus) {
724 // C++ [dcl.init.aggr]p12:
725 // All implicit type conversions (clause 4) are considered when
Rafael Espindola12ce0a02011-07-14 22:58:04 +0000726 // initializing the aggregate member with an ini- tializer from
John McCallfef8b342011-02-21 07:57:55 +0000727 // an initializer-list. If the initializer can initialize a
728 // member, the member is initialized. [...]
729
730 // FIXME: Better EqualLoc?
731 InitializationKind Kind =
732 InitializationKind::CreateCopy(expr->getLocStart(), SourceLocation());
733 InitializationSequence Seq(SemaRef, Entity, Kind, &expr, 1);
734
735 if (Seq) {
736 ExprResult Result =
737 Seq.Perform(SemaRef, Entity, Kind, MultiExprArg(&expr, 1));
738 if (Result.isInvalid())
739 hadError = true;
740
741 UpdateStructuredListElement(StructuredList, StructuredIndex,
742 Result.takeAs<Expr>());
743 ++Index;
744 return;
745 }
746
747 // Fall through for subaggregate initialization
748 } else {
749 // C99 6.7.8p13:
750 //
751 // The initializer for a structure or union object that has
752 // automatic storage duration shall be either an initializer
753 // list as described below, or a single expression that has
754 // compatible structure or union type. In the latter case, the
755 // initial value of the object, including unnamed members, is
756 // that of the expression.
John Wiegley429bb272011-04-08 18:41:53 +0000757 ExprResult ExprRes = SemaRef.Owned(expr);
John McCallfef8b342011-02-21 07:57:55 +0000758 if ((ElemType->isRecordType() || ElemType->isVectorType()) &&
John Wiegley429bb272011-04-08 18:41:53 +0000759 SemaRef.CheckSingleAssignmentConstraints(ElemType, ExprRes)
John McCallfef8b342011-02-21 07:57:55 +0000760 == Sema::Compatible) {
John Wiegley429bb272011-04-08 18:41:53 +0000761 if (ExprRes.isInvalid())
762 hadError = true;
763 else {
764 ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.take());
765 if (ExprRes.isInvalid())
766 hadError = true;
767 }
768 UpdateStructuredListElement(StructuredList, StructuredIndex,
769 ExprRes.takeAs<Expr>());
John McCallfef8b342011-02-21 07:57:55 +0000770 ++Index;
771 return;
772 }
John Wiegley429bb272011-04-08 18:41:53 +0000773 ExprRes.release();
John McCallfef8b342011-02-21 07:57:55 +0000774 // Fall through for subaggregate initialization
775 }
776
777 // C++ [dcl.init.aggr]p12:
778 //
779 // [...] Otherwise, if the member is itself a non-empty
780 // subaggregate, brace elision is assumed and the initializer is
781 // considered for the initialization of the first member of
782 // the subaggregate.
Tanya Lattner61b4bc82011-07-15 23:07:01 +0000783 if (!SemaRef.getLangOptions().OpenCL &&
784 (ElemType->isAggregateType() || ElemType->isVectorType())) {
John McCallfef8b342011-02-21 07:57:55 +0000785 CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
786 StructuredIndex);
787 ++StructuredIndex;
788 } else {
789 // We cannot initialize this element, so let
790 // PerformCopyInitialization produce the appropriate diagnostic.
791 SemaRef.PerformCopyInitialization(Entity, SourceLocation(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000792 SemaRef.Owned(expr),
793 /*TopLevelOfInitList=*/true);
John McCallfef8b342011-02-21 07:57:55 +0000794 hadError = true;
795 ++Index;
796 ++StructuredIndex;
Douglas Gregor930d8b52009-01-30 22:09:00 +0000797 }
Eli Friedmanb85f7072008-05-19 19:16:24 +0000798}
799
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000800void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000801 InitListExpr *IList, QualType DeclType,
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +0000802 unsigned &Index,
Douglas Gregor4c678342009-01-28 21:54:33 +0000803 InitListExpr *StructuredList,
804 unsigned &StructuredIndex) {
John McCallb934c2d2010-11-11 00:46:36 +0000805 if (Index >= IList->getNumInits()) {
Chris Lattner08202542009-02-24 22:50:46 +0000806 SemaRef.Diag(IList->getLocStart(), diag::err_empty_scalar_initializer)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000807 << IList->getSourceRange();
Eli Friedmanbb504d32008-05-19 20:12:18 +0000808 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +0000809 ++Index;
810 ++StructuredIndex;
Eli Friedmanbb504d32008-05-19 20:12:18 +0000811 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000812 }
John McCallb934c2d2010-11-11 00:46:36 +0000813
814 Expr *expr = IList->getInit(Index);
815 if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
816 SemaRef.Diag(SubIList->getLocStart(),
817 diag::warn_many_braces_around_scalar_init)
818 << SubIList->getSourceRange();
819
820 CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
821 StructuredIndex);
822 return;
823 } else if (isa<DesignatedInitExpr>(expr)) {
824 SemaRef.Diag(expr->getSourceRange().getBegin(),
825 diag::err_designator_for_scalar_init)
826 << DeclType << expr->getSourceRange();
827 hadError = true;
828 ++Index;
829 ++StructuredIndex;
830 return;
831 }
832
833 ExprResult Result =
834 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000835 SemaRef.Owned(expr),
836 /*TopLevelOfInitList=*/true);
John McCallb934c2d2010-11-11 00:46:36 +0000837
838 Expr *ResultExpr = 0;
839
840 if (Result.isInvalid())
841 hadError = true; // types weren't compatible.
842 else {
843 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000844
John McCallb934c2d2010-11-11 00:46:36 +0000845 if (ResultExpr != expr) {
846 // The type was promoted, update initializer list.
847 IList->setInit(Index, ResultExpr);
848 }
849 }
850 if (hadError)
851 ++StructuredIndex;
852 else
853 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
854 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +0000855}
856
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000857void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
858 InitListExpr *IList, QualType DeclType,
Douglas Gregor930d8b52009-01-30 22:09:00 +0000859 unsigned &Index,
860 InitListExpr *StructuredList,
861 unsigned &StructuredIndex) {
862 if (Index < IList->getNumInits()) {
863 Expr *expr = IList->getInit(Index);
864 if (isa<InitListExpr>(expr)) {
Chris Lattner08202542009-02-24 22:50:46 +0000865 SemaRef.Diag(IList->getLocStart(), diag::err_init_non_aggr_init_list)
Douglas Gregor930d8b52009-01-30 22:09:00 +0000866 << DeclType << IList->getSourceRange();
867 hadError = true;
868 ++Index;
869 ++StructuredIndex;
870 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000871 }
Douglas Gregor930d8b52009-01-30 22:09:00 +0000872
John McCall60d7b3a2010-08-24 06:29:42 +0000873 ExprResult Result =
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000874 SemaRef.PerformCopyInitialization(Entity, expr->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000875 SemaRef.Owned(expr),
876 /*TopLevelOfInitList=*/true);
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000877
878 if (Result.isInvalid())
Douglas Gregor930d8b52009-01-30 22:09:00 +0000879 hadError = true;
Anders Carlssona6fe0bf2010-01-29 02:47:33 +0000880
881 expr = Result.takeAs<Expr>();
882 IList->setInit(Index, expr);
883
Douglas Gregor930d8b52009-01-30 22:09:00 +0000884 if (hadError)
885 ++StructuredIndex;
886 else
887 UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
888 ++Index;
889 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +0000890 // FIXME: It would be wonderful if we could point at the actual member. In
891 // general, it would be useful to pass location information down the stack,
892 // so that we know the location (or decl) of the "current object" being
893 // initialized.
Mike Stump1eb44332009-09-09 15:08:12 +0000894 SemaRef.Diag(IList->getLocStart(),
Douglas Gregor930d8b52009-01-30 22:09:00 +0000895 diag::err_init_reference_member_uninitialized)
896 << DeclType
897 << IList->getSourceRange();
898 hadError = true;
899 ++Index;
900 ++StructuredIndex;
901 return;
902 }
903}
904
Anders Carlsson8ff9e862010-01-23 23:23:01 +0000905void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
Anders Carlsson46f46592010-01-23 19:55:29 +0000906 InitListExpr *IList, QualType DeclType,
Douglas Gregor4c678342009-01-28 21:54:33 +0000907 unsigned &Index,
908 InitListExpr *StructuredList,
909 unsigned &StructuredIndex) {
John McCall20e047a2010-10-30 00:11:39 +0000910 if (Index >= IList->getNumInits())
911 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000912
John McCall20e047a2010-10-30 00:11:39 +0000913 const VectorType *VT = DeclType->getAs<VectorType>();
914 unsigned maxElements = VT->getNumElements();
915 unsigned numEltsInit = 0;
916 QualType elementType = VT->getElementType();
Anders Carlsson46f46592010-01-23 19:55:29 +0000917
John McCall20e047a2010-10-30 00:11:39 +0000918 if (!SemaRef.getLangOptions().OpenCL) {
919 // If the initializing element is a vector, try to copy-initialize
920 // instead of breaking it apart (which is doomed to failure anyway).
921 Expr *Init = IList->getInit(Index);
922 if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
923 ExprResult Result =
924 SemaRef.PerformCopyInitialization(Entity, Init->getLocStart(),
Jeffrey Yasskin19159132011-07-26 23:20:30 +0000925 SemaRef.Owned(Init),
926 /*TopLevelOfInitList=*/true);
John McCall20e047a2010-10-30 00:11:39 +0000927
928 Expr *ResultExpr = 0;
929 if (Result.isInvalid())
930 hadError = true; // types weren't compatible.
931 else {
932 ResultExpr = Result.takeAs<Expr>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000933
John McCall20e047a2010-10-30 00:11:39 +0000934 if (ResultExpr != Init) {
935 // The type was promoted, update initializer list.
936 IList->setInit(Index, ResultExpr);
Nate Begeman2ef13e52009-08-10 23:49:36 +0000937 }
938 }
John McCall20e047a2010-10-30 00:11:39 +0000939 if (hadError)
940 ++StructuredIndex;
941 else
942 UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
943 ++Index;
944 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
John McCall20e047a2010-10-30 00:11:39 +0000947 InitializedEntity ElementEntity =
948 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000949
John McCall20e047a2010-10-30 00:11:39 +0000950 for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) {
951 // Don't attempt to go past the end of the init list
952 if (Index >= IList->getNumInits())
953 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000954
John McCall20e047a2010-10-30 00:11:39 +0000955 ElementEntity.setElementIndex(Index);
956 CheckSubElementType(ElementEntity, IList, elementType, Index,
957 StructuredList, StructuredIndex);
958 }
959 return;
Steve Naroff0cca7492008-05-01 22:18:59 +0000960 }
John McCall20e047a2010-10-30 00:11:39 +0000961
962 InitializedEntity ElementEntity =
963 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000964
John McCall20e047a2010-10-30 00:11:39 +0000965 // OpenCL initializers allows vectors to be constructed from vectors.
966 for (unsigned i = 0; i < maxElements; ++i) {
967 // Don't attempt to go past the end of the init list
968 if (Index >= IList->getNumInits())
969 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000970
John McCall20e047a2010-10-30 00:11:39 +0000971 ElementEntity.setElementIndex(Index);
972
973 QualType IType = IList->getInit(Index)->getType();
974 if (!IType->isVectorType()) {
975 CheckSubElementType(ElementEntity, IList, elementType, Index,
976 StructuredList, StructuredIndex);
977 ++numEltsInit;
978 } else {
979 QualType VecType;
980 const VectorType *IVT = IType->getAs<VectorType>();
981 unsigned numIElts = IVT->getNumElements();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000982
John McCall20e047a2010-10-30 00:11:39 +0000983 if (IType->isExtVectorType())
984 VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
985 else
986 VecType = SemaRef.Context.getVectorType(elementType, numIElts,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000987 IVT->getVectorKind());
John McCall20e047a2010-10-30 00:11:39 +0000988 CheckSubElementType(ElementEntity, IList, VecType, Index,
989 StructuredList, StructuredIndex);
990 numEltsInit += numIElts;
991 }
992 }
993
994 // OpenCL requires all elements to be initialized.
995 if (numEltsInit != maxElements)
996 if (SemaRef.getLangOptions().OpenCL)
997 SemaRef.Diag(IList->getSourceRange().getBegin(),
998 diag::err_vector_incorrect_num_initializers)
999 << (numEltsInit < maxElements) << maxElements << numEltsInit;
Steve Naroff0cca7492008-05-01 22:18:59 +00001000}
1001
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001002void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
Anders Carlsson784f6992010-01-23 20:13:41 +00001003 InitListExpr *IList, QualType &DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001004 llvm::APSInt elementIndex,
Mike Stump1eb44332009-09-09 15:08:12 +00001005 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001006 unsigned &Index,
1007 InitListExpr *StructuredList,
1008 unsigned &StructuredIndex) {
John McCallce6c9b72011-02-21 07:22:22 +00001009 const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1010
Steve Naroff0cca7492008-05-01 22:18:59 +00001011 // Check for the special-case of initializing an array with a string.
1012 if (Index < IList->getNumInits()) {
John McCallce6c9b72011-02-21 07:22:22 +00001013 if (Expr *Str = IsStringInit(IList->getInit(Index), arrayType,
Chris Lattner79e079d2009-02-24 23:10:27 +00001014 SemaRef.Context)) {
John McCallfef8b342011-02-21 07:57:55 +00001015 CheckStringInit(Str, DeclType, arrayType, SemaRef);
Douglas Gregor4c678342009-01-28 21:54:33 +00001016 // We place the string literal directly into the resulting
1017 // initializer list. This is the only place where the structure
1018 // of the structured initializer list doesn't match exactly,
1019 // because doing so would involve allocating one character
1020 // constant for each string.
Chris Lattnerf71ae8d2009-02-24 22:41:04 +00001021 UpdateStructuredListElement(StructuredList, StructuredIndex, Str);
Chris Lattner08202542009-02-24 22:50:46 +00001022 StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001023 ++Index;
Steve Naroff0cca7492008-05-01 22:18:59 +00001024 return;
1025 }
1026 }
John McCallce6c9b72011-02-21 07:22:22 +00001027 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
Eli Friedman638e1442008-05-25 13:22:35 +00001028 // Check for VLAs; in standard C it would be possible to check this
1029 // earlier, but I don't know where clang accepts VLAs (gcc accepts
1030 // them in all sorts of strange places).
Chris Lattner08202542009-02-24 22:50:46 +00001031 SemaRef.Diag(VAT->getSizeExpr()->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001032 diag::err_variable_object_no_init)
1033 << VAT->getSizeExpr()->getSourceRange();
Eli Friedman638e1442008-05-25 13:22:35 +00001034 hadError = true;
Douglas Gregor4c678342009-01-28 21:54:33 +00001035 ++Index;
1036 ++StructuredIndex;
Eli Friedman638e1442008-05-25 13:22:35 +00001037 return;
1038 }
1039
Douglas Gregor05c13a32009-01-22 00:58:24 +00001040 // We might know the maximum number of elements in advance.
Douglas Gregor4c678342009-01-28 21:54:33 +00001041 llvm::APSInt maxElements(elementIndex.getBitWidth(),
1042 elementIndex.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001043 bool maxElementsKnown = false;
John McCallce6c9b72011-02-21 07:22:22 +00001044 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001045 maxElements = CAT->getSize();
Jay Foad9f71a8f2010-12-07 08:25:34 +00001046 elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001047 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001048 maxElementsKnown = true;
1049 }
1050
John McCallce6c9b72011-02-21 07:22:22 +00001051 QualType elementType = arrayType->getElementType();
Douglas Gregor05c13a32009-01-22 00:58:24 +00001052 while (Index < IList->getNumInits()) {
1053 Expr *Init = IList->getInit(Index);
1054 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001055 // If we're not the subobject that matches up with the '{' for
1056 // the designator, we shouldn't be handling the
1057 // designator. Return immediately.
1058 if (!SubobjectIsDesignatorContext)
1059 return;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001060
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001061 // Handle this designated initializer. elementIndex will be
1062 // updated to be the next array element we'll initialize.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001063 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001064 DeclType, 0, &elementIndex, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001065 StructuredList, StructuredIndex, true,
1066 false)) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001067 hadError = true;
1068 continue;
1069 }
1070
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001071 if (elementIndex.getBitWidth() > maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001072 maxElements = maxElements.extend(elementIndex.getBitWidth());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001073 else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001074 elementIndex = elementIndex.extend(maxElements.getBitWidth());
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001075 elementIndex.setIsUnsigned(maxElements.isUnsigned());
Douglas Gregorf6c717c2009-01-23 16:54:12 +00001076
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001077 // If the array is of incomplete type, keep track of the number of
1078 // elements in the initializer.
1079 if (!maxElementsKnown && elementIndex > maxElements)
1080 maxElements = elementIndex;
1081
Douglas Gregor05c13a32009-01-22 00:58:24 +00001082 continue;
1083 }
1084
1085 // If we know the maximum number of elements, and we've already
1086 // hit it, stop consuming elements in the initializer list.
1087 if (maxElementsKnown && elementIndex == maxElements)
Steve Naroff0cca7492008-05-01 22:18:59 +00001088 break;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001089
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001090 InitializedEntity ElementEntity =
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001091 InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001092 Entity);
1093 // Check this element.
1094 CheckSubElementType(ElementEntity, IList, elementType, Index,
1095 StructuredList, StructuredIndex);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001096 ++elementIndex;
1097
1098 // If the array is of incomplete type, keep track of the number of
1099 // elements in the initializer.
1100 if (!maxElementsKnown && elementIndex > maxElements)
1101 maxElements = elementIndex;
Steve Naroff0cca7492008-05-01 22:18:59 +00001102 }
Eli Friedman587cbdf2009-05-29 20:17:55 +00001103 if (!hadError && DeclType->isIncompleteArrayType()) {
Steve Naroff0cca7492008-05-01 22:18:59 +00001104 // If this is an incomplete array type, the actual type needs to
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001105 // be calculated here.
Douglas Gregore3fa2de2009-01-23 18:58:42 +00001106 llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
Douglas Gregor05c13a32009-01-22 00:58:24 +00001107 if (maxElements == Zero) {
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001108 // Sizing an array implicitly to zero is not allowed by ISO C,
1109 // but is supported by GNU.
Chris Lattner08202542009-02-24 22:50:46 +00001110 SemaRef.Diag(IList->getLocStart(),
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001111 diag::ext_typecheck_zero_array_size);
Steve Naroff0cca7492008-05-01 22:18:59 +00001112 }
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001113
Mike Stump1eb44332009-09-09 15:08:12 +00001114 DeclType = SemaRef.Context.getConstantArrayType(elementType, maxElements,
Daniel Dunbar396f0bf2008-08-18 20:28:46 +00001115 ArrayType::Normal, 0);
Steve Naroff0cca7492008-05-01 22:18:59 +00001116 }
1117}
1118
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001119bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1120 Expr *InitExpr,
1121 FieldDecl *Field,
1122 bool TopLevelObject) {
1123 // Handle GNU flexible array initializers.
1124 unsigned FlexArrayDiag;
1125 if (isa<InitListExpr>(InitExpr) &&
1126 cast<InitListExpr>(InitExpr)->getNumInits() == 0) {
1127 // Empty flexible array init always allowed as an extension
1128 FlexArrayDiag = diag::ext_flexible_array_init;
1129 } else if (SemaRef.getLangOptions().CPlusPlus) {
1130 // Disallow flexible array init in C++; it is not required for gcc
1131 // compatibility, and it needs work to IRGen correctly in general.
1132 FlexArrayDiag = diag::err_flexible_array_init;
1133 } else if (!TopLevelObject) {
1134 // Disallow flexible array init on non-top-level object
1135 FlexArrayDiag = diag::err_flexible_array_init;
1136 } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
1137 // Disallow flexible array init on anything which is not a variable.
1138 FlexArrayDiag = diag::err_flexible_array_init;
1139 } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
1140 // Disallow flexible array init on local variables.
1141 FlexArrayDiag = diag::err_flexible_array_init;
1142 } else {
1143 // Allow other cases.
1144 FlexArrayDiag = diag::ext_flexible_array_init;
1145 }
1146
1147 SemaRef.Diag(InitExpr->getSourceRange().getBegin(),
1148 FlexArrayDiag)
1149 << InitExpr->getSourceRange().getBegin();
1150 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
1151 << Field;
1152
1153 return FlexArrayDiag != diag::ext_flexible_array_init;
1154}
1155
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001156void InitListChecker::CheckStructUnionTypes(const InitializedEntity &Entity,
Anders Carlsson2bbae5d2010-01-23 20:20:40 +00001157 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001158 QualType DeclType,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001159 RecordDecl::field_iterator Field,
Mike Stump1eb44332009-09-09 15:08:12 +00001160 bool SubobjectIsDesignatorContext,
Douglas Gregor4c678342009-01-28 21:54:33 +00001161 unsigned &Index,
1162 InitListExpr *StructuredList,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001163 unsigned &StructuredIndex,
1164 bool TopLevelObject) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001165 RecordDecl* structDecl = DeclType->getAs<RecordType>()->getDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Eli Friedmanb85f7072008-05-19 19:16:24 +00001167 // If the record is invalid, some of it's members are invalid. To avoid
1168 // confusion, we forgo checking the intializer for the entire record.
1169 if (structDecl->isInvalidDecl()) {
1170 hadError = true;
1171 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001172 }
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001173
1174 if (DeclType->isUnionType() && IList->getNumInits() == 0) {
1175 // Value-initialize the first named member of the union.
Ted Kremenek6217b802009-07-29 21:53:49 +00001176 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001177 for (RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregor3498bdb2009-01-29 17:44:32 +00001178 Field != FieldEnd; ++Field) {
1179 if (Field->getDeclName()) {
1180 StructuredList->setInitializedFieldInUnion(*Field);
1181 break;
1182 }
1183 }
1184 return;
1185 }
1186
Douglas Gregor05c13a32009-01-22 00:58:24 +00001187 // If structDecl is a forward declaration, this loop won't do
1188 // anything except look at designated initializers; That's okay,
1189 // because an error should get printed out elsewhere. It might be
1190 // worthwhile to skip over the rest of the initializer, though.
Ted Kremenek6217b802009-07-29 21:53:49 +00001191 RecordDecl *RD = DeclType->getAs<RecordType>()->getDecl();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001192 RecordDecl::field_iterator FieldEnd = RD->field_end();
Douglas Gregordfb5e592009-02-12 19:00:39 +00001193 bool InitializedSomething = false;
John McCall80639de2010-03-11 19:32:38 +00001194 bool CheckForMissingFields = true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001195 while (Index < IList->getNumInits()) {
1196 Expr *Init = IList->getInit(Index);
1197
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. Field will be updated to
1206 // the next field that we'll be initializing.
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001207 if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
Douglas Gregor4c678342009-01-28 21:54:33 +00001208 DeclType, &Field, 0, Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001209 StructuredList, StructuredIndex,
1210 true, TopLevelObject))
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001211 hadError = true;
1212
Douglas Gregordfb5e592009-02-12 19:00:39 +00001213 InitializedSomething = true;
John McCall80639de2010-03-11 19:32:38 +00001214
1215 // Disable check for missing fields when designators are used.
1216 // This matches gcc behaviour.
1217 CheckForMissingFields = false;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001218 continue;
1219 }
1220
1221 if (Field == FieldEnd) {
1222 // We've run out of fields. We're done.
1223 break;
1224 }
1225
Douglas Gregordfb5e592009-02-12 19:00:39 +00001226 // We've already initialized a member of a union. We're done.
1227 if (InitializedSomething && DeclType->isUnionType())
1228 break;
1229
Douglas Gregor44b43212008-12-11 16:49:14 +00001230 // If we've hit the flexible array member at the end, we're done.
1231 if (Field->getType()->isIncompleteArrayType())
1232 break;
1233
Douglas Gregor0bb76892009-01-29 16:53:55 +00001234 if (Field->isUnnamedBitfield()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001235 // Don't initialize unnamed bitfields, e.g. "int : 20;"
Douglas Gregor05c13a32009-01-22 00:58:24 +00001236 ++Field;
Eli Friedmanb85f7072008-05-19 19:16:24 +00001237 continue;
Steve Naroff0cca7492008-05-01 22:18:59 +00001238 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001239
Douglas Gregor54001c12011-06-29 21:51:31 +00001240 // Make sure we can use this declaration.
1241 if (SemaRef.DiagnoseUseOfDecl(*Field,
1242 IList->getInit(Index)->getLocStart())) {
1243 ++Index;
1244 ++Field;
1245 hadError = true;
1246 continue;
1247 }
1248
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001249 InitializedEntity MemberEntity =
1250 InitializedEntity::InitializeMember(*Field, &Entity);
1251 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
1252 StructuredList, StructuredIndex);
Douglas Gregordfb5e592009-02-12 19:00:39 +00001253 InitializedSomething = true;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001254
1255 if (DeclType->isUnionType()) {
1256 // Initialize the first field within the union.
1257 StructuredList->setInitializedFieldInUnion(*Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001258 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00001259
1260 ++Field;
Steve Naroff0cca7492008-05-01 22:18:59 +00001261 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001262
John McCall80639de2010-03-11 19:32:38 +00001263 // Emit warnings for missing struct field initializers.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001264 if (InitializedSomething && CheckForMissingFields && Field != FieldEnd &&
John McCall80639de2010-03-11 19:32:38 +00001265 !Field->getType()->isIncompleteArrayType() && !DeclType->isUnionType()) {
1266 // It is possible we have one or more unnamed bitfields remaining.
1267 // Find first (if any) named field and emit warning.
1268 for (RecordDecl::field_iterator it = Field, end = RD->field_end();
1269 it != end; ++it) {
1270 if (!it->isUnnamedBitfield()) {
1271 SemaRef.Diag(IList->getSourceRange().getEnd(),
1272 diag::warn_missing_field_initializers) << it->getName();
1273 break;
1274 }
1275 }
1276 }
1277
Mike Stump1eb44332009-09-09 15:08:12 +00001278 if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() ||
Douglas Gregora6457962009-03-20 00:32:56 +00001279 Index >= IList->getNumInits())
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001280 return;
1281
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001282 if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
1283 TopLevelObject)) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001284 hadError = true;
Douglas Gregora6457962009-03-20 00:32:56 +00001285 ++Index;
1286 return;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001287 }
1288
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001289 InitializedEntity MemberEntity =
1290 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001291
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001292 if (isa<InitListExpr>(IList->getInit(Index)))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001293 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001294 StructuredList, StructuredIndex);
1295 else
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001296 CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
Anders Carlsson987dc6a2010-01-23 20:47:59 +00001297 StructuredList, StructuredIndex);
Steve Naroff0cca7492008-05-01 22:18:59 +00001298}
Steve Naroff0cca7492008-05-01 22:18:59 +00001299
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001300/// \brief Expand a field designator that refers to a member of an
1301/// anonymous struct or union into a series of field designators that
1302/// refers to the field within the appropriate subobject.
1303///
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001304static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
Mike Stump1eb44332009-09-09 15:08:12 +00001305 DesignatedInitExpr *DIE,
1306 unsigned DesigIdx,
Francois Picheta0e27f02010-12-22 03:46:10 +00001307 IndirectFieldDecl *IndirectField) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001308 typedef DesignatedInitExpr::Designator Designator;
1309
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001310 // Build the replacement designators.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001311 SmallVector<Designator, 4> Replacements;
Francois Picheta0e27f02010-12-22 03:46:10 +00001312 for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
1313 PE = IndirectField->chain_end(); PI != PE; ++PI) {
1314 if (PI + 1 == PE)
Mike Stump1eb44332009-09-09 15:08:12 +00001315 Replacements.push_back(Designator((IdentifierInfo *)0,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001316 DIE->getDesignator(DesigIdx)->getDotLoc(),
1317 DIE->getDesignator(DesigIdx)->getFieldLoc()));
1318 else
1319 Replacements.push_back(Designator((IdentifierInfo *)0, SourceLocation(),
1320 SourceLocation()));
Francois Picheta0e27f02010-12-22 03:46:10 +00001321 assert(isa<FieldDecl>(*PI));
1322 Replacements.back().setField(cast<FieldDecl>(*PI));
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001323 }
1324
1325 // Expand the current designator into the set of replacement
1326 // designators, so we have a full subobject path down to where the
1327 // member of the anonymous struct/union is actually stored.
Douglas Gregor319d57f2010-01-06 23:17:19 +00001328 DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001329 &Replacements[0] + Replacements.size());
Francois Picheta0e27f02010-12-22 03:46:10 +00001330}
Mike Stump1eb44332009-09-09 15:08:12 +00001331
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001332/// \brief Given an implicit anonymous field, search the IndirectField that
Francois Picheta0e27f02010-12-22 03:46:10 +00001333/// corresponds to FieldName.
1334static IndirectFieldDecl *FindIndirectFieldDesignator(FieldDecl *AnonField,
1335 IdentifierInfo *FieldName) {
1336 assert(AnonField->isAnonymousStructOrUnion());
1337 Decl *NextDecl = AnonField->getNextDeclInContext();
1338 while (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(NextDecl)) {
1339 if (FieldName && FieldName == IF->getAnonField()->getIdentifier())
1340 return IF;
1341 NextDecl = NextDecl->getNextDeclInContext();
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001342 }
Francois Picheta0e27f02010-12-22 03:46:10 +00001343 return 0;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001344}
1345
Douglas Gregor05c13a32009-01-22 00:58:24 +00001346/// @brief Check the well-formedness of a C99 designated initializer.
1347///
1348/// Determines whether the designated initializer @p DIE, which
1349/// resides at the given @p Index within the initializer list @p
1350/// IList, is well-formed for a current object of type @p DeclType
1351/// (C99 6.7.8). The actual subobject that this designator refers to
Mike Stump1eb44332009-09-09 15:08:12 +00001352/// within the current subobject is returned in either
Douglas Gregor4c678342009-01-28 21:54:33 +00001353/// @p NextField or @p NextElementIndex (whichever is appropriate).
Douglas Gregor05c13a32009-01-22 00:58:24 +00001354///
1355/// @param IList The initializer list in which this designated
1356/// initializer occurs.
1357///
Douglas Gregor71199712009-04-15 04:56:10 +00001358/// @param DIE The designated initializer expression.
1359///
1360/// @param DesigIdx The index of the current designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001361///
1362/// @param DeclType The type of the "current object" (C99 6.7.8p17),
1363/// into which the designation in @p DIE should refer.
1364///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001365/// @param NextField If non-NULL and the first designator in @p DIE is
1366/// a field, this will be set to the field declaration corresponding
1367/// to the field named by the designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001368///
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001369/// @param NextElementIndex If non-NULL and the first designator in @p
1370/// DIE is an array designator or GNU array-range designator, this
1371/// will be set to the last index initialized by this designator.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001372///
1373/// @param Index Index into @p IList where the designated initializer
1374/// @p DIE occurs.
1375///
Douglas Gregor4c678342009-01-28 21:54:33 +00001376/// @param StructuredList The initializer list expression that
1377/// describes all of the subobject initializers in the order they'll
1378/// actually be initialized.
1379///
Douglas Gregor05c13a32009-01-22 00:58:24 +00001380/// @returns true if there was an error, false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001381bool
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001382InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001383 InitListExpr *IList,
Mike Stump1eb44332009-09-09 15:08:12 +00001384 DesignatedInitExpr *DIE,
Douglas Gregor71199712009-04-15 04:56:10 +00001385 unsigned DesigIdx,
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001386 QualType &CurrentObjectType,
1387 RecordDecl::field_iterator *NextField,
1388 llvm::APSInt *NextElementIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001389 unsigned &Index,
1390 InitListExpr *StructuredList,
Douglas Gregor34e79462009-01-28 23:36:17 +00001391 unsigned &StructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001392 bool FinishSubobjectInit,
1393 bool TopLevelObject) {
Douglas Gregor71199712009-04-15 04:56:10 +00001394 if (DesigIdx == DIE->size()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001395 // Check the actual initialization for the designated object type.
1396 bool prevHadError = hadError;
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001397
1398 // Temporarily remove the designator expression from the
1399 // initializer list that the child calls see, so that we don't try
1400 // to re-process the designator.
1401 unsigned OldIndex = Index;
1402 IList->setInit(OldIndex, DIE->getInit());
1403
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001404 CheckSubElementType(Entity, IList, CurrentObjectType, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001405 StructuredList, StructuredIndex);
Douglas Gregor6fbdc6b2009-01-29 00:39:20 +00001406
1407 // Restore the designated initializer expression in the syntactic
1408 // form of the initializer list.
1409 if (IList->getInit(OldIndex) != DIE->getInit())
1410 DIE->setInit(IList->getInit(OldIndex));
1411 IList->setInit(OldIndex, DIE);
1412
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001413 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001414 }
1415
Douglas Gregor71199712009-04-15 04:56:10 +00001416 bool IsFirstDesignator = (DesigIdx == 0);
Mike Stump1eb44332009-09-09 15:08:12 +00001417 assert((IsFirstDesignator || StructuredList) &&
Douglas Gregor4c678342009-01-28 21:54:33 +00001418 "Need a non-designated initializer list to start from");
1419
Douglas Gregor71199712009-04-15 04:56:10 +00001420 DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
Douglas Gregor4c678342009-01-28 21:54:33 +00001421 // Determine the structural initializer list that corresponds to the
1422 // current subobject.
1423 StructuredList = IsFirstDesignator? SyntacticToSemantic[IList]
Mike Stump1eb44332009-09-09 15:08:12 +00001424 : getStructuredSubobjectInit(IList, Index, CurrentObjectType,
Douglas Gregored8a93d2009-03-01 17:12:46 +00001425 StructuredList, StructuredIndex,
Douglas Gregor4c678342009-01-28 21:54:33 +00001426 SourceRange(D->getStartLocation(),
1427 DIE->getSourceRange().getEnd()));
1428 assert(StructuredList && "Expected a structured initializer list");
1429
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001430 if (D->isFieldDesignator()) {
1431 // C99 6.7.8p7:
1432 //
1433 // If a designator has the form
1434 //
1435 // . identifier
1436 //
1437 // then the current object (defined below) shall have
1438 // structure or union type and the identifier shall be the
Mike Stump1eb44332009-09-09 15:08:12 +00001439 // name of a member of that type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001440 const RecordType *RT = CurrentObjectType->getAs<RecordType>();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001441 if (!RT) {
1442 SourceLocation Loc = D->getDotLoc();
1443 if (Loc.isInvalid())
1444 Loc = D->getFieldLoc();
Chris Lattner08202542009-02-24 22:50:46 +00001445 SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
1446 << SemaRef.getLangOptions().CPlusPlus << CurrentObjectType;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001447 ++Index;
1448 return true;
1449 }
1450
Douglas Gregor4c678342009-01-28 21:54:33 +00001451 // Note: we perform a linear search of the fields here, despite
1452 // the fact that we have a faster lookup method, because we always
1453 // need to compute the field's index.
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001454 FieldDecl *KnownField = D->getField();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001455 IdentifierInfo *FieldName = D->getFieldName();
Douglas Gregor4c678342009-01-28 21:54:33 +00001456 unsigned FieldIndex = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001457 RecordDecl::field_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001458 Field = RT->getDecl()->field_begin(),
1459 FieldEnd = RT->getDecl()->field_end();
Douglas Gregor4c678342009-01-28 21:54:33 +00001460 for (; Field != FieldEnd; ++Field) {
1461 if (Field->isUnnamedBitfield())
1462 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001463
Francois Picheta0e27f02010-12-22 03:46:10 +00001464 // If we find a field representing an anonymous field, look in the
1465 // IndirectFieldDecl that follow for the designated initializer.
1466 if (!KnownField && Field->isAnonymousStructOrUnion()) {
1467 if (IndirectFieldDecl *IF =
1468 FindIndirectFieldDesignator(*Field, FieldName)) {
1469 ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IF);
1470 D = DIE->getDesignator(DesigIdx);
1471 break;
1472 }
1473 }
Douglas Gregor022d13d2010-10-08 20:44:28 +00001474 if (KnownField && KnownField == *Field)
1475 break;
1476 if (FieldName && FieldName == Field->getIdentifier())
Douglas Gregor4c678342009-01-28 21:54:33 +00001477 break;
1478
1479 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001480 }
1481
Douglas Gregor4c678342009-01-28 21:54:33 +00001482 if (Field == FieldEnd) {
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001483 // There was no normal field in the struct with the designated
1484 // name. Perform another lookup for this name, which may find
1485 // something that we can't designate (e.g., a member function),
1486 // may find nothing, or may find a member of an anonymous
Mike Stump1eb44332009-09-09 15:08:12 +00001487 // struct/union.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001488 DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001489 FieldDecl *ReplacementField = 0;
Douglas Gregor4c678342009-01-28 21:54:33 +00001490 if (Lookup.first == Lookup.second) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001491 // Name lookup didn't find anything. Determine whether this
1492 // was a typo for another field name.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001493 LookupResult R(SemaRef, FieldName, D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001494 Sema::LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001495 TypoCorrection Corrected = SemaRef.CorrectTypo(
1496 DeclarationNameInfo(FieldName, D->getFieldLoc()),
1497 Sema::LookupMemberName, /*Scope=*/NULL, /*SS=*/NULL,
1498 RT->getDecl(), false, Sema::CTC_NoKeywords);
1499 if ((ReplacementField = Corrected.getCorrectionDeclAs<FieldDecl>()) &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00001500 ReplacementField->getDeclContext()->getRedeclContext()
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001501 ->Equals(RT->getDecl())) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001502 std::string CorrectedStr(
1503 Corrected.getAsString(SemaRef.getLangOptions()));
1504 std::string CorrectedQuotedStr(
1505 Corrected.getQuoted(SemaRef.getLangOptions()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001506 SemaRef.Diag(D->getFieldLoc(),
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001507 diag::err_field_designator_unknown_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001508 << FieldName << CurrentObjectType << CorrectedQuotedStr
1509 << FixItHint::CreateReplacement(D->getFieldLoc(), CorrectedStr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001510 SemaRef.Diag(ReplacementField->getLocation(),
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001511 diag::note_previous_decl) << CorrectedQuotedStr;
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001512 } else {
1513 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
1514 << FieldName << CurrentObjectType;
1515 ++Index;
1516 return true;
1517 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001518 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001519
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001520 if (!ReplacementField) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001521 // Name lookup found something, but it wasn't a field.
Chris Lattner08202542009-02-24 22:50:46 +00001522 SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
Douglas Gregor4c678342009-01-28 21:54:33 +00001523 << FieldName;
Mike Stump1eb44332009-09-09 15:08:12 +00001524 SemaRef.Diag((*Lookup.first)->getLocation(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001525 diag::note_field_designator_found);
Eli Friedmanba79fc22009-04-16 17:49:48 +00001526 ++Index;
1527 return true;
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001528 }
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001529
Francois Picheta0e27f02010-12-22 03:46:10 +00001530 if (!KnownField) {
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001531 // The replacement field comes from typo correction; find it
1532 // in the list of fields.
1533 FieldIndex = 0;
1534 Field = RT->getDecl()->field_begin();
1535 for (; Field != FieldEnd; ++Field) {
1536 if (Field->isUnnamedBitfield())
1537 continue;
1538
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001539 if (ReplacementField == *Field ||
Douglas Gregorc171e3b2010-01-01 00:03:05 +00001540 Field->getIdentifier() == ReplacementField->getIdentifier())
1541 break;
1542
1543 ++FieldIndex;
1544 }
1545 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001546 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001547
1548 // All of the fields of a union are located at the same place in
1549 // the initializer list.
Douglas Gregor0bb76892009-01-29 16:53:55 +00001550 if (RT->getDecl()->isUnion()) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001551 FieldIndex = 0;
Douglas Gregor0bb76892009-01-29 16:53:55 +00001552 StructuredList->setInitializedFieldInUnion(*Field);
1553 }
Douglas Gregor4c678342009-01-28 21:54:33 +00001554
Douglas Gregor54001c12011-06-29 21:51:31 +00001555 // Make sure we can use this declaration.
1556 if (SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc())) {
1557 ++Index;
1558 return true;
1559 }
1560
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001561 // Update the designator with the field declaration.
Douglas Gregor4c678342009-01-28 21:54:33 +00001562 D->setField(*Field);
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Douglas Gregor4c678342009-01-28 21:54:33 +00001564 // Make sure that our non-designated initializer list has space
1565 // for a subobject corresponding to this field.
1566 if (FieldIndex >= StructuredList->getNumInits())
Chris Lattner08202542009-02-24 22:50:46 +00001567 StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001568
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001569 // This designator names a flexible array member.
1570 if (Field->getType()->isIncompleteArrayType()) {
1571 bool Invalid = false;
Douglas Gregor71199712009-04-15 04:56:10 +00001572 if ((DesigIdx + 1) != DIE->size()) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001573 // We can't designate an object within the flexible array
1574 // member (because GCC doesn't allow it).
Mike Stump1eb44332009-09-09 15:08:12 +00001575 DesignatedInitExpr::Designator *NextD
Douglas Gregor71199712009-04-15 04:56:10 +00001576 = DIE->getDesignator(DesigIdx + 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001577 SemaRef.Diag(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001578 diag::err_designator_into_flexible_array_member)
Mike Stump1eb44332009-09-09 15:08:12 +00001579 << SourceRange(NextD->getStartLocation(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001580 DIE->getSourceRange().getEnd());
Chris Lattner08202542009-02-24 22:50:46 +00001581 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001582 << *Field;
1583 Invalid = true;
1584 }
1585
Chris Lattner9046c222010-10-10 17:49:49 +00001586 if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
1587 !isa<StringLiteral>(DIE->getInit())) {
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001588 // The initializer is not an initializer list.
Chris Lattner08202542009-02-24 22:50:46 +00001589 SemaRef.Diag(DIE->getInit()->getSourceRange().getBegin(),
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001590 diag::err_flexible_array_init_needs_braces)
1591 << DIE->getInit()->getSourceRange();
Chris Lattner08202542009-02-24 22:50:46 +00001592 SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001593 << *Field;
1594 Invalid = true;
1595 }
1596
Eli Friedmanf40fd6b2011-08-23 22:24:57 +00001597 // Check GNU flexible array initializer.
1598 if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
1599 TopLevelObject))
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001600 Invalid = true;
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001601
1602 if (Invalid) {
1603 ++Index;
1604 return true;
1605 }
1606
1607 // Initialize the array.
1608 bool prevHadError = hadError;
1609 unsigned newStructuredIndex = FieldIndex;
1610 unsigned OldIndex = Index;
1611 IList->setInit(Index, DIE->getInit());
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001612
1613 InitializedEntity MemberEntity =
1614 InitializedEntity::InitializeMember(*Field, &Entity);
1615 CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001616 StructuredList, newStructuredIndex);
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001617
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001618 IList->setInit(OldIndex, DIE);
1619 if (hadError && !prevHadError) {
1620 ++Field;
1621 ++FieldIndex;
1622 if (NextField)
1623 *NextField = Field;
1624 StructuredIndex = FieldIndex;
1625 return true;
1626 }
1627 } else {
1628 // Recurse to check later designated subobjects.
1629 QualType FieldType = (*Field)->getType();
1630 unsigned newStructuredIndex = FieldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001631
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001632 InitializedEntity MemberEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001633 InitializedEntity::InitializeMember(*Field, &Entity);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001634 if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
1635 FieldType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001636 StructuredList, newStructuredIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001637 true, false))
1638 return true;
1639 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001640
1641 // Find the position of the next field to be initialized in this
1642 // subobject.
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001643 ++Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001644 ++FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001645
1646 // If this the first designator, our caller will continue checking
1647 // the rest of this struct/class/union subobject.
1648 if (IsFirstDesignator) {
1649 if (NextField)
1650 *NextField = Field;
Douglas Gregor4c678342009-01-28 21:54:33 +00001651 StructuredIndex = FieldIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001652 return false;
1653 }
1654
Douglas Gregor34e79462009-01-28 23:36:17 +00001655 if (!FinishSubobjectInit)
1656 return false;
1657
Douglas Gregorffb4b6e2009-04-15 06:41:24 +00001658 // We've already initialized something in the union; we're done.
1659 if (RT->getDecl()->isUnion())
1660 return hadError;
1661
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001662 // Check the remaining fields within this class/struct/union subobject.
1663 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001664
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001665 CheckStructUnionTypes(Entity, IList, CurrentObjectType, Field, false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001666 StructuredList, FieldIndex);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001667 return hadError && !prevHadError;
1668 }
1669
1670 // C99 6.7.8p6:
1671 //
1672 // If a designator has the form
1673 //
1674 // [ constant-expression ]
1675 //
1676 // then the current object (defined below) shall have array
1677 // type and the expression shall be an integer constant
1678 // expression. If the array is of unknown size, any
1679 // nonnegative value is valid.
1680 //
1681 // Additionally, cope with the GNU extension that permits
1682 // designators of the form
1683 //
1684 // [ constant-expression ... constant-expression ]
Chris Lattner08202542009-02-24 22:50:46 +00001685 const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001686 if (!AT) {
Chris Lattner08202542009-02-24 22:50:46 +00001687 SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001688 << CurrentObjectType;
1689 ++Index;
1690 return true;
1691 }
1692
1693 Expr *IndexExpr = 0;
Douglas Gregor34e79462009-01-28 23:36:17 +00001694 llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
1695 if (D->isArrayDesignator()) {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001696 IndexExpr = DIE->getArrayIndex(*D);
Chris Lattner3bf68932009-04-25 21:59:05 +00001697 DesignatedStartIndex = IndexExpr->EvaluateAsInt(SemaRef.Context);
Douglas Gregor34e79462009-01-28 23:36:17 +00001698 DesignatedEndIndex = DesignatedStartIndex;
1699 } else {
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001700 assert(D->isArrayRangeDesignator() && "Need array-range designator");
Douglas Gregor34e79462009-01-28 23:36:17 +00001701
Mike Stump1eb44332009-09-09 15:08:12 +00001702 DesignatedStartIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001703 DIE->getArrayRangeStart(*D)->EvaluateAsInt(SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001704 DesignatedEndIndex =
Chris Lattner3bf68932009-04-25 21:59:05 +00001705 DIE->getArrayRangeEnd(*D)->EvaluateAsInt(SemaRef.Context);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001706 IndexExpr = DIE->getArrayRangeEnd(*D);
Douglas Gregor34e79462009-01-28 23:36:17 +00001707
Chris Lattnere0fd8322011-02-19 22:28:58 +00001708 // Codegen can't handle evaluating array range designators that have side
1709 // effects, because we replicate the AST value for each initialized element.
1710 // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
1711 // elements with something that has a side effect, so codegen can emit an
1712 // "error unsupported" error instead of miscompiling the app.
1713 if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
1714 DIE->getInit()->HasSideEffects(SemaRef.Context))
Douglas Gregora9c87802009-01-29 19:42:23 +00001715 FullyStructuredList->sawArrayRangeDesignator();
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001716 }
1717
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001718 if (isa<ConstantArrayType>(AT)) {
1719 llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
Jay Foad9f71a8f2010-12-07 08:25:34 +00001720 DesignatedStartIndex
1721 = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001722 DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
Jay Foad9f71a8f2010-12-07 08:25:34 +00001723 DesignatedEndIndex
1724 = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001725 DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
1726 if (DesignatedEndIndex >= MaxElements) {
Chris Lattner08202542009-02-24 22:50:46 +00001727 SemaRef.Diag(IndexExpr->getSourceRange().getBegin(),
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001728 diag::err_array_designator_too_large)
Douglas Gregor34e79462009-01-28 23:36:17 +00001729 << DesignatedEndIndex.toString(10) << MaxElements.toString(10)
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001730 << IndexExpr->getSourceRange();
1731 ++Index;
1732 return true;
1733 }
Douglas Gregor34e79462009-01-28 23:36:17 +00001734 } else {
1735 // Make sure the bit-widths and signedness match.
1736 if (DesignatedStartIndex.getBitWidth() > DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001737 DesignatedEndIndex
1738 = DesignatedEndIndex.extend(DesignatedStartIndex.getBitWidth());
Chris Lattner3bf68932009-04-25 21:59:05 +00001739 else if (DesignatedStartIndex.getBitWidth() <
1740 DesignatedEndIndex.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001741 DesignatedStartIndex
1742 = DesignatedStartIndex.extend(DesignatedEndIndex.getBitWidth());
Douglas Gregor34e79462009-01-28 23:36:17 +00001743 DesignatedStartIndex.setIsUnsigned(true);
1744 DesignatedEndIndex.setIsUnsigned(true);
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001745 }
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Douglas Gregor4c678342009-01-28 21:54:33 +00001747 // Make sure that our non-designated initializer list has space
1748 // for a subobject corresponding to this array element.
Douglas Gregor34e79462009-01-28 23:36:17 +00001749 if (DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits())
Mike Stump1eb44332009-09-09 15:08:12 +00001750 StructuredList->resizeInits(SemaRef.Context,
Douglas Gregor34e79462009-01-28 23:36:17 +00001751 DesignatedEndIndex.getZExtValue() + 1);
Douglas Gregor4c678342009-01-28 21:54:33 +00001752
Douglas Gregor34e79462009-01-28 23:36:17 +00001753 // Repeatedly perform subobject initializations in the range
1754 // [DesignatedStartIndex, DesignatedEndIndex].
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001755
Douglas Gregor34e79462009-01-28 23:36:17 +00001756 // Move to the next designator
1757 unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
1758 unsigned OldIndex = Index;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001759
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001760 InitializedEntity ElementEntity =
Anders Carlsson8ff9e862010-01-23 23:23:01 +00001761 InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001762
Douglas Gregor34e79462009-01-28 23:36:17 +00001763 while (DesignatedStartIndex <= DesignatedEndIndex) {
1764 // Recurse to check later designated subobjects.
1765 QualType ElementType = AT->getElementType();
1766 Index = OldIndex;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001767
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001768 ElementEntity.setElementIndex(ElementIndex);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001769 if (CheckDesignatedInitializer(ElementEntity, IList, DIE, DesigIdx + 1,
1770 ElementType, 0, 0, Index,
Anders Carlsson9a8a70e2010-01-23 22:49:02 +00001771 StructuredList, ElementIndex,
Douglas Gregoreeb15d42009-02-04 22:46:25 +00001772 (DesignatedStartIndex == DesignatedEndIndex),
1773 false))
Douglas Gregor34e79462009-01-28 23:36:17 +00001774 return true;
1775
1776 // Move to the next index in the array that we'll be initializing.
1777 ++DesignatedStartIndex;
1778 ElementIndex = DesignatedStartIndex.getZExtValue();
1779 }
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001780
1781 // If this the first designator, our caller will continue checking
1782 // the rest of this array subobject.
1783 if (IsFirstDesignator) {
1784 if (NextElementIndex)
Douglas Gregor34e79462009-01-28 23:36:17 +00001785 *NextElementIndex = DesignatedStartIndex;
Douglas Gregor4c678342009-01-28 21:54:33 +00001786 StructuredIndex = ElementIndex;
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001787 return false;
1788 }
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Douglas Gregor34e79462009-01-28 23:36:17 +00001790 if (!FinishSubobjectInit)
1791 return false;
1792
Douglas Gregor87f55cf2009-01-22 23:26:18 +00001793 // Check the remaining elements within this array subobject.
Douglas Gregor05c13a32009-01-22 00:58:24 +00001794 bool prevHadError = hadError;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795 CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
Anders Carlsson784f6992010-01-23 20:13:41 +00001796 /*SubobjectIsDesignatorContext=*/false, Index,
Douglas Gregor4c678342009-01-28 21:54:33 +00001797 StructuredList, ElementIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001798 return hadError && !prevHadError;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001799}
1800
Douglas Gregor4c678342009-01-28 21:54:33 +00001801// Get the structured initializer list for a subobject of type
1802// @p CurrentObjectType.
1803InitListExpr *
1804InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
1805 QualType CurrentObjectType,
1806 InitListExpr *StructuredList,
1807 unsigned StructuredIndex,
1808 SourceRange InitRange) {
1809 Expr *ExistingInit = 0;
1810 if (!StructuredList)
1811 ExistingInit = SyntacticToSemantic[IList];
1812 else if (StructuredIndex < StructuredList->getNumInits())
1813 ExistingInit = StructuredList->getInit(StructuredIndex);
Mike Stump1eb44332009-09-09 15:08:12 +00001814
Douglas Gregor4c678342009-01-28 21:54:33 +00001815 if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
1816 return Result;
1817
1818 if (ExistingInit) {
1819 // We are creating an initializer list that initializes the
1820 // subobjects of the current object, but there was already an
1821 // initialization that completely initialized the current
1822 // subobject, e.g., by a compound literal:
Mike Stump1eb44332009-09-09 15:08:12 +00001823 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001824 // struct X { int a, b; };
1825 // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
Mike Stump1eb44332009-09-09 15:08:12 +00001826 //
Douglas Gregor4c678342009-01-28 21:54:33 +00001827 // Here, xs[0].a == 0 and xs[0].b == 3, since the second,
1828 // designated initializer re-initializes the whole
1829 // subobject [0], overwriting previous initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001830 SemaRef.Diag(InitRange.getBegin(),
Douglas Gregored8a93d2009-03-01 17:12:46 +00001831 diag::warn_subobject_initializer_overrides)
Douglas Gregor4c678342009-01-28 21:54:33 +00001832 << InitRange;
Mike Stump1eb44332009-09-09 15:08:12 +00001833 SemaRef.Diag(ExistingInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001834 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001835 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001836 << ExistingInit->getSourceRange();
1837 }
1838
Mike Stump1eb44332009-09-09 15:08:12 +00001839 InitListExpr *Result
Ted Kremenek709210f2010-04-13 23:39:13 +00001840 = new (SemaRef.Context) InitListExpr(SemaRef.Context,
1841 InitRange.getBegin(), 0, 0,
Ted Kremenekba7bc552010-02-19 01:50:18 +00001842 InitRange.getEnd());
Douglas Gregored8a93d2009-03-01 17:12:46 +00001843
Douglas Gregor63982352010-07-13 18:40:04 +00001844 Result->setType(CurrentObjectType.getNonLValueExprType(SemaRef.Context));
Douglas Gregor4c678342009-01-28 21:54:33 +00001845
Douglas Gregorfa219202009-03-20 23:58:33 +00001846 // Pre-allocate storage for the structured initializer list.
1847 unsigned NumElements = 0;
Douglas Gregor08457732009-03-21 18:13:52 +00001848 unsigned NumInits = 0;
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001849 bool GotNumInits = false;
1850 if (!StructuredList) {
Douglas Gregor08457732009-03-21 18:13:52 +00001851 NumInits = IList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001852 GotNumInits = true;
1853 } else if (Index < IList->getNumInits()) {
1854 if (InitListExpr *SubList = dyn_cast<InitListExpr>(IList->getInit(Index))) {
Douglas Gregor08457732009-03-21 18:13:52 +00001855 NumInits = SubList->getNumInits();
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001856 GotNumInits = true;
1857 }
Douglas Gregor08457732009-03-21 18:13:52 +00001858 }
1859
Mike Stump1eb44332009-09-09 15:08:12 +00001860 if (const ArrayType *AType
Douglas Gregorfa219202009-03-20 23:58:33 +00001861 = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
1862 if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
1863 NumElements = CAType->getSize().getZExtValue();
1864 // Simple heuristic so that we don't allocate a very large
1865 // initializer with many empty entries at the end.
Argyrios Kyrtzidisf8b17712011-04-28 18:53:55 +00001866 if (GotNumInits && NumElements > NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001867 NumElements = 0;
1868 }
John McCall183700f2009-09-21 23:43:11 +00001869 } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>())
Douglas Gregorfa219202009-03-20 23:58:33 +00001870 NumElements = VType->getNumElements();
Ted Kremenek6217b802009-07-29 21:53:49 +00001871 else if (const RecordType *RType = CurrentObjectType->getAs<RecordType>()) {
Douglas Gregorfa219202009-03-20 23:58:33 +00001872 RecordDecl *RDecl = RType->getDecl();
1873 if (RDecl->isUnion())
1874 NumElements = 1;
1875 else
Mike Stump1eb44332009-09-09 15:08:12 +00001876 NumElements = std::distance(RDecl->field_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001877 RDecl->field_end());
Douglas Gregorfa219202009-03-20 23:58:33 +00001878 }
1879
Douglas Gregor08457732009-03-21 18:13:52 +00001880 if (NumElements < NumInits)
Douglas Gregorfa219202009-03-20 23:58:33 +00001881 NumElements = IList->getNumInits();
1882
Ted Kremenek709210f2010-04-13 23:39:13 +00001883 Result->reserveInits(SemaRef.Context, NumElements);
Douglas Gregorfa219202009-03-20 23:58:33 +00001884
Douglas Gregor4c678342009-01-28 21:54:33 +00001885 // Link this new initializer list into the structured initializer
1886 // lists.
1887 if (StructuredList)
Ted Kremenek709210f2010-04-13 23:39:13 +00001888 StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
Douglas Gregor4c678342009-01-28 21:54:33 +00001889 else {
1890 Result->setSyntacticForm(IList);
1891 SyntacticToSemantic[IList] = Result;
1892 }
1893
1894 return Result;
1895}
1896
1897/// Update the initializer at index @p StructuredIndex within the
1898/// structured initializer list to the value @p expr.
1899void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
1900 unsigned &StructuredIndex,
1901 Expr *expr) {
1902 // No structured initializer list to update
1903 if (!StructuredList)
1904 return;
1905
Ted Kremenek709210f2010-04-13 23:39:13 +00001906 if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
1907 StructuredIndex, expr)) {
Douglas Gregor4c678342009-01-28 21:54:33 +00001908 // This initializer overwrites a previous initializer. Warn.
Mike Stump1eb44332009-09-09 15:08:12 +00001909 SemaRef.Diag(expr->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001910 diag::warn_initializer_overrides)
1911 << expr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001912 SemaRef.Diag(PrevInit->getSourceRange().getBegin(),
Douglas Gregor4c678342009-01-28 21:54:33 +00001913 diag::note_previous_initializer)
Douglas Gregor54f07282009-01-28 23:43:32 +00001914 << /*FIXME:has side effects=*/0
Douglas Gregor4c678342009-01-28 21:54:33 +00001915 << PrevInit->getSourceRange();
1916 }
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Douglas Gregor4c678342009-01-28 21:54:33 +00001918 ++StructuredIndex;
1919}
1920
Douglas Gregor05c13a32009-01-22 00:58:24 +00001921/// Check that the given Index expression is a valid array designator
1922/// value. This is essentailly just a wrapper around
Chris Lattner3bf68932009-04-25 21:59:05 +00001923/// VerifyIntegerConstantExpression that also checks for negative values
Douglas Gregor05c13a32009-01-22 00:58:24 +00001924/// and produces a reasonable diagnostic if there is a
1925/// failure. Returns true if there was an error, false otherwise. If
1926/// everything went okay, Value will receive the value of the constant
1927/// expression.
Mike Stump1eb44332009-09-09 15:08:12 +00001928static bool
Chris Lattner3bf68932009-04-25 21:59:05 +00001929CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001930 SourceLocation Loc = Index->getSourceRange().getBegin();
1931
1932 // Make sure this is an integer constant expression.
Chris Lattner3bf68932009-04-25 21:59:05 +00001933 if (S.VerifyIntegerConstantExpression(Index, &Value))
1934 return true;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001935
Chris Lattner3bf68932009-04-25 21:59:05 +00001936 if (Value.isSigned() && Value.isNegative())
1937 return S.Diag(Loc, diag::err_array_designator_negative)
Douglas Gregor05c13a32009-01-22 00:58:24 +00001938 << Value.toString(10) << Index->getSourceRange();
1939
Douglas Gregor53d3d8e2009-01-23 21:04:18 +00001940 Value.setIsUnsigned(true);
Douglas Gregor05c13a32009-01-22 00:58:24 +00001941 return false;
1942}
1943
John McCall60d7b3a2010-08-24 06:29:42 +00001944ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
Nick Lewycky7663f392010-11-20 01:29:55 +00001945 SourceLocation Loc,
1946 bool GNUSyntax,
1947 ExprResult Init) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00001948 typedef DesignatedInitExpr::Designator ASTDesignator;
1949
1950 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001951 SmallVector<ASTDesignator, 32> Designators;
1952 SmallVector<Expr *, 32> InitExpressions;
Douglas Gregor05c13a32009-01-22 00:58:24 +00001953
1954 // Build designators and check array designator expressions.
1955 for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) {
1956 const Designator &D = Desig.getDesignator(Idx);
1957 switch (D.getKind()) {
1958 case Designator::FieldDesignator:
Mike Stump1eb44332009-09-09 15:08:12 +00001959 Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001960 D.getFieldLoc()));
1961 break;
1962
1963 case Designator::ArrayDesignator: {
1964 Expr *Index = static_cast<Expr *>(D.getArrayIndex());
1965 llvm::APSInt IndexValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001966 if (!Index->isTypeDependent() &&
1967 !Index->isValueDependent() &&
1968 CheckArrayDesignatorExpr(*this, Index, IndexValue))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001969 Invalid = true;
1970 else {
1971 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00001972 D.getLBracketLoc(),
Douglas Gregor05c13a32009-01-22 00:58:24 +00001973 D.getRBracketLoc()));
1974 InitExpressions.push_back(Index);
1975 }
1976 break;
1977 }
1978
1979 case Designator::ArrayRangeDesignator: {
1980 Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
1981 Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
1982 llvm::APSInt StartValue;
1983 llvm::APSInt EndValue;
Douglas Gregor9ea62762009-05-21 23:17:49 +00001984 bool StartDependent = StartIndex->isTypeDependent() ||
1985 StartIndex->isValueDependent();
1986 bool EndDependent = EndIndex->isTypeDependent() ||
1987 EndIndex->isValueDependent();
1988 if ((!StartDependent &&
1989 CheckArrayDesignatorExpr(*this, StartIndex, StartValue)) ||
1990 (!EndDependent &&
1991 CheckArrayDesignatorExpr(*this, EndIndex, EndValue)))
Douglas Gregor05c13a32009-01-22 00:58:24 +00001992 Invalid = true;
Douglas Gregord6f584f2009-01-23 22:22:29 +00001993 else {
1994 // Make sure we're comparing values with the same bit width.
Douglas Gregor9ea62762009-05-21 23:17:49 +00001995 if (StartDependent || EndDependent) {
1996 // Nothing to compute.
1997 } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00001998 EndValue = EndValue.extend(StartValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00001999 else if (StartValue.getBitWidth() < EndValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002000 StartValue = StartValue.extend(EndValue.getBitWidth());
Douglas Gregord6f584f2009-01-23 22:22:29 +00002001
Douglas Gregorc4bb7bf2009-05-21 23:30:39 +00002002 if (!StartDependent && !EndDependent && EndValue < StartValue) {
Douglas Gregord6f584f2009-01-23 22:22:29 +00002003 Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
Mike Stump1eb44332009-09-09 15:08:12 +00002004 << StartValue.toString(10) << EndValue.toString(10)
Douglas Gregord6f584f2009-01-23 22:22:29 +00002005 << StartIndex->getSourceRange() << EndIndex->getSourceRange();
2006 Invalid = true;
2007 } else {
2008 Designators.push_back(ASTDesignator(InitExpressions.size(),
Mike Stump1eb44332009-09-09 15:08:12 +00002009 D.getLBracketLoc(),
Douglas Gregord6f584f2009-01-23 22:22:29 +00002010 D.getEllipsisLoc(),
2011 D.getRBracketLoc()));
2012 InitExpressions.push_back(StartIndex);
2013 InitExpressions.push_back(EndIndex);
2014 }
Douglas Gregor05c13a32009-01-22 00:58:24 +00002015 }
2016 break;
2017 }
2018 }
2019 }
2020
2021 if (Invalid || Init.isInvalid())
2022 return ExprError();
2023
2024 // Clear out the expressions within the designation.
2025 Desig.ClearExprs(*this);
2026
2027 DesignatedInitExpr *DIE
Jay Foadbeaaccd2009-05-21 09:52:38 +00002028 = DesignatedInitExpr::Create(Context,
2029 Designators.data(), Designators.size(),
2030 InitExpressions.data(), InitExpressions.size(),
Anders Carlssone9146f22009-05-01 19:49:17 +00002031 Loc, GNUSyntax, Init.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002032
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002033 if (getLangOptions().CPlusPlus)
Eli Friedmana47317b2011-04-24 22:14:22 +00002034 Diag(DIE->getLocStart(), diag::ext_designated_init_cxx)
2035 << DIE->getSourceRange();
2036 else if (!getLangOptions().C99)
Douglas Gregor2d75bbd2011-01-16 16:13:16 +00002037 Diag(DIE->getLocStart(), diag::ext_designated_init)
2038 << DIE->getSourceRange();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002039
Douglas Gregor05c13a32009-01-22 00:58:24 +00002040 return Owned(DIE);
2041}
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002042
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002043bool Sema::CheckInitList(const InitializedEntity &Entity,
2044 InitListExpr *&InitList, QualType &DeclType) {
2045 InitListChecker CheckInitList(*this, Entity, InitList, DeclType);
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00002046 if (!CheckInitList.HadError())
2047 InitList = CheckInitList.getFullyStructuredList();
2048
2049 return CheckInitList.HadError();
2050}
Douglas Gregor87fd7032009-02-02 17:43:21 +00002051
Douglas Gregor20093b42009-12-09 23:02:17 +00002052//===----------------------------------------------------------------------===//
2053// Initialization entity
2054//===----------------------------------------------------------------------===//
2055
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002056InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002057 const InitializedEntity &Parent)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002058 : Parent(&Parent), Index(Index)
Douglas Gregorcb57fb92009-12-16 06:35:08 +00002059{
Anders Carlssond3d824d2010-01-23 04:34:47 +00002060 if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
2061 Kind = EK_ArrayElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002062 Type = AT->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002063 } else {
2064 Kind = EK_VectorElement;
Douglas Gregord6542d82009-12-22 15:35:07 +00002065 Type = Parent.getType()->getAs<VectorType>()->getElementType();
Anders Carlssond3d824d2010-01-23 04:34:47 +00002066 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002067}
2068
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002069InitializedEntity InitializedEntity::InitializeBase(ASTContext &Context,
Anders Carlsson711f34a2010-04-21 19:52:01 +00002070 CXXBaseSpecifier *Base,
2071 bool IsInheritedVirtualBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002072{
2073 InitializedEntity Result;
2074 Result.Kind = EK_Base;
Anders Carlsson711f34a2010-04-21 19:52:01 +00002075 Result.Base = reinterpret_cast<uintptr_t>(Base);
2076 if (IsInheritedVirtualBase)
2077 Result.Base |= 0x01;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002078
Douglas Gregord6542d82009-12-22 15:35:07 +00002079 Result.Type = Base->getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002080 return Result;
2081}
2082
Douglas Gregor99a2e602009-12-16 01:38:02 +00002083DeclarationName InitializedEntity::getName() const {
2084 switch (getKind()) {
John McCallf85e1932011-06-15 23:02:42 +00002085 case EK_Parameter: {
2086 ParmVarDecl *D = reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2087 return (D ? D->getDeclName() : DeclarationName());
2088 }
Douglas Gregora188ff22009-12-22 16:09:06 +00002089
2090 case EK_Variable:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002091 case EK_Member:
2092 return VariableOrMember->getDeclName();
2093
2094 case EK_Result:
2095 case EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002096 case EK_New:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002097 case EK_Temporary:
2098 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002099 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002100 case EK_ArrayElement:
2101 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002102 case EK_BlockElement:
Douglas Gregor99a2e602009-12-16 01:38:02 +00002103 return DeclarationName();
2104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002105
Douglas Gregor99a2e602009-12-16 01:38:02 +00002106 // Silence GCC warning
2107 return DeclarationName();
2108}
2109
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002110DeclaratorDecl *InitializedEntity::getDecl() const {
2111 switch (getKind()) {
2112 case EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002113 case EK_Member:
2114 return VariableOrMember;
2115
John McCallf85e1932011-06-15 23:02:42 +00002116 case EK_Parameter:
2117 return reinterpret_cast<ParmVarDecl*>(Parameter & ~0x1);
2118
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002119 case EK_Result:
2120 case EK_Exception:
2121 case EK_New:
2122 case EK_Temporary:
2123 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002124 case EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00002125 case EK_ArrayElement:
2126 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002127 case EK_BlockElement:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002128 return 0;
2129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002130
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00002131 // Silence GCC warning
2132 return 0;
2133}
2134
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002135bool InitializedEntity::allowsNRVO() const {
2136 switch (getKind()) {
2137 case EK_Result:
2138 case EK_Exception:
2139 return LocAndNRVO.NRVO;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002141 case EK_Variable:
2142 case EK_Parameter:
2143 case EK_Member:
2144 case EK_New:
2145 case EK_Temporary:
2146 case EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00002147 case EK_Delegating:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002148 case EK_ArrayElement:
2149 case EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00002150 case EK_BlockElement:
Douglas Gregor3c9034c2010-05-15 00:13:29 +00002151 break;
2152 }
2153
2154 return false;
2155}
2156
Douglas Gregor20093b42009-12-09 23:02:17 +00002157//===----------------------------------------------------------------------===//
2158// Initialization sequence
2159//===----------------------------------------------------------------------===//
2160
2161void InitializationSequence::Step::Destroy() {
2162 switch (Kind) {
2163 case SK_ResolveAddressOfOverloadedFunction:
2164 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002165 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002166 case SK_CastDerivedToBaseLValue:
2167 case SK_BindReference:
2168 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00002169 case SK_ExtraneousCopyToTemporary:
Douglas Gregor20093b42009-12-09 23:02:17 +00002170 case SK_UserConversion:
2171 case SK_QualificationConversionRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002172 case SK_QualificationConversionXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00002173 case SK_QualificationConversionLValue:
Douglas Gregord87b61f2009-12-10 17:56:55 +00002174 case SK_ListInitialization:
Douglas Gregor51c56d62009-12-14 20:49:26 +00002175 case SK_ConstructorInitialization:
Douglas Gregor71d17402009-12-15 00:01:57 +00002176 case SK_ZeroInitialization:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002177 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002178 case SK_StringInit:
Douglas Gregor569c3162010-08-07 11:51:51 +00002179 case SK_ObjCObjectConversion:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002180 case SK_ArrayInit:
John McCallf85e1932011-06-15 23:02:42 +00002181 case SK_PassByIndirectCopyRestore:
2182 case SK_PassByIndirectRestore:
2183 case SK_ProduceObjCObject:
Douglas Gregor20093b42009-12-09 23:02:17 +00002184 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002185
Douglas Gregor20093b42009-12-09 23:02:17 +00002186 case SK_ConversionSequence:
2187 delete ICS;
2188 }
2189}
2190
Douglas Gregorb70cf442010-03-26 20:14:36 +00002191bool InitializationSequence::isDirectReferenceBinding() const {
Sebastian Redl3b802322011-07-14 19:07:55 +00002192 return !Steps.empty() && Steps.back().Kind == SK_BindReference;
Douglas Gregorb70cf442010-03-26 20:14:36 +00002193}
2194
2195bool InitializationSequence::isAmbiguous() const {
Sebastian Redld695d6b2011-06-05 13:59:05 +00002196 if (!Failed())
Douglas Gregorb70cf442010-03-26 20:14:36 +00002197 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002198
Douglas Gregorb70cf442010-03-26 20:14:36 +00002199 switch (getFailureKind()) {
2200 case FK_TooManyInitsForReference:
2201 case FK_ArrayNeedsInitList:
2202 case FK_ArrayNeedsInitListOrStringLiteral:
2203 case FK_AddressOfOverloadFailed: // FIXME: Could do better
2204 case FK_NonConstLValueReferenceBindingToTemporary:
2205 case FK_NonConstLValueReferenceBindingToUnrelated:
2206 case FK_RValueReferenceBindingToLValue:
2207 case FK_ReferenceInitDropsQualifiers:
2208 case FK_ReferenceInitFailed:
2209 case FK_ConversionFailed:
John Wiegley429bb272011-04-08 18:41:53 +00002210 case FK_ConversionFromPropertyFailed:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002211 case FK_TooManyInitsForScalar:
2212 case FK_ReferenceBindingToInitList:
2213 case FK_InitListBadDestinationType:
2214 case FK_DefaultInitOfConst:
Douglas Gregor72a43bb2010-05-20 22:12:02 +00002215 case FK_Incomplete:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002216 case FK_ArrayTypeMismatch:
2217 case FK_NonConstantArrayInit:
Douglas Gregorb70cf442010-03-26 20:14:36 +00002218 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002219
Douglas Gregorb70cf442010-03-26 20:14:36 +00002220 case FK_ReferenceInitOverloadFailed:
2221 case FK_UserConversionOverloadFailed:
2222 case FK_ConstructorOverloadFailed:
2223 return FailedOverloadResult == OR_Ambiguous;
2224 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002225
Douglas Gregorb70cf442010-03-26 20:14:36 +00002226 return false;
2227}
2228
Douglas Gregord6e44a32010-04-16 22:09:46 +00002229bool InitializationSequence::isConstructorInitialization() const {
2230 return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization;
2231}
2232
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002233bool InitializationSequence::endsWithNarrowing(ASTContext &Ctx,
2234 const Expr *Initializer,
2235 bool *isInitializerConstant,
2236 APValue *ConstantValue) const {
2237 if (Steps.empty() || Initializer->isValueDependent())
2238 return false;
2239
2240 const Step &LastStep = Steps.back();
2241 if (LastStep.Kind != SK_ConversionSequence)
2242 return false;
2243
2244 const ImplicitConversionSequence &ICS = *LastStep.ICS;
2245 const StandardConversionSequence *SCS = NULL;
2246 switch (ICS.getKind()) {
2247 case ImplicitConversionSequence::StandardConversion:
2248 SCS = &ICS.Standard;
2249 break;
2250 case ImplicitConversionSequence::UserDefinedConversion:
2251 SCS = &ICS.UserDefined.After;
2252 break;
2253 case ImplicitConversionSequence::AmbiguousConversion:
2254 case ImplicitConversionSequence::EllipsisConversion:
2255 case ImplicitConversionSequence::BadConversion:
2256 return false;
2257 }
2258
2259 // Check if SCS represents a narrowing conversion, according to C++0x
2260 // [dcl.init.list]p7:
2261 //
2262 // A narrowing conversion is an implicit conversion ...
2263 ImplicitConversionKind PossibleNarrowing = SCS->Second;
2264 QualType FromType = SCS->getToType(0);
2265 QualType ToType = SCS->getToType(1);
2266 switch (PossibleNarrowing) {
2267 // * from a floating-point type to an integer type, or
2268 //
2269 // * from an integer type or unscoped enumeration type to a floating-point
2270 // type, except where the source is a constant expression and the actual
2271 // value after conversion will fit into the target type and will produce
2272 // the original value when converted back to the original type, or
2273 case ICK_Floating_Integral:
2274 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
2275 *isInitializerConstant = false;
2276 return true;
2277 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
2278 llvm::APSInt IntConstantValue;
2279 if (Initializer &&
2280 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
2281 // Convert the integer to the floating type.
2282 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
2283 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
2284 llvm::APFloat::rmNearestTiesToEven);
2285 // And back.
2286 llvm::APSInt ConvertedValue = IntConstantValue;
2287 bool ignored;
2288 Result.convertToInteger(ConvertedValue,
2289 llvm::APFloat::rmTowardZero, &ignored);
2290 // If the resulting value is different, this was a narrowing conversion.
2291 if (IntConstantValue != ConvertedValue) {
2292 *isInitializerConstant = true;
2293 *ConstantValue = APValue(IntConstantValue);
2294 return true;
2295 }
2296 } else {
2297 // Variables are always narrowings.
2298 *isInitializerConstant = false;
2299 return true;
2300 }
2301 }
2302 return false;
2303
2304 // * from long double to double or float, or from double to float, except
2305 // where the source is a constant expression and the actual value after
2306 // conversion is within the range of values that can be represented (even
2307 // if it cannot be represented exactly), or
2308 case ICK_Floating_Conversion:
2309 if (1 == Ctx.getFloatingTypeOrder(FromType, ToType)) {
2310 // FromType is larger than ToType.
2311 Expr::EvalResult InitializerValue;
2312 // FIXME: Check whether Initializer is a constant expression according
2313 // to C++0x [expr.const], rather than just whether it can be folded.
2314 if (Initializer->Evaluate(InitializerValue, Ctx) &&
2315 !InitializerValue.HasSideEffects && InitializerValue.Val.isFloat()) {
2316 // Constant! (Except for FIXME above.)
2317 llvm::APFloat FloatVal = InitializerValue.Val.getFloat();
2318 // Convert the source value into the target type.
2319 bool ignored;
2320 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
2321 Ctx.getFloatTypeSemantics(ToType),
2322 llvm::APFloat::rmNearestTiesToEven, &ignored);
2323 // If there was no overflow, the source value is within the range of
2324 // values that can be represented.
2325 if (ConvertStatus & llvm::APFloat::opOverflow) {
2326 *isInitializerConstant = true;
2327 *ConstantValue = InitializerValue.Val;
2328 return true;
2329 }
2330 } else {
2331 *isInitializerConstant = false;
2332 return true;
2333 }
2334 }
2335 return false;
2336
2337 // * from an integer type or unscoped enumeration type to an integer type
2338 // that cannot represent all the values of the original type, except where
2339 // the source is a constant expression and the actual value after
2340 // conversion will fit into the target type and will produce the original
2341 // value when converted back to the original type.
Jeffrey Yasskin6d0ee8d2011-08-12 20:56:43 +00002342 case ICK_Boolean_Conversion: // Bools are integers too.
Jeffrey Yasskinb89d5ed2011-08-30 22:25:41 +00002343 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
2344 // Boolean conversions can be from pointers and pointers to members
2345 // [conv.bool], and those aren't considered narrowing conversions.
2346 return false;
2347 } // Otherwise, fall through to the integral case.
Jeffrey Yasskin19159132011-07-26 23:20:30 +00002348 case ICK_Integral_Conversion: {
2349 assert(FromType->isIntegralOrUnscopedEnumerationType());
2350 assert(ToType->isIntegralOrUnscopedEnumerationType());
2351 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
2352 const unsigned FromWidth = Ctx.getIntWidth(FromType);
2353 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
2354 const unsigned ToWidth = Ctx.getIntWidth(ToType);
2355
2356 if (FromWidth > ToWidth ||
2357 (FromWidth == ToWidth && FromSigned != ToSigned)) {
2358 // Not all values of FromType can be represented in ToType.
2359 llvm::APSInt InitializerValue;
2360 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
2361 *isInitializerConstant = true;
2362 *ConstantValue = APValue(InitializerValue);
2363
2364 // Add a bit to the InitializerValue so we don't have to worry about
2365 // signed vs. unsigned comparisons.
2366 InitializerValue = InitializerValue.extend(
2367 InitializerValue.getBitWidth() + 1);
2368 // Convert the initializer to and from the target width and signed-ness.
2369 llvm::APSInt ConvertedValue = InitializerValue;
2370 ConvertedValue = ConvertedValue.trunc(ToWidth);
2371 ConvertedValue.setIsSigned(ToSigned);
2372 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
2373 ConvertedValue.setIsSigned(InitializerValue.isSigned());
2374 // If the result is different, this was a narrowing conversion.
2375 return ConvertedValue != InitializerValue;
2376 } else {
2377 // Variables are always narrowings.
2378 *isInitializerConstant = false;
2379 return true;
2380 }
2381 }
2382 return false;
2383 }
2384
2385 default:
2386 // Other kinds of conversions are not narrowings.
2387 return false;
2388 }
2389}
2390
Douglas Gregor20093b42009-12-09 23:02:17 +00002391void InitializationSequence::AddAddressOverloadResolutionStep(
John McCall6bb80172010-03-30 21:47:33 +00002392 FunctionDecl *Function,
2393 DeclAccessPair Found) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002394 Step S;
2395 S.Kind = SK_ResolveAddressOfOverloadedFunction;
2396 S.Type = Function->getType();
John McCall9aa472c2010-03-19 07:35:19 +00002397 S.Function.Function = Function;
John McCall6bb80172010-03-30 21:47:33 +00002398 S.Function.FoundDecl = Found;
Douglas Gregor20093b42009-12-09 23:02:17 +00002399 Steps.push_back(S);
2400}
2401
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002402void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
John McCall5baba9d2010-08-25 10:28:54 +00002403 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002404 Step S;
John McCall5baba9d2010-08-25 10:28:54 +00002405 switch (VK) {
2406 case VK_RValue: S.Kind = SK_CastDerivedToBaseRValue; break;
2407 case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
2408 case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002409 default: llvm_unreachable("No such category");
2410 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002411 S.Type = BaseType;
2412 Steps.push_back(S);
2413}
2414
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002415void InitializationSequence::AddReferenceBindingStep(QualType T,
Douglas Gregor20093b42009-12-09 23:02:17 +00002416 bool BindingTemporary) {
2417 Step S;
2418 S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference;
2419 S.Type = T;
2420 Steps.push_back(S);
2421}
2422
Douglas Gregor523d46a2010-04-18 07:40:54 +00002423void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
2424 Step S;
2425 S.Kind = SK_ExtraneousCopyToTemporary;
2426 S.Type = T;
2427 Steps.push_back(S);
2428}
2429
Eli Friedman03981012009-12-11 02:42:07 +00002430void InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002431 DeclAccessPair FoundDecl,
Eli Friedman03981012009-12-11 02:42:07 +00002432 QualType T) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002433 Step S;
2434 S.Kind = SK_UserConversion;
Eli Friedman03981012009-12-11 02:42:07 +00002435 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002436 S.Function.Function = Function;
2437 S.Function.FoundDecl = FoundDecl;
Douglas Gregor20093b42009-12-09 23:02:17 +00002438 Steps.push_back(S);
2439}
2440
2441void InitializationSequence::AddQualificationConversionStep(QualType Ty,
John McCall5baba9d2010-08-25 10:28:54 +00002442 ExprValueKind VK) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002443 Step S;
John McCall38a4ffe2010-08-26 16:36:35 +00002444 S.Kind = SK_QualificationConversionRValue; // work around a gcc warning
John McCall5baba9d2010-08-25 10:28:54 +00002445 switch (VK) {
2446 case VK_RValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002447 S.Kind = SK_QualificationConversionRValue;
2448 break;
John McCall5baba9d2010-08-25 10:28:54 +00002449 case VK_XValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002450 S.Kind = SK_QualificationConversionXValue;
2451 break;
John McCall5baba9d2010-08-25 10:28:54 +00002452 case VK_LValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00002453 S.Kind = SK_QualificationConversionLValue;
2454 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00002455 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002456 S.Type = Ty;
2457 Steps.push_back(S);
2458}
2459
2460void InitializationSequence::AddConversionSequenceStep(
2461 const ImplicitConversionSequence &ICS,
2462 QualType T) {
2463 Step S;
2464 S.Kind = SK_ConversionSequence;
2465 S.Type = T;
2466 S.ICS = new ImplicitConversionSequence(ICS);
2467 Steps.push_back(S);
2468}
2469
Douglas Gregord87b61f2009-12-10 17:56:55 +00002470void InitializationSequence::AddListInitializationStep(QualType T) {
2471 Step S;
2472 S.Kind = SK_ListInitialization;
2473 S.Type = T;
2474 Steps.push_back(S);
2475}
2476
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002477void
Douglas Gregor51c56d62009-12-14 20:49:26 +00002478InitializationSequence::AddConstructorInitializationStep(
2479 CXXConstructorDecl *Constructor,
John McCallb13b7372010-02-01 03:16:54 +00002480 AccessSpecifier Access,
Douglas Gregor51c56d62009-12-14 20:49:26 +00002481 QualType T) {
2482 Step S;
2483 S.Kind = SK_ConstructorInitialization;
2484 S.Type = T;
John McCall9aa472c2010-03-19 07:35:19 +00002485 S.Function.Function = Constructor;
2486 S.Function.FoundDecl = DeclAccessPair::make(Constructor, Access);
Douglas Gregor51c56d62009-12-14 20:49:26 +00002487 Steps.push_back(S);
2488}
2489
Douglas Gregor71d17402009-12-15 00:01:57 +00002490void InitializationSequence::AddZeroInitializationStep(QualType T) {
2491 Step S;
2492 S.Kind = SK_ZeroInitialization;
2493 S.Type = T;
2494 Steps.push_back(S);
2495}
2496
Douglas Gregor18ef5e22009-12-18 05:02:21 +00002497void InitializationSequence::AddCAssignmentStep(QualType T) {
2498 Step S;
2499 S.Kind = SK_CAssignment;
2500 S.Type = T;
2501 Steps.push_back(S);
2502}
2503
Eli Friedmancfdc81a2009-12-19 08:11:05 +00002504void InitializationSequence::AddStringInitStep(QualType T) {
2505 Step S;
2506 S.Kind = SK_StringInit;
2507 S.Type = T;
2508 Steps.push_back(S);
2509}
2510
Douglas Gregor569c3162010-08-07 11:51:51 +00002511void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
2512 Step S;
2513 S.Kind = SK_ObjCObjectConversion;
2514 S.Type = T;
2515 Steps.push_back(S);
2516}
2517
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00002518void InitializationSequence::AddArrayInitStep(QualType T) {
2519 Step S;
2520 S.Kind = SK_ArrayInit;
2521 S.Type = T;
2522 Steps.push_back(S);
2523}
2524
John McCallf85e1932011-06-15 23:02:42 +00002525void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
2526 bool shouldCopy) {
2527 Step s;
2528 s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore
2529 : SK_PassByIndirectRestore);
2530 s.Type = type;
2531 Steps.push_back(s);
2532}
2533
2534void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
2535 Step S;
2536 S.Kind = SK_ProduceObjCObject;
2537 S.Type = T;
2538 Steps.push_back(S);
2539}
2540
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002541void InitializationSequence::SetOverloadFailure(FailureKind Failure,
Douglas Gregor20093b42009-12-09 23:02:17 +00002542 OverloadingResult Result) {
Sebastian Redl7491c492011-06-05 13:59:11 +00002543 setSequenceKind(FailedSequence);
Douglas Gregor20093b42009-12-09 23:02:17 +00002544 this->Failure = Failure;
2545 this->FailedOverloadResult = Result;
2546}
2547
2548//===----------------------------------------------------------------------===//
2549// Attempt initialization
2550//===----------------------------------------------------------------------===//
2551
John McCallf85e1932011-06-15 23:02:42 +00002552static void MaybeProduceObjCObject(Sema &S,
2553 InitializationSequence &Sequence,
2554 const InitializedEntity &Entity) {
2555 if (!S.getLangOptions().ObjCAutoRefCount) return;
2556
2557 /// When initializing a parameter, produce the value if it's marked
2558 /// __attribute__((ns_consumed)).
2559 if (Entity.getKind() == InitializedEntity::EK_Parameter) {
2560 if (!Entity.isParameterConsumed())
2561 return;
2562
2563 assert(Entity.getType()->isObjCRetainableType() &&
2564 "consuming an object of unretainable type?");
2565 Sequence.AddProduceObjCObjectStep(Entity.getType());
2566
2567 /// When initializing a return value, if the return type is a
2568 /// retainable type, then returns need to immediately retain the
2569 /// object. If an autorelease is required, it will be done at the
2570 /// last instant.
2571 } else if (Entity.getKind() == InitializedEntity::EK_Result) {
2572 if (!Entity.getType()->isObjCRetainableType())
2573 return;
2574
2575 Sequence.AddProduceObjCObjectStep(Entity.getType());
2576 }
2577}
2578
Rafael Espindola12ce0a02011-07-14 22:58:04 +00002579/// \brief Attempt list initialization (C++0x [dcl.init.list])
2580static void TryListInitialization(Sema &S,
2581 const InitializedEntity &Entity,
2582 const InitializationKind &Kind,
2583 InitListExpr *InitList,
2584 InitializationSequence &Sequence) {
2585 // FIXME: We only perform rudimentary checking of list
2586 // initializations at this point, then assume that any list
2587 // initialization of an array, aggregate, or scalar will be
2588 // well-formed. When we actually "perform" list initialization, we'll
2589 // do all of the necessary checking. C++0x initializer lists will
2590 // force us to perform more checking here.
2591
2592 QualType DestType = Entity.getType();
2593
2594 // C++ [dcl.init]p13:
2595 // If T is a scalar type, then a declaration of the form
2596 //
2597 // T x = { a };
2598 //
2599 // is equivalent to
2600 //
2601 // T x = a;
2602 if (DestType->isScalarType()) {
2603 if (InitList->getNumInits() > 1 && S.getLangOptions().CPlusPlus) {
2604 Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
2605 return;
2606 }
2607
2608 // Assume scalar initialization from a single value works.
2609 } else if (DestType->isAggregateType()) {
2610 // Assume aggregate initialization works.
2611 } else if (DestType->isVectorType()) {
2612 // Assume vector initialization works.
2613 } else if (DestType->isReferenceType()) {
2614 // FIXME: C++0x defines behavior for this.
2615 Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
2616 return;
2617 } else if (DestType->isRecordType()) {
2618 // FIXME: C++0x defines behavior for this
2619 Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
2620 }
2621
2622 // Add a general "list initialization" step.
2623 Sequence.AddListInitializationStep(DestType);
2624}
Douglas Gregor20093b42009-12-09 23:02:17 +00002625
2626/// \brief Try a reference initialization that involves calling a conversion
2627/// function.
Douglas Gregor20093b42009-12-09 23:02:17 +00002628static OverloadingResult TryRefInitWithConversionFunction(Sema &S,
2629 const InitializedEntity &Entity,
2630 const InitializationKind &Kind,
2631 Expr *Initializer,
2632 bool AllowRValues,
2633 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002634 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002635 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
2636 QualType T1 = cv1T1.getUnqualifiedType();
2637 QualType cv2T2 = Initializer->getType();
2638 QualType T2 = cv2T2.getUnqualifiedType();
2639
2640 bool DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002641 bool ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002642 bool ObjCLifetimeConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643 assert(!S.CompareReferenceRelationship(Initializer->getLocStart(),
Douglas Gregor569c3162010-08-07 11:51:51 +00002644 T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002645 ObjCConversion,
2646 ObjCLifetimeConversion) &&
Douglas Gregor20093b42009-12-09 23:02:17 +00002647 "Must have incompatible references when binding via conversion");
Chandler Carruth60cfcec2009-12-13 01:37:04 +00002648 (void)DerivedToBase;
Douglas Gregor569c3162010-08-07 11:51:51 +00002649 (void)ObjCConversion;
John McCallf85e1932011-06-15 23:02:42 +00002650 (void)ObjCLifetimeConversion;
2651
Douglas Gregor20093b42009-12-09 23:02:17 +00002652 // Build the candidate set directly in the initialization sequence
2653 // structure, so that it will persist if we fail.
2654 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
2655 CandidateSet.clear();
2656
2657 // Determine whether we are allowed to call explicit constructors or
2658 // explicit conversion operators.
2659 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002660
Douglas Gregor20093b42009-12-09 23:02:17 +00002661 const RecordType *T1RecordType = 0;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002662 if (AllowRValues && (T1RecordType = T1->getAs<RecordType>()) &&
2663 !S.RequireCompleteType(Kind.getLocation(), T1, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002664 // The type we're converting to is a class type. Enumerate its constructors
2665 // to see if there is a suitable conversion.
2666 CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
John McCall572fc622010-08-17 07:23:57 +00002667
Douglas Gregor20093b42009-12-09 23:02:17 +00002668 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00002669 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(T1RecordDecl);
Douglas Gregor20093b42009-12-09 23:02:17 +00002670 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002671 NamedDecl *D = *Con;
2672 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2673
Douglas Gregor20093b42009-12-09 23:02:17 +00002674 // Find the constructor (which may be a template).
2675 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00002676 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor20093b42009-12-09 23:02:17 +00002677 if (ConstructorTmpl)
2678 Constructor = cast<CXXConstructorDecl>(
2679 ConstructorTmpl->getTemplatedDecl());
2680 else
John McCall9aa472c2010-03-19 07:35:19 +00002681 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002682
Douglas Gregor20093b42009-12-09 23:02:17 +00002683 if (!Constructor->isInvalidDecl() &&
2684 Constructor->isConvertingConstructor(AllowExplicit)) {
2685 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00002686 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00002687 /*ExplicitArgs*/ 0,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002688 &Initializer, 1, CandidateSet,
2689 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002690 else
John McCall9aa472c2010-03-19 07:35:19 +00002691 S.AddOverloadCandidate(Constructor, FoundDecl,
Argyrios Kyrtzidisb72db892010-10-05 03:05:30 +00002692 &Initializer, 1, CandidateSet,
2693 /*SuppressUserConversions=*/true);
Douglas Gregor20093b42009-12-09 23:02:17 +00002694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002695 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002696 }
John McCall572fc622010-08-17 07:23:57 +00002697 if (T1RecordType && T1RecordType->getDecl()->isInvalidDecl())
2698 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002699
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002700 const RecordType *T2RecordType = 0;
2701 if ((T2RecordType = T2->getAs<RecordType>()) &&
2702 !S.RequireCompleteType(Kind.getLocation(), T2, 0)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002703 // The type we're converting from is a class type, enumerate its conversion
2704 // functions.
2705 CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
2706
John McCalleec51cf2010-01-20 00:46:10 +00002707 const UnresolvedSetImpl *Conversions
Douglas Gregor20093b42009-12-09 23:02:17 +00002708 = T2RecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002709 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
2710 E = Conversions->end(); I != E; ++I) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002711 NamedDecl *D = *I;
2712 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2713 if (isa<UsingShadowDecl>(D))
2714 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002715
Douglas Gregor20093b42009-12-09 23:02:17 +00002716 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
2717 CXXConversionDecl *Conv;
2718 if (ConvTemplate)
2719 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2720 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002721 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002722
Douglas Gregor20093b42009-12-09 23:02:17 +00002723 // If the conversion function doesn't return a reference type,
2724 // it can't be considered for this conversion unless we're allowed to
2725 // consider rvalues.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002726 // FIXME: Do we need to make sure that we only consider conversion
2727 // candidates with reference-compatible results? That might be needed to
Douglas Gregor20093b42009-12-09 23:02:17 +00002728 // break recursion.
2729 if ((AllowExplicit || !Conv->isExplicit()) &&
2730 (AllowRValues || Conv->getConversionType()->isLValueReferenceType())){
2731 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00002732 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00002733 ActingDC, Initializer,
Douglas Gregor564cb062011-01-21 00:27:08 +00002734 DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002735 else
John McCall9aa472c2010-03-19 07:35:19 +00002736 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
Douglas Gregor564cb062011-01-21 00:27:08 +00002737 Initializer, DestType, CandidateSet);
Douglas Gregor20093b42009-12-09 23:02:17 +00002738 }
2739 }
2740 }
John McCall572fc622010-08-17 07:23:57 +00002741 if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
2742 return OR_No_Viable_Function;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002743
Douglas Gregor20093b42009-12-09 23:02:17 +00002744 SourceLocation DeclLoc = Initializer->getLocStart();
2745
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002746 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor20093b42009-12-09 23:02:17 +00002747 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002748 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002749 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true))
Douglas Gregor20093b42009-12-09 23:02:17 +00002750 return Result;
Eli Friedman03981012009-12-11 02:42:07 +00002751
Douglas Gregor20093b42009-12-09 23:02:17 +00002752 FunctionDecl *Function = Best->Function;
Eli Friedman03981012009-12-11 02:42:07 +00002753
Chandler Carruth25ca4212011-02-25 19:41:05 +00002754 // This is the overload that will actually be used for the initialization, so
2755 // mark it as used.
2756 S.MarkDeclarationReferenced(DeclLoc, Function);
2757
Eli Friedman03981012009-12-11 02:42:07 +00002758 // Compute the returned type of the conversion.
Douglas Gregor20093b42009-12-09 23:02:17 +00002759 if (isa<CXXConversionDecl>(Function))
2760 T2 = Function->getResultType();
2761 else
2762 T2 = cv1T1;
Eli Friedman03981012009-12-11 02:42:07 +00002763
2764 // Add the user-defined conversion step.
John McCall9aa472c2010-03-19 07:35:19 +00002765 Sequence.AddUserConversionStep(Function, Best->FoundDecl,
Douglas Gregor63982352010-07-13 18:40:04 +00002766 T2.getNonLValueExprType(S.Context));
Eli Friedman03981012009-12-11 02:42:07 +00002767
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002768 // Determine whether we need to perform derived-to-base or
Eli Friedman03981012009-12-11 02:42:07 +00002769 // cv-qualification adjustments.
John McCall5baba9d2010-08-25 10:28:54 +00002770 ExprValueKind VK = VK_RValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002771 if (T2->isLValueReferenceType())
John McCall5baba9d2010-08-25 10:28:54 +00002772 VK = VK_LValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002773 else if (const RValueReferenceType *RRef = T2->getAs<RValueReferenceType>())
John McCall5baba9d2010-08-25 10:28:54 +00002774 VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue;
Sebastian Redl906082e2010-07-20 04:20:21 +00002775
Douglas Gregor20093b42009-12-09 23:02:17 +00002776 bool NewDerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002777 bool NewObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002778 bool NewObjCLifetimeConversion = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00002779 Sema::ReferenceCompareResult NewRefRelationship
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002780 = S.CompareReferenceRelationship(DeclLoc, T1,
Douglas Gregor63982352010-07-13 18:40:04 +00002781 T2.getNonLValueExprType(S.Context),
John McCallf85e1932011-06-15 23:02:42 +00002782 NewDerivedToBase, NewObjCConversion,
2783 NewObjCLifetimeConversion);
Douglas Gregora1a9f032010-03-07 23:17:44 +00002784 if (NewRefRelationship == Sema::Ref_Incompatible) {
2785 // If the type we've converted to is not reference-related to the
2786 // type we're looking for, then there is another conversion step
2787 // we need to perform to produce a temporary of the right type
2788 // that we'll be binding to.
2789 ImplicitConversionSequence ICS;
2790 ICS.setStandard();
2791 ICS.Standard = Best->FinalConversion;
2792 T2 = ICS.Standard.getToType(2);
2793 Sequence.AddConversionSequenceStep(ICS, T2);
2794 } else if (NewDerivedToBase)
Douglas Gregor20093b42009-12-09 23:02:17 +00002795 Sequence.AddDerivedToBaseCastStep(
2796 S.Context.getQualifiedType(T1,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002797 T2.getNonReferenceType().getQualifiers()),
John McCall5baba9d2010-08-25 10:28:54 +00002798 VK);
Douglas Gregor569c3162010-08-07 11:51:51 +00002799 else if (NewObjCConversion)
2800 Sequence.AddObjCObjectConversionStep(
2801 S.Context.getQualifiedType(T1,
2802 T2.getNonReferenceType().getQualifiers()));
2803
Douglas Gregor20093b42009-12-09 23:02:17 +00002804 if (cv1T1.getQualifiers() != T2.getNonReferenceType().getQualifiers())
John McCall5baba9d2010-08-25 10:28:54 +00002805 Sequence.AddQualificationConversionStep(cv1T1, VK);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002806
Douglas Gregor20093b42009-12-09 23:02:17 +00002807 Sequence.AddReferenceBindingStep(cv1T1, !T2->isReferenceType());
2808 return OR_Success;
2809}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810
2811/// \brief Attempt reference initialization (C++0x [dcl.init.ref])
2812static void TryReferenceInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00002813 const InitializedEntity &Entity,
2814 const InitializationKind &Kind,
2815 Expr *Initializer,
2816 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00002817 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00002818 QualType cv1T1 = DestType->getAs<ReferenceType>()->getPointeeType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002819 Qualifiers T1Quals;
2820 QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002821 QualType cv2T2 = Initializer->getType();
Chandler Carruth5535c382010-01-12 20:32:25 +00002822 Qualifiers T2Quals;
2823 QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
Douglas Gregor20093b42009-12-09 23:02:17 +00002824 SourceLocation DeclLoc = Initializer->getLocStart();
Sebastian Redl4680bf22010-06-30 18:13:39 +00002825
Douglas Gregor20093b42009-12-09 23:02:17 +00002826 // If the initializer is the address of an overloaded function, try
2827 // to resolve the overloaded function. If all goes well, T2 is the
2828 // type of the resulting function.
2829 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
John McCall6bb80172010-03-30 21:47:33 +00002830 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002831 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Initializer,
Douglas Gregor3afb9772010-11-08 15:20:28 +00002832 T1,
2833 false,
2834 Found)) {
2835 Sequence.AddAddressOverloadResolutionStep(Fn, Found);
2836 cv2T2 = Fn->getType();
2837 T2 = cv2T2.getUnqualifiedType();
2838 } else if (!T1->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002839 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2840 return;
2841 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002842 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002843
Douglas Gregor20093b42009-12-09 23:02:17 +00002844 // Compute some basic properties of the types and the initializer.
2845 bool isLValueRef = DestType->isLValueReferenceType();
2846 bool isRValueRef = !isLValueRef;
2847 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002848 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00002849 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002850 Expr::Classification InitCategory = Initializer->Classify(S.Context);
Douglas Gregor20093b42009-12-09 23:02:17 +00002851 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002852 = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00002853 ObjCConversion, ObjCLifetimeConversion);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002854
Douglas Gregor20093b42009-12-09 23:02:17 +00002855 // C++0x [dcl.init.ref]p5:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002856 // A reference to type "cv1 T1" is initialized by an expression of type
Douglas Gregor20093b42009-12-09 23:02:17 +00002857 // "cv2 T2" as follows:
2858 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002859 // - If the reference is an lvalue reference and the initializer
Douglas Gregor20093b42009-12-09 23:02:17 +00002860 // expression
Sebastian Redl4680bf22010-06-30 18:13:39 +00002861 // Note the analogous bullet points for rvlaue refs to functions. Because
2862 // there are no function rvalues in C++, rvalue refs to functions are treated
2863 // like lvalue refs.
Douglas Gregor20093b42009-12-09 23:02:17 +00002864 OverloadingResult ConvOvlResult = OR_Success;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002865 bool T1Function = T1->isFunctionType();
2866 if (isLValueRef || T1Function) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002867 if (InitCategory.isLValue() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002868 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002869 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002870 RefRelationship == Sema::Ref_Related))) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002871 // - is an lvalue (but is not a bit-field), and "cv1 T1" is
Douglas Gregor20093b42009-12-09 23:02:17 +00002872 // reference-compatible with "cv2 T2," or
2873 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002874 // Per C++ [over.best.ics]p2, we don't diagnose whether the lvalue is a
Douglas Gregor20093b42009-12-09 23:02:17 +00002875 // bit-field when we're determining whether the reference initialization
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002876 // can occur. However, we do pay attention to whether it is a bit-field
2877 // to decide whether we're actually binding to a temporary created from
2878 // the bit-field.
Douglas Gregor20093b42009-12-09 23:02:17 +00002879 if (DerivedToBase)
2880 Sequence.AddDerivedToBaseCastStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002881 S.Context.getQualifiedType(T1, T2Quals),
John McCall5baba9d2010-08-25 10:28:54 +00002882 VK_LValue);
Douglas Gregor569c3162010-08-07 11:51:51 +00002883 else if (ObjCConversion)
2884 Sequence.AddObjCObjectConversionStep(
2885 S.Context.getQualifiedType(T1, T2Quals));
2886
Chandler Carruth5535c382010-01-12 20:32:25 +00002887 if (T1Quals != T2Quals)
John McCall5baba9d2010-08-25 10:28:54 +00002888 Sequence.AddQualificationConversionStep(cv1T1, VK_LValue);
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002889 bool BindingTemporary = T1Quals.hasConst() && !T1Quals.hasVolatile() &&
Anders Carlsson09380262010-01-31 17:18:49 +00002890 (Initializer->getBitField() || Initializer->refersToVectorElement());
Douglas Gregorde4b1d82010-01-29 19:14:02 +00002891 Sequence.AddReferenceBindingStep(cv1T1, BindingTemporary);
Douglas Gregor20093b42009-12-09 23:02:17 +00002892 return;
2893 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002894
2895 // - has a class type (i.e., T2 is a class type), where T1 is not
2896 // reference-related to T2, and can be implicitly converted to an
2897 // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
2898 // with "cv3 T3" (this conversion is selected by enumerating the
Douglas Gregor20093b42009-12-09 23:02:17 +00002899 // applicable conversion functions (13.3.1.6) and choosing the best
2900 // one through overload resolution (13.3)),
Sebastian Redl4680bf22010-06-30 18:13:39 +00002901 // If we have an rvalue ref to function type here, the rhs must be
2902 // an rvalue.
2903 if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() &&
2904 (isLValueRef || InitCategory.isRValue())) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002905 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity, Kind,
Douglas Gregor20093b42009-12-09 23:02:17 +00002906 Initializer,
Sebastian Redl4680bf22010-06-30 18:13:39 +00002907 /*AllowRValues=*/isRValueRef,
Douglas Gregor20093b42009-12-09 23:02:17 +00002908 Sequence);
2909 if (ConvOvlResult == OR_Success)
2910 return;
John McCall1d318332010-01-12 00:44:57 +00002911 if (ConvOvlResult != OR_No_Viable_Function) {
2912 Sequence.SetOverloadFailure(
2913 InitializationSequence::FK_ReferenceInitOverloadFailed,
2914 ConvOvlResult);
2915 }
Douglas Gregor20093b42009-12-09 23:02:17 +00002916 }
2917 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002918
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002919 // - Otherwise, the reference shall be an lvalue reference to a
Douglas Gregor20093b42009-12-09 23:02:17 +00002920 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor69d83162011-01-20 16:08:06 +00002921 // shall be an rvalue reference.
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002922 if (isLValueRef && !(T1Quals.hasConst() && !T1Quals.hasVolatile())) {
Douglas Gregor3afb9772010-11-08 15:20:28 +00002923 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
2924 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
2925 else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
Douglas Gregor20093b42009-12-09 23:02:17 +00002926 Sequence.SetOverloadFailure(
2927 InitializationSequence::FK_ReferenceInitOverloadFailed,
2928 ConvOvlResult);
Douglas Gregorb2855ad2011-01-21 00:52:42 +00002929 else
Sebastian Redl4680bf22010-06-30 18:13:39 +00002930 Sequence.SetFailed(InitCategory.isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00002931 ? (RefRelationship == Sema::Ref_Related
2932 ? InitializationSequence::FK_ReferenceInitDropsQualifiers
2933 : InitializationSequence::FK_NonConstLValueReferenceBindingToUnrelated)
2934 : InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002935
Douglas Gregor20093b42009-12-09 23:02:17 +00002936 return;
2937 }
Sebastian Redl4680bf22010-06-30 18:13:39 +00002938
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002939 // - If the initializer expression
2940 // - is an xvalue, class prvalue, array prvalue, or function lvalue and
2941 // "cv1 T1" is reference-compatible with "cv2 T2"
2942 // Note: functions are handled below.
2943 if (!T1Function &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002944 (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification ||
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002945 (Kind.isCStyleOrFunctionalCast() &&
Douglas Gregor14d0aee2011-01-27 00:58:17 +00002946 RefRelationship == Sema::Ref_Related)) &&
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002947 (InitCategory.isXValue() ||
2948 (InitCategory.isPRValue() && T2->isRecordType()) ||
2949 (InitCategory.isPRValue() && T2->isArrayType()))) {
2950 ExprValueKind ValueKind = InitCategory.isXValue()? VK_XValue : VK_RValue;
2951 if (InitCategory.isPRValue() && T2->isRecordType()) {
Douglas Gregor523d46a2010-04-18 07:40:54 +00002952 // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
2953 // compiler the freedom to perform a copy here or bind to the
2954 // object, while C++0x requires that we bind directly to the
2955 // object. Hence, we always bind to the object without making an
2956 // extra copy. However, in C++03 requires that we check for the
2957 // presence of a suitable copy constructor:
2958 //
2959 // The constructor that would be used to make the copy shall
2960 // be callable whether or not the copy is actually done.
Francois Pichetf57258b2010-12-31 10:43:42 +00002961 if (!S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft)
Douglas Gregor523d46a2010-04-18 07:40:54 +00002962 Sequence.AddExtraneousCopyToTemporary(cv2T2);
Douglas Gregor20093b42009-12-09 23:02:17 +00002963 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002964
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002965 if (DerivedToBase)
2966 Sequence.AddDerivedToBaseCastStep(S.Context.getQualifiedType(T1, T2Quals),
2967 ValueKind);
2968 else if (ObjCConversion)
2969 Sequence.AddObjCObjectConversionStep(
2970 S.Context.getQualifiedType(T1, T2Quals));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002971
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002972 if (T1Quals != T2Quals)
2973 Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974 Sequence.AddReferenceBindingStep(cv1T1,
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002975 /*bindingTemporary=*/(InitCategory.isPRValue() && !T2->isArrayType()));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002976 return;
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002977 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002978
2979 // - has a class type (i.e., T2 is a class type), where T1 is not
2980 // reference-related to T2, and can be implicitly converted to an
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002981 // xvalue, class prvalue, or function lvalue of type "cv3 T3",
2982 // where "cv1 T1" is reference-compatible with "cv3 T3",
Douglas Gregorc5db24d2011-01-20 16:44:54 +00002983 if (T2->isRecordType()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00002984 if (RefRelationship == Sema::Ref_Incompatible) {
2985 ConvOvlResult = TryRefInitWithConversionFunction(S, Entity,
2986 Kind, Initializer,
2987 /*AllowRValues=*/true,
2988 Sequence);
2989 if (ConvOvlResult)
2990 Sequence.SetOverloadFailure(
2991 InitializationSequence::FK_ReferenceInitOverloadFailed,
2992 ConvOvlResult);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002993
Douglas Gregor20093b42009-12-09 23:02:17 +00002994 return;
2995 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002996
Douglas Gregor20093b42009-12-09 23:02:17 +00002997 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
2998 return;
2999 }
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003000
3001 // - Otherwise, a temporary of type "cv1 T1" is created and initialized
Douglas Gregor20093b42009-12-09 23:02:17 +00003002 // from the initializer expression using the rules for a non-reference
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003003 // copy initialization (8.5). The reference is then bound to the
Douglas Gregor20093b42009-12-09 23:02:17 +00003004 // temporary. [...]
John McCall369371c2010-06-04 02:29:22 +00003005
Douglas Gregor20093b42009-12-09 23:02:17 +00003006 // Determine whether we are allowed to call explicit constructors or
3007 // explicit conversion operators.
3008 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct);
John McCall369371c2010-06-04 02:29:22 +00003009
3010 InitializedEntity TempEntity = InitializedEntity::InitializeTemporary(cv1T1);
3011
John McCallf85e1932011-06-15 23:02:42 +00003012 ImplicitConversionSequence ICS
3013 = S.TryImplicitConversion(Initializer, TempEntity.getType(),
John McCall369371c2010-06-04 02:29:22 +00003014 /*SuppressUserConversions*/ false,
3015 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003016 /*FIXME:InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003017 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3018 /*AllowObjCWritebackConversion=*/false);
3019
3020 if (ICS.isBad()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003021 // FIXME: Use the conversion function set stored in ICS to turn
3022 // this into an overloading ambiguity diagnostic. However, we need
3023 // to keep that set as an OverloadCandidateSet rather than as some
3024 // other kind of set.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003025 if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty())
3026 Sequence.SetOverloadFailure(
3027 InitializationSequence::FK_ReferenceInitOverloadFailed,
3028 ConvOvlResult);
Douglas Gregor3afb9772010-11-08 15:20:28 +00003029 else if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
3030 Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003031 else
3032 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed);
Douglas Gregor20093b42009-12-09 23:02:17 +00003033 return;
John McCallf85e1932011-06-15 23:02:42 +00003034 } else {
3035 Sequence.AddConversionSequenceStep(ICS, TempEntity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003036 }
3037
3038 // [...] If T1 is reference-related to T2, cv1 must be the
3039 // same cv-qualification as, or greater cv-qualification
3040 // than, cv2; otherwise, the program is ill-formed.
Chandler Carruth5535c382010-01-12 20:32:25 +00003041 unsigned T1CVRQuals = T1Quals.getCVRQualifiers();
3042 unsigned T2CVRQuals = T2Quals.getCVRQualifiers();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003043 if (RefRelationship == Sema::Ref_Related &&
Chandler Carruth5535c382010-01-12 20:32:25 +00003044 (T1CVRQuals | T2CVRQuals) != T1CVRQuals) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003045 Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
3046 return;
3047 }
3048
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003049 // [...] If T1 is reference-related to T2 and the reference is an rvalue
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003050 // reference, the initializer expression shall not be an lvalue.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003051 if (RefRelationship >= Sema::Ref_Related && !isLValueRef &&
Douglas Gregorb2855ad2011-01-21 00:52:42 +00003052 InitCategory.isLValue()) {
3053 Sequence.SetFailed(
3054 InitializationSequence::FK_RValueReferenceBindingToLValue);
3055 return;
3056 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003057
Douglas Gregor20093b42009-12-09 23:02:17 +00003058 Sequence.AddReferenceBindingStep(cv1T1, /*bindingTemporary=*/true);
3059 return;
3060}
3061
3062/// \brief Attempt character array initialization from a string literal
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003063/// (C++ [dcl.init.string], C99 6.7.8).
3064static void TryStringLiteralInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003065 const InitializedEntity &Entity,
3066 const InitializationKind &Kind,
3067 Expr *Initializer,
3068 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003069 Sequence.AddStringInitStep(Entity.getType());
Douglas Gregor20093b42009-12-09 23:02:17 +00003070}
3071
Douglas Gregor20093b42009-12-09 23:02:17 +00003072/// \brief Attempt initialization by constructor (C++ [dcl.init]), which
3073/// enumerates the constructors of the initialized entity and performs overload
3074/// resolution to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003075static void TryConstructorInitialization(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003076 const InitializedEntity &Entity,
3077 const InitializationKind &Kind,
3078 Expr **Args, unsigned NumArgs,
Douglas Gregor71d17402009-12-15 00:01:57 +00003079 QualType DestType,
Douglas Gregor20093b42009-12-09 23:02:17 +00003080 InitializationSequence &Sequence) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003081 // Build the candidate set directly in the initialization sequence
3082 // structure, so that it will persist if we fail.
3083 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3084 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003085
Douglas Gregor51c56d62009-12-14 20:49:26 +00003086 // Determine whether we are allowed to call explicit constructors or
3087 // explicit conversion operators.
3088 bool AllowExplicit = (Kind.getKind() == InitializationKind::IK_Direct ||
3089 Kind.getKind() == InitializationKind::IK_Value ||
Douglas Gregor2f599792010-04-02 18:24:57 +00003090 Kind.getKind() == InitializationKind::IK_Default);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003091
3092 // The type we're constructing needs to be complete.
3093 if (S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor72a43bb2010-05-20 22:12:02 +00003094 Sequence.SetFailed(InitializationSequence::FK_Incomplete);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003095 return;
3096 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003097
Douglas Gregor51c56d62009-12-14 20:49:26 +00003098 // The type we're converting to is a class type. Enumerate its constructors
3099 // to see if one is suitable.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003100 const RecordType *DestRecordType = DestType->getAs<RecordType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003101 assert(DestRecordType && "Constructor initialization requires record type");
Douglas Gregor51c56d62009-12-14 20:49:26 +00003102 CXXRecordDecl *DestRecordDecl
3103 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003104
Douglas Gregor51c56d62009-12-14 20:49:26 +00003105 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003106 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003107 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003108 NamedDecl *D = *Con;
3109 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
Douglas Gregord1a27222010-04-24 20:54:38 +00003110 bool SuppressUserConversions = false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003111
Douglas Gregor51c56d62009-12-14 20:49:26 +00003112 // Find the constructor (which may be a template).
3113 CXXConstructorDecl *Constructor = 0;
John McCall9aa472c2010-03-19 07:35:19 +00003114 FunctionTemplateDecl *ConstructorTmpl = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003115 if (ConstructorTmpl)
3116 Constructor = cast<CXXConstructorDecl>(
3117 ConstructorTmpl->getTemplatedDecl());
Douglas Gregord1a27222010-04-24 20:54:38 +00003118 else {
John McCall9aa472c2010-03-19 07:35:19 +00003119 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregord1a27222010-04-24 20:54:38 +00003120
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003121 // If we're performing copy initialization using a copy constructor, we
Douglas Gregord1a27222010-04-24 20:54:38 +00003122 // suppress user-defined conversions on the arguments.
3123 // FIXME: Move constructors?
3124 if (Kind.getKind() == InitializationKind::IK_Copy &&
3125 Constructor->isCopyConstructor())
3126 SuppressUserConversions = true;
3127 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003128
Douglas Gregor51c56d62009-12-14 20:49:26 +00003129 if (!Constructor->isInvalidDecl() &&
Douglas Gregor99a2e602009-12-16 01:38:02 +00003130 (AllowExplicit || !Constructor->isExplicit())) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003131 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00003132 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003133 /*ExplicitArgs*/ 0,
Douglas Gregord1a27222010-04-24 20:54:38 +00003134 Args, NumArgs, CandidateSet,
3135 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003136 else
John McCall9aa472c2010-03-19 07:35:19 +00003137 S.AddOverloadCandidate(Constructor, FoundDecl,
Douglas Gregord1a27222010-04-24 20:54:38 +00003138 Args, NumArgs, CandidateSet,
3139 SuppressUserConversions);
Douglas Gregor51c56d62009-12-14 20:49:26 +00003140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003141 }
3142
Douglas Gregor51c56d62009-12-14 20:49:26 +00003143 SourceLocation DeclLoc = Kind.getLocation();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003144
3145 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor51c56d62009-12-14 20:49:26 +00003146 OverloadCandidateSet::iterator Best;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003147 if (OverloadingResult Result
John McCall120d63c2010-08-24 20:38:10 +00003148 = CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
Douglas Gregor51c56d62009-12-14 20:49:26 +00003149 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003150 InitializationSequence::FK_ConstructorOverloadFailed,
Douglas Gregor51c56d62009-12-14 20:49:26 +00003151 Result);
3152 return;
3153 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003154
3155 // C++0x [dcl.init]p6:
3156 // If a program calls for the default initialization of an object
3157 // of a const-qualified type T, T shall be a class type with a
3158 // user-provided default constructor.
3159 if (Kind.getKind() == InitializationKind::IK_Default &&
3160 Entity.getType().isConstQualified() &&
3161 cast<CXXConstructorDecl>(Best->Function)->isImplicit()) {
3162 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
3163 return;
3164 }
3165
Douglas Gregor51c56d62009-12-14 20:49:26 +00003166 // Add the constructor initialization step. Any cv-qualification conversion is
3167 // subsumed by the initialization.
Douglas Gregor2f599792010-04-02 18:24:57 +00003168 Sequence.AddConstructorInitializationStep(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003169 cast<CXXConstructorDecl>(Best->Function),
John McCall9aa472c2010-03-19 07:35:19 +00003170 Best->FoundDecl.getAccess(),
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003171 DestType);
Douglas Gregor20093b42009-12-09 23:02:17 +00003172}
3173
Douglas Gregor71d17402009-12-15 00:01:57 +00003174/// \brief Attempt value initialization (C++ [dcl.init]p7).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175static void TryValueInitialization(Sema &S,
Douglas Gregor71d17402009-12-15 00:01:57 +00003176 const InitializedEntity &Entity,
3177 const InitializationKind &Kind,
3178 InitializationSequence &Sequence) {
3179 // C++ [dcl.init]p5:
3180 //
3181 // To value-initialize an object of type T means:
Douglas Gregord6542d82009-12-22 15:35:07 +00003182 QualType T = Entity.getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003183
Douglas Gregor71d17402009-12-15 00:01:57 +00003184 // -- if T is an array type, then each element is value-initialized;
3185 while (const ArrayType *AT = S.Context.getAsArrayType(T))
3186 T = AT->getElementType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187
Douglas Gregor71d17402009-12-15 00:01:57 +00003188 if (const RecordType *RT = T->getAs<RecordType>()) {
3189 if (CXXRecordDecl *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3190 // -- if T is a class type (clause 9) with a user-declared
3191 // constructor (12.1), then the default constructor for T is
3192 // called (and the initialization is ill-formed if T has no
3193 // accessible default constructor);
3194 //
3195 // FIXME: we really want to refer to a single subobject of the array,
3196 // but Entity doesn't have a way to capture that (yet).
3197 if (ClassDecl->hasUserDeclaredConstructor())
3198 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003199
Douglas Gregor16006c92009-12-16 18:50:27 +00003200 // -- if T is a (possibly cv-qualified) non-union class type
3201 // without a user-provided constructor, then the object is
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003202 // zero-initialized and, if T's implicitly-declared default
Douglas Gregor16006c92009-12-16 18:50:27 +00003203 // constructor is non-trivial, that constructor is called.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003204 if ((ClassDecl->getTagKind() == TTK_Class ||
Douglas Gregored8abf12010-07-08 06:14:04 +00003205 ClassDecl->getTagKind() == TTK_Struct)) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003206 Sequence.AddZeroInitializationStep(Entity.getType());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003207 return TryConstructorInitialization(S, Entity, Kind, 0, 0, T, Sequence);
Douglas Gregor16006c92009-12-16 18:50:27 +00003208 }
Douglas Gregor71d17402009-12-15 00:01:57 +00003209 }
3210 }
3211
Douglas Gregord6542d82009-12-22 15:35:07 +00003212 Sequence.AddZeroInitializationStep(Entity.getType());
Douglas Gregor71d17402009-12-15 00:01:57 +00003213}
3214
Douglas Gregor99a2e602009-12-16 01:38:02 +00003215/// \brief Attempt default initialization (C++ [dcl.init]p6).
3216static void TryDefaultInitialization(Sema &S,
3217 const InitializedEntity &Entity,
3218 const InitializationKind &Kind,
3219 InitializationSequence &Sequence) {
3220 assert(Kind.getKind() == InitializationKind::IK_Default);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003221
Douglas Gregor99a2e602009-12-16 01:38:02 +00003222 // C++ [dcl.init]p6:
3223 // To default-initialize an object of type T means:
3224 // - if T is an array type, each element is default-initialized;
John McCallf85e1932011-06-15 23:02:42 +00003225 QualType DestType = S.Context.getBaseElementType(Entity.getType());
3226
Douglas Gregor99a2e602009-12-16 01:38:02 +00003227 // - if T is a (possibly cv-qualified) class type (Clause 9), the default
3228 // constructor for T is called (and the initialization is ill-formed if
3229 // T has no accessible default constructor);
Douglas Gregor60c93c92010-02-09 07:26:29 +00003230 if (DestType->isRecordType() && S.getLangOptions().CPlusPlus) {
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00003231 TryConstructorInitialization(S, Entity, Kind, 0, 0, DestType, Sequence);
3232 return;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003233 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003234
Douglas Gregor99a2e602009-12-16 01:38:02 +00003235 // - otherwise, no initialization is performed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003236
Douglas Gregor99a2e602009-12-16 01:38:02 +00003237 // If a program calls for the default initialization of an object of
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003238 // a const-qualified type T, T shall be a class type with a user-provided
Douglas Gregor99a2e602009-12-16 01:38:02 +00003239 // default constructor.
John McCallf85e1932011-06-15 23:02:42 +00003240 if (DestType.isConstQualified() && S.getLangOptions().CPlusPlus) {
Douglas Gregor99a2e602009-12-16 01:38:02 +00003241 Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
John McCallf85e1932011-06-15 23:02:42 +00003242 return;
3243 }
3244
3245 // If the destination type has a lifetime property, zero-initialize it.
3246 if (DestType.getQualifiers().hasObjCLifetime()) {
3247 Sequence.AddZeroInitializationStep(Entity.getType());
3248 return;
3249 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00003250}
3251
Douglas Gregor20093b42009-12-09 23:02:17 +00003252/// \brief Attempt a user-defined conversion between two types (C++ [dcl.init]),
3253/// which enumerates all conversion functions and performs overload resolution
3254/// to select the best.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003255static void TryUserDefinedConversion(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00003256 const InitializedEntity &Entity,
3257 const InitializationKind &Kind,
3258 Expr *Initializer,
3259 InitializationSequence &Sequence) {
Douglas Gregord6542d82009-12-22 15:35:07 +00003260 QualType DestType = Entity.getType();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003261 assert(!DestType->isReferenceType() && "References are handled elsewhere");
3262 QualType SourceType = Initializer->getType();
3263 assert((DestType->isRecordType() || SourceType->isRecordType()) &&
3264 "Must have a class type to perform a user-defined conversion");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003265
Douglas Gregor4a520a22009-12-14 17:27:33 +00003266 // Build the candidate set directly in the initialization sequence
3267 // structure, so that it will persist if we fail.
3268 OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
3269 CandidateSet.clear();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003270
Douglas Gregor4a520a22009-12-14 17:27:33 +00003271 // Determine whether we are allowed to call explicit constructors or
3272 // explicit conversion operators.
3273 bool AllowExplicit = Kind.getKind() == InitializationKind::IK_Direct;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003274
Douglas Gregor4a520a22009-12-14 17:27:33 +00003275 if (const RecordType *DestRecordType = DestType->getAs<RecordType>()) {
3276 // The type we're converting to is a class type. Enumerate its constructors
3277 // to see if there is a suitable conversion.
3278 CXXRecordDecl *DestRecordDecl
3279 = cast<CXXRecordDecl>(DestRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003280
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003281 // Try to complete the type we're converting to.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003282 if (!S.RequireCompleteType(Kind.getLocation(), DestType, 0)) {
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003283 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003284 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(DestRecordDecl);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003285 Con != ConEnd; ++Con) {
3286 NamedDecl *D = *Con;
3287 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003288
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003289 // Find the constructor (which may be a template).
3290 CXXConstructorDecl *Constructor = 0;
3291 FunctionTemplateDecl *ConstructorTmpl
3292 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003293 if (ConstructorTmpl)
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003294 Constructor = cast<CXXConstructorDecl>(
3295 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor4712c022010-07-01 03:43:00 +00003296 else
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003297 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003298
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003299 if (!Constructor->isInvalidDecl() &&
3300 Constructor->isConvertingConstructor(AllowExplicit)) {
3301 if (ConstructorTmpl)
3302 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3303 /*ExplicitArgs*/ 0,
3304 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003305 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003306 else
3307 S.AddOverloadCandidate(Constructor, FoundDecl,
3308 &Initializer, 1, CandidateSet,
Douglas Gregor4712c022010-07-01 03:43:00 +00003309 /*SuppressUserConversions=*/true);
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003310 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003311 }
Douglas Gregor087fb7d2010-04-26 14:36:57 +00003312 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003313 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003314
3315 SourceLocation DeclLoc = Initializer->getLocStart();
3316
Douglas Gregor4a520a22009-12-14 17:27:33 +00003317 if (const RecordType *SourceRecordType = SourceType->getAs<RecordType>()) {
3318 // The type we're converting from is a class type, enumerate its conversion
3319 // functions.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003320
Eli Friedman33c2da92009-12-20 22:12:03 +00003321 // We can only enumerate the conversion functions for a complete type; if
3322 // the type isn't complete, simply skip this step.
3323 if (!S.RequireCompleteType(DeclLoc, SourceType, 0)) {
3324 CXXRecordDecl *SourceRecordDecl
3325 = cast<CXXRecordDecl>(SourceRecordType->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003326
John McCalleec51cf2010-01-20 00:46:10 +00003327 const UnresolvedSetImpl *Conversions
Eli Friedman33c2da92009-12-20 22:12:03 +00003328 = SourceRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003329 for (UnresolvedSetImpl::const_iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003330 E = Conversions->end();
Eli Friedman33c2da92009-12-20 22:12:03 +00003331 I != E; ++I) {
3332 NamedDecl *D = *I;
3333 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3334 if (isa<UsingShadowDecl>(D))
3335 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003336
Eli Friedman33c2da92009-12-20 22:12:03 +00003337 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
3338 CXXConversionDecl *Conv;
Douglas Gregor4a520a22009-12-14 17:27:33 +00003339 if (ConvTemplate)
Eli Friedman33c2da92009-12-20 22:12:03 +00003340 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Douglas Gregor4a520a22009-12-14 17:27:33 +00003341 else
John McCall32daa422010-03-31 01:36:47 +00003342 Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003343
Eli Friedman33c2da92009-12-20 22:12:03 +00003344 if (AllowExplicit || !Conv->isExplicit()) {
3345 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00003346 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(),
John McCall86820f52010-01-26 01:37:31 +00003347 ActingDC, Initializer, DestType,
Eli Friedman33c2da92009-12-20 22:12:03 +00003348 CandidateSet);
3349 else
John McCall9aa472c2010-03-19 07:35:19 +00003350 S.AddConversionCandidate(Conv, I.getPair(), ActingDC,
John McCall86820f52010-01-26 01:37:31 +00003351 Initializer, DestType, CandidateSet);
Eli Friedman33c2da92009-12-20 22:12:03 +00003352 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003353 }
3354 }
3355 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003356
3357 // Perform overload resolution. If it fails, return the failed result.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003358 OverloadCandidateSet::iterator Best;
John McCall1d318332010-01-12 00:44:57 +00003359 if (OverloadingResult Result
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003360 = CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Douglas Gregor4a520a22009-12-14 17:27:33 +00003361 Sequence.SetOverloadFailure(
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003362 InitializationSequence::FK_UserConversionOverloadFailed,
Douglas Gregor4a520a22009-12-14 17:27:33 +00003363 Result);
3364 return;
3365 }
John McCall1d318332010-01-12 00:44:57 +00003366
Douglas Gregor4a520a22009-12-14 17:27:33 +00003367 FunctionDecl *Function = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003368 S.MarkDeclarationReferenced(DeclLoc, Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369
Douglas Gregor4a520a22009-12-14 17:27:33 +00003370 if (isa<CXXConstructorDecl>(Function)) {
3371 // Add the user-defined conversion step. Any cv-qualification conversion is
3372 // subsumed by the initialization.
John McCall9aa472c2010-03-19 07:35:19 +00003373 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
Douglas Gregor4a520a22009-12-14 17:27:33 +00003374 return;
3375 }
3376
3377 // Add the user-defined conversion step that calls the conversion function.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00003378 QualType ConvType = Function->getCallResultType();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003379 if (ConvType->getAs<RecordType>()) {
3380 // If we're converting to a class type, there may be an copy if
3381 // the resulting temporary object (possible to create an object of
3382 // a base class type). That copy is not a separate conversion, so
3383 // we just make a note of the actual destination type (possibly a
3384 // base class of the type returned by the conversion function) and
3385 // let the user-defined conversion step handle the conversion.
3386 Sequence.AddUserConversionStep(Function, Best->FoundDecl, DestType);
3387 return;
3388 }
Douglas Gregor4a520a22009-12-14 17:27:33 +00003389
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003390 Sequence.AddUserConversionStep(Function, Best->FoundDecl, ConvType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003391
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003392 // If the conversion following the call to the conversion function
3393 // is interesting, add it as a separate step.
Douglas Gregor4a520a22009-12-14 17:27:33 +00003394 if (Best->FinalConversion.First || Best->FinalConversion.Second ||
3395 Best->FinalConversion.Third) {
3396 ImplicitConversionSequence ICS;
John McCall1d318332010-01-12 00:44:57 +00003397 ICS.setStandard();
Douglas Gregor4a520a22009-12-14 17:27:33 +00003398 ICS.Standard = Best->FinalConversion;
3399 Sequence.AddConversionSequenceStep(ICS, DestType);
3400 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003401}
3402
John McCallf85e1932011-06-15 23:02:42 +00003403/// The non-zero enum values here are indexes into diagnostic alternatives.
3404enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar };
3405
3406/// Determines whether this expression is an acceptable ICR source.
John McCallc03fa492011-06-27 23:59:58 +00003407static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e,
3408 bool isAddressOf) {
John McCallf85e1932011-06-15 23:02:42 +00003409 // Skip parens.
3410 e = e->IgnoreParens();
3411
3412 // Skip address-of nodes.
3413 if (UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
3414 if (op->getOpcode() == UO_AddrOf)
John McCallc03fa492011-06-27 23:59:58 +00003415 return isInvalidICRSource(C, op->getSubExpr(), /*addressof*/ true);
John McCallf85e1932011-06-15 23:02:42 +00003416
3417 // Skip certain casts.
John McCallc03fa492011-06-27 23:59:58 +00003418 } else if (CastExpr *ce = dyn_cast<CastExpr>(e)) {
3419 switch (ce->getCastKind()) {
John McCallf85e1932011-06-15 23:02:42 +00003420 case CK_Dependent:
3421 case CK_BitCast:
3422 case CK_LValueBitCast:
John McCallf85e1932011-06-15 23:02:42 +00003423 case CK_NoOp:
John McCallc03fa492011-06-27 23:59:58 +00003424 return isInvalidICRSource(C, ce->getSubExpr(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003425
3426 case CK_ArrayToPointerDecay:
3427 return IIK_nonscalar;
3428
3429 case CK_NullToPointer:
3430 return IIK_okay;
3431
3432 default:
3433 break;
3434 }
3435
3436 // If we have a declaration reference, it had better be a local variable.
John McCallc03fa492011-06-27 23:59:58 +00003437 } else if (isa<DeclRefExpr>(e) || isa<BlockDeclRefExpr>(e)) {
3438 if (!isAddressOf) return IIK_nonlocal;
3439
3440 VarDecl *var;
3441 if (isa<DeclRefExpr>(e)) {
3442 var = dyn_cast<VarDecl>(cast<DeclRefExpr>(e)->getDecl());
3443 if (!var) return IIK_nonlocal;
3444 } else {
3445 var = cast<BlockDeclRefExpr>(e)->getDecl();
3446 }
3447
3448 return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal);
John McCallf85e1932011-06-15 23:02:42 +00003449
3450 // If we have a conditional operator, check both sides.
3451 } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(e)) {
John McCallc03fa492011-06-27 23:59:58 +00003452 if (InvalidICRKind iik = isInvalidICRSource(C, cond->getLHS(), isAddressOf))
John McCallf85e1932011-06-15 23:02:42 +00003453 return iik;
3454
John McCallc03fa492011-06-27 23:59:58 +00003455 return isInvalidICRSource(C, cond->getRHS(), isAddressOf);
John McCallf85e1932011-06-15 23:02:42 +00003456
3457 // These are never scalar.
3458 } else if (isa<ArraySubscriptExpr>(e)) {
3459 return IIK_nonscalar;
3460
3461 // Otherwise, it needs to be a null pointer constant.
3462 } else {
3463 return (e->isNullPointerConstant(C, Expr::NPC_ValueDependentIsNull)
3464 ? IIK_okay : IIK_nonlocal);
3465 }
3466
3467 return IIK_nonlocal;
3468}
3469
3470/// Check whether the given expression is a valid operand for an
3471/// indirect copy/restore.
3472static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) {
3473 assert(src->isRValue());
3474
John McCallc03fa492011-06-27 23:59:58 +00003475 InvalidICRKind iik = isInvalidICRSource(S.Context, src, false);
John McCallf85e1932011-06-15 23:02:42 +00003476 if (iik == IIK_okay) return;
3477
3478 S.Diag(src->getExprLoc(), diag::err_arc_nonlocal_writeback)
3479 << ((unsigned) iik - 1) // shift index into diagnostic explanations
3480 << src->getSourceRange();
3481}
3482
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003483/// \brief Determine whether we have compatible array types for the
3484/// purposes of GNU by-copy array initialization.
3485static bool hasCompatibleArrayTypes(ASTContext &Context,
3486 const ArrayType *Dest,
3487 const ArrayType *Source) {
3488 // If the source and destination array types are equivalent, we're
3489 // done.
3490 if (Context.hasSameType(QualType(Dest, 0), QualType(Source, 0)))
3491 return true;
3492
3493 // Make sure that the element types are the same.
3494 if (!Context.hasSameType(Dest->getElementType(), Source->getElementType()))
3495 return false;
3496
3497 // The only mismatch we allow is when the destination is an
3498 // incomplete array type and the source is a constant array type.
3499 return Source->isConstantArrayType() && Dest->isIncompleteArrayType();
3500}
3501
John McCallf85e1932011-06-15 23:02:42 +00003502static bool tryObjCWritebackConversion(Sema &S,
3503 InitializationSequence &Sequence,
3504 const InitializedEntity &Entity,
3505 Expr *Initializer) {
3506 bool ArrayDecay = false;
3507 QualType ArgType = Initializer->getType();
3508 QualType ArgPointee;
3509 if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(ArgType)) {
3510 ArrayDecay = true;
3511 ArgPointee = ArgArrayType->getElementType();
3512 ArgType = S.Context.getPointerType(ArgPointee);
3513 }
3514
3515 // Handle write-back conversion.
3516 QualType ConvertedArgType;
3517 if (!S.isObjCWritebackConversion(ArgType, Entity.getType(),
3518 ConvertedArgType))
3519 return false;
3520
3521 // We should copy unless we're passing to an argument explicitly
3522 // marked 'out'.
3523 bool ShouldCopy = true;
3524 if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3525 ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3526
3527 // Do we need an lvalue conversion?
3528 if (ArrayDecay || Initializer->isGLValue()) {
3529 ImplicitConversionSequence ICS;
3530 ICS.setStandard();
3531 ICS.Standard.setAsIdentityConversion();
3532
3533 QualType ResultType;
3534 if (ArrayDecay) {
3535 ICS.Standard.First = ICK_Array_To_Pointer;
3536 ResultType = S.Context.getPointerType(ArgPointee);
3537 } else {
3538 ICS.Standard.First = ICK_Lvalue_To_Rvalue;
3539 ResultType = Initializer->getType().getNonLValueExprType(S.Context);
3540 }
3541
3542 Sequence.AddConversionSequenceStep(ICS, ResultType);
3543 }
3544
3545 Sequence.AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
3546 return true;
3547}
3548
Douglas Gregor20093b42009-12-09 23:02:17 +00003549InitializationSequence::InitializationSequence(Sema &S,
3550 const InitializedEntity &Entity,
3551 const InitializationKind &Kind,
3552 Expr **Args,
John McCall5769d612010-02-08 23:07:23 +00003553 unsigned NumArgs)
3554 : FailedCandidateSet(Kind.getLocation()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003555 ASTContext &Context = S.Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003556
Douglas Gregor20093b42009-12-09 23:02:17 +00003557 // C++0x [dcl.init]p16:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003558 // The semantics of initializers are as follows. The destination type is
3559 // the type of the object or reference being initialized and the source
Douglas Gregor20093b42009-12-09 23:02:17 +00003560 // type is the type of the initializer expression. The source type is not
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003561 // defined when the initializer is a braced-init-list or when it is a
Douglas Gregor20093b42009-12-09 23:02:17 +00003562 // parenthesized list of expressions.
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003563 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00003564
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003565 if (DestType->isDependentType() ||
Douglas Gregor20093b42009-12-09 23:02:17 +00003566 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3567 SequenceKind = DependentSequence;
3568 return;
3569 }
3570
Sebastian Redl7491c492011-06-05 13:59:11 +00003571 // Almost everything is a normal sequence.
3572 setSequenceKind(NormalSequence);
3573
John McCall241d5582010-12-07 22:54:16 +00003574 for (unsigned I = 0; I != NumArgs; ++I)
John Wiegley429bb272011-04-08 18:41:53 +00003575 if (Args[I]->getObjectKind() == OK_ObjCProperty) {
3576 ExprResult Result = S.ConvertPropertyForRValue(Args[I]);
3577 if (Result.isInvalid()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003578 SetFailed(FK_ConversionFromPropertyFailed);
John Wiegley429bb272011-04-08 18:41:53 +00003579 return;
3580 }
3581 Args[I] = Result.take();
3582 }
John McCall241d5582010-12-07 22:54:16 +00003583
Douglas Gregor20093b42009-12-09 23:02:17 +00003584 QualType SourceType;
3585 Expr *Initializer = 0;
Douglas Gregor99a2e602009-12-16 01:38:02 +00003586 if (NumArgs == 1) {
Douglas Gregor20093b42009-12-09 23:02:17 +00003587 Initializer = Args[0];
3588 if (!isa<InitListExpr>(Initializer))
3589 SourceType = Initializer->getType();
3590 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003591
3592 // - If the initializer is a braced-init-list, the object is
Douglas Gregor20093b42009-12-09 23:02:17 +00003593 // list-initialized (8.5.4).
3594 if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Initializer)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003595 TryListInitialization(S, Entity, Kind, InitList, *this);
Douglas Gregord87b61f2009-12-10 17:56:55 +00003596 return;
Douglas Gregor20093b42009-12-09 23:02:17 +00003597 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003598
Douglas Gregor20093b42009-12-09 23:02:17 +00003599 // - If the destination type is a reference type, see 8.5.3.
3600 if (DestType->isReferenceType()) {
3601 // C++0x [dcl.init.ref]p1:
3602 // A variable declared to be a T& or T&&, that is, "reference to type T"
3603 // (8.3.2), shall be initialized by an object, or function, of type T or
3604 // by an object that can be converted into a T.
3605 // (Therefore, multiple arguments are not permitted.)
3606 if (NumArgs != 1)
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003607 SetFailed(FK_TooManyInitsForReference);
Douglas Gregor20093b42009-12-09 23:02:17 +00003608 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003609 TryReferenceInitialization(S, Entity, Kind, Args[0], *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003610 return;
3611 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003612
Douglas Gregor20093b42009-12-09 23:02:17 +00003613 // - If the initializer is (), the object is value-initialized.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003614 if (Kind.getKind() == InitializationKind::IK_Value ||
3615 (Kind.getKind() == InitializationKind::IK_Direct && NumArgs == 0)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003616 TryValueInitialization(S, Entity, Kind, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003617 return;
3618 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003619
Douglas Gregor99a2e602009-12-16 01:38:02 +00003620 // Handle default initialization.
Nick Lewycky7663f392010-11-20 01:29:55 +00003621 if (Kind.getKind() == InitializationKind::IK_Default) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003622 TryDefaultInitialization(S, Entity, Kind, *this);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003623 return;
3624 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003625
John McCallce6c9b72011-02-21 07:22:22 +00003626 // - If the destination type is an array of characters, an array of
3627 // char16_t, an array of char32_t, or an array of wchar_t, and the
3628 // initializer is a string literal, see 8.5.2.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003629 // - Otherwise, if the destination type is an array, the program is
Douglas Gregor20093b42009-12-09 23:02:17 +00003630 // ill-formed.
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003631 if (const ArrayType *DestAT = Context.getAsArrayType(DestType)) {
3632 if (Initializer && IsStringInit(Initializer, DestAT, Context)) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003633 TryStringLiteralInitialization(S, Entity, Kind, Initializer, *this);
John McCallce6c9b72011-02-21 07:22:22 +00003634 return;
3635 }
3636
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003637 // Note: as an GNU C extension, we allow initialization of an
3638 // array from a compound literal that creates an array of the same
3639 // type, so long as the initializer has no side effects.
3640 if (!S.getLangOptions().CPlusPlus && Initializer &&
3641 isa<CompoundLiteralExpr>(Initializer->IgnoreParens()) &&
3642 Initializer->getType()->isArrayType()) {
3643 const ArrayType *SourceAT
3644 = Context.getAsArrayType(Initializer->getType());
3645 if (!hasCompatibleArrayTypes(S.Context, DestAT, SourceAT))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003646 SetFailed(FK_ArrayTypeMismatch);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003647 else if (Initializer->HasSideEffects(S.Context))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003648 SetFailed(FK_NonConstantArrayInit);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003649 else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003650 AddArrayInitStep(DestType);
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00003651 }
3652 } else if (DestAT->getElementType()->isAnyCharacterType())
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003653 SetFailed(FK_ArrayNeedsInitListOrStringLiteral);
Douglas Gregor20093b42009-12-09 23:02:17 +00003654 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003655 SetFailed(FK_ArrayNeedsInitList);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003656
Douglas Gregor20093b42009-12-09 23:02:17 +00003657 return;
3658 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003659
John McCallf85e1932011-06-15 23:02:42 +00003660 // Determine whether we should consider writeback conversions for
3661 // Objective-C ARC.
3662 bool allowObjCWritebackConversion = S.getLangOptions().ObjCAutoRefCount &&
3663 Entity.getKind() == InitializedEntity::EK_Parameter;
3664
3665 // We're at the end of the line for C: it's either a write-back conversion
3666 // or it's a C assignment. There's no need to check anything else.
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003667 if (!S.getLangOptions().CPlusPlus) {
John McCallf85e1932011-06-15 23:02:42 +00003668 // If allowed, check whether this is an Objective-C writeback conversion.
3669 if (allowObjCWritebackConversion &&
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003670 tryObjCWritebackConversion(S, *this, Entity, Initializer)) {
John McCallf85e1932011-06-15 23:02:42 +00003671 return;
3672 }
3673
3674 // Handle initialization in C
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003675 AddCAssignmentStep(DestType);
3676 MaybeProduceObjCObject(S, *this, Entity);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00003677 return;
3678 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003679
John McCallf85e1932011-06-15 23:02:42 +00003680 assert(S.getLangOptions().CPlusPlus);
3681
Douglas Gregor20093b42009-12-09 23:02:17 +00003682 // - If the destination type is a (possibly cv-qualified) class type:
3683 if (DestType->isRecordType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684 // - If the initialization is direct-initialization, or if it is
3685 // copy-initialization where the cv-unqualified version of the
3686 // source type is the same class as, or a derived class of, the
Douglas Gregor20093b42009-12-09 23:02:17 +00003687 // class of the destination, constructors are considered. [...]
3688 if (Kind.getKind() == InitializationKind::IK_Direct ||
3689 (Kind.getKind() == InitializationKind::IK_Copy &&
3690 (Context.hasSameUnqualifiedType(SourceType, DestType) ||
3691 S.IsDerivedFrom(SourceType, DestType))))
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003692 TryConstructorInitialization(S, Entity, Kind, Args, NumArgs,
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003693 Entity.getType(), *this);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003694 // - Otherwise (i.e., for the remaining copy-initialization cases),
Douglas Gregor20093b42009-12-09 23:02:17 +00003695 // user-defined conversion sequences that can convert from the source
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003696 // type to the destination type or (when a conversion function is
Douglas Gregor20093b42009-12-09 23:02:17 +00003697 // used) to a derived class thereof are enumerated as described in
3698 // 13.3.1.4, and the best one is chosen through overload resolution
3699 // (13.3).
3700 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003701 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
Douglas Gregor20093b42009-12-09 23:02:17 +00003702 return;
3703 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003704
Douglas Gregor99a2e602009-12-16 01:38:02 +00003705 if (NumArgs > 1) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003706 SetFailed(FK_TooManyInitsForScalar);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003707 return;
3708 }
3709 assert(NumArgs == 1 && "Zero-argument case handled above");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003710
3711 // - Otherwise, if the source type is a (possibly cv-qualified) class
Douglas Gregor20093b42009-12-09 23:02:17 +00003712 // type, conversion functions are considered.
Douglas Gregor99a2e602009-12-16 01:38:02 +00003713 if (!SourceType.isNull() && SourceType->isRecordType()) {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003714 TryUserDefinedConversion(S, Entity, Kind, Initializer, *this);
3715 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00003716 return;
3717 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003718
Douglas Gregor20093b42009-12-09 23:02:17 +00003719 // - Otherwise, the initial value of the object being initialized is the
Douglas Gregor4a520a22009-12-14 17:27:33 +00003720 // (possibly converted) value of the initializer expression. Standard
Douglas Gregor20093b42009-12-09 23:02:17 +00003721 // conversions (Clause 4) will be used, if necessary, to convert the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003722 // initializer expression to the cv-unqualified version of the
Douglas Gregor20093b42009-12-09 23:02:17 +00003723 // destination type; no user-defined conversions are considered.
John McCallf85e1932011-06-15 23:02:42 +00003724
3725 ImplicitConversionSequence ICS
3726 = S.TryImplicitConversion(Initializer, Entity.getType(),
3727 /*SuppressUserConversions*/true,
John McCall369371c2010-06-04 02:29:22 +00003728 /*AllowExplicitConversions*/ false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003729 /*InOverloadResolution*/ false,
John McCallf85e1932011-06-15 23:02:42 +00003730 /*CStyle=*/Kind.isCStyleOrFunctionalCast(),
3731 allowObjCWritebackConversion);
3732
3733 if (ICS.isStandard() &&
3734 ICS.Standard.Second == ICK_Writeback_Conversion) {
3735 // Objective-C ARC writeback conversion.
3736
3737 // We should copy unless we're passing to an argument explicitly
3738 // marked 'out'.
3739 bool ShouldCopy = true;
3740 if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Entity.getDecl()))
3741 ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out);
3742
3743 // If there was an lvalue adjustment, add it as a separate conversion.
3744 if (ICS.Standard.First == ICK_Array_To_Pointer ||
3745 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
3746 ImplicitConversionSequence LvalueICS;
3747 LvalueICS.setStandard();
3748 LvalueICS.Standard.setAsIdentityConversion();
3749 LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(0));
3750 LvalueICS.Standard.First = ICS.Standard.First;
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003751 AddConversionSequenceStep(LvalueICS, ICS.Standard.getToType(0));
John McCallf85e1932011-06-15 23:02:42 +00003752 }
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003753
3754 AddPassByIndirectCopyRestoreStep(Entity.getType(), ShouldCopy);
John McCallf85e1932011-06-15 23:02:42 +00003755 } else if (ICS.isBad()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00003756 DeclAccessPair dap;
3757 if (Initializer->getType() == Context.OverloadTy &&
3758 !S.ResolveAddressOfOverloadedFunction(Initializer
3759 , DestType, false, dap))
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003760 SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
Douglas Gregor8e960432010-11-08 03:40:48 +00003761 else
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003762 SetFailed(InitializationSequence::FK_ConversionFailed);
John McCallf85e1932011-06-15 23:02:42 +00003763 } else {
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003764 AddConversionSequenceStep(ICS, Entity.getType());
John McCall856d3792011-06-16 23:24:51 +00003765
Rafael Espindola12ce0a02011-07-14 22:58:04 +00003766 MaybeProduceObjCObject(S, *this, Entity);
Douglas Gregor8e960432010-11-08 03:40:48 +00003767 }
Douglas Gregor20093b42009-12-09 23:02:17 +00003768}
3769
3770InitializationSequence::~InitializationSequence() {
Chris Lattner5f9e2722011-07-23 10:55:15 +00003771 for (SmallVectorImpl<Step>::iterator Step = Steps.begin(),
Douglas Gregor20093b42009-12-09 23:02:17 +00003772 StepEnd = Steps.end();
3773 Step != StepEnd; ++Step)
3774 Step->Destroy();
3775}
3776
3777//===----------------------------------------------------------------------===//
3778// Perform initialization
3779//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003780static Sema::AssignmentAction
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003781getAssignmentAction(const InitializedEntity &Entity) {
3782 switch(Entity.getKind()) {
3783 case InitializedEntity::EK_Variable:
3784 case InitializedEntity::EK_New:
Douglas Gregora3998bd2010-12-02 21:47:04 +00003785 case InitializedEntity::EK_Exception:
3786 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003787 case InitializedEntity::EK_Delegating:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003788 return Sema::AA_Initializing;
3789
3790 case InitializedEntity::EK_Parameter:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003791 if (Entity.getDecl() &&
Douglas Gregor688fc9b2010-04-21 23:24:10 +00003792 isa<ObjCMethodDecl>(Entity.getDecl()->getDeclContext()))
3793 return Sema::AA_Sending;
3794
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003795 return Sema::AA_Passing;
3796
3797 case InitializedEntity::EK_Result:
3798 return Sema::AA_Returning;
3799
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003800 case InitializedEntity::EK_Temporary:
3801 // FIXME: Can we tell apart casting vs. converting?
3802 return Sema::AA_Casting;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003803
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003804 case InitializedEntity::EK_Member:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003805 case InitializedEntity::EK_ArrayElement:
3806 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003807 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003808 return Sema::AA_Initializing;
3809 }
3810
3811 return Sema::AA_Converting;
3812}
3813
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003814/// \brief Whether we should binding a created object as a temporary when
3815/// initializing the given entity.
Douglas Gregor2f599792010-04-02 18:24:57 +00003816static bool shouldBindAsTemporary(const InitializedEntity &Entity) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003817 switch (Entity.getKind()) {
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003818 case InitializedEntity::EK_ArrayElement:
3819 case InitializedEntity::EK_Member:
Douglas Gregor2f599792010-04-02 18:24:57 +00003820 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003821 case InitializedEntity::EK_New:
3822 case InitializedEntity::EK_Variable:
3823 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003824 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003825 case InitializedEntity::EK_VectorElement:
Anders Carlssona508b7d2010-02-06 23:23:06 +00003826 case InitializedEntity::EK_Exception:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003827 case InitializedEntity::EK_BlockElement:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003828 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003829
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003830 case InitializedEntity::EK_Parameter:
3831 case InitializedEntity::EK_Temporary:
3832 return true;
3833 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003834
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003835 llvm_unreachable("missed an InitializedEntity kind?");
3836}
3837
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003838/// \brief Whether the given entity, when initialized with an object
3839/// created for that initialization, requires destruction.
3840static bool shouldDestroyTemporary(const InitializedEntity &Entity) {
3841 switch (Entity.getKind()) {
3842 case InitializedEntity::EK_Member:
3843 case InitializedEntity::EK_Result:
3844 case InitializedEntity::EK_New:
3845 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003846 case InitializedEntity::EK_Delegating:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003847 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003848 case InitializedEntity::EK_BlockElement:
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003849 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003850
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003851 case InitializedEntity::EK_Variable:
3852 case InitializedEntity::EK_Parameter:
3853 case InitializedEntity::EK_Temporary:
3854 case InitializedEntity::EK_ArrayElement:
3855 case InitializedEntity::EK_Exception:
3856 return true;
3857 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003858
3859 llvm_unreachable("missed an InitializedEntity kind?");
Douglas Gregor4154e0b2010-04-24 23:45:46 +00003860}
3861
Douglas Gregor523d46a2010-04-18 07:40:54 +00003862/// \brief Make a (potentially elidable) temporary copy of the object
3863/// provided by the given initializer by calling the appropriate copy
3864/// constructor.
3865///
3866/// \param S The Sema object used for type-checking.
3867///
Abramo Bagnara63e7d252011-01-27 19:55:10 +00003868/// \param T The type of the temporary object, which must either be
Douglas Gregor523d46a2010-04-18 07:40:54 +00003869/// the type of the initializer expression or a superclass thereof.
3870///
3871/// \param Enter The entity being initialized.
3872///
3873/// \param CurInit The initializer expression.
3874///
3875/// \param IsExtraneousCopy Whether this is an "extraneous" copy that
3876/// is permitted in C++03 (but not C++0x) when binding a reference to
3877/// an rvalue.
3878///
3879/// \returns An expression that copies the initializer expression into
3880/// a temporary object, or an error expression if a copy could not be
3881/// created.
John McCall60d7b3a2010-08-24 06:29:42 +00003882static ExprResult CopyObject(Sema &S,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003883 QualType T,
3884 const InitializedEntity &Entity,
3885 ExprResult CurInit,
3886 bool IsExtraneousCopy) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003887 // Determine which class type we're copying to.
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003888 Expr *CurInitExpr = (Expr *)CurInit.get();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003889 CXXRecordDecl *Class = 0;
Douglas Gregor523d46a2010-04-18 07:40:54 +00003890 if (const RecordType *Record = T->getAs<RecordType>())
Douglas Gregor2f599792010-04-02 18:24:57 +00003891 Class = cast<CXXRecordDecl>(Record->getDecl());
3892 if (!Class)
3893 return move(CurInit);
3894
Douglas Gregorf5d8f462011-01-21 18:05:27 +00003895 // C++0x [class.copy]p32:
Douglas Gregor2f599792010-04-02 18:24:57 +00003896 // When certain criteria are met, an implementation is allowed to
3897 // omit the copy/move construction of a class object, even if the
3898 // copy/move constructor and/or destructor for the object have
3899 // side effects. [...]
3900 // - when a temporary class object that has not been bound to a
3901 // reference (12.2) would be copied/moved to a class object
3902 // with the same cv-unqualified type, the copy/move operation
3903 // can be omitted by constructing the temporary object
3904 // directly into the target of the omitted copy/move
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003905 //
Douglas Gregor2f599792010-04-02 18:24:57 +00003906 // Note that the other three bullets are handled elsewhere. Copy
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003907 // elision for return statements and throw expressions are handled as part
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003908 // of constructor initialization, while copy elision for exception handlers
Douglas Gregor3c9034c2010-05-15 00:13:29 +00003909 // is handled by the run-time.
John McCall558d2ab2010-09-15 10:14:12 +00003910 bool Elidable = CurInitExpr->isTemporaryObject(S.Context, Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003911 SourceLocation Loc;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003912 switch (Entity.getKind()) {
3913 case InitializedEntity::EK_Result:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003914 Loc = Entity.getReturnLoc();
3915 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003916
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003917 case InitializedEntity::EK_Exception:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003918 Loc = Entity.getThrowLoc();
3919 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003920
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003921 case InitializedEntity::EK_Variable:
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003922 Loc = Entity.getDecl()->getLocation();
3923 break;
3924
Anders Carlsson1b36a2f2010-01-24 00:19:41 +00003925 case InitializedEntity::EK_ArrayElement:
3926 case InitializedEntity::EK_Member:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003927 case InitializedEntity::EK_Parameter:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003928 case InitializedEntity::EK_Temporary:
Douglas Gregor2f599792010-04-02 18:24:57 +00003929 case InitializedEntity::EK_New:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003930 case InitializedEntity::EK_Base:
Sean Hunt059ce0d2011-05-01 07:04:31 +00003931 case InitializedEntity::EK_Delegating:
Anders Carlssond3d824d2010-01-23 04:34:47 +00003932 case InitializedEntity::EK_VectorElement:
Fariborz Jahanian310b1c42010-06-07 16:14:00 +00003933 case InitializedEntity::EK_BlockElement:
Douglas Gregor2f599792010-04-02 18:24:57 +00003934 Loc = CurInitExpr->getLocStart();
3935 break;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003936 }
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003937
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003938 // Make sure that the type we are copying is complete.
Douglas Gregorf86fcb32010-04-24 21:09:25 +00003939 if (S.RequireCompleteType(Loc, T, S.PDiag(diag::err_temp_copy_incomplete)))
3940 return move(CurInit);
3941
Douglas Gregorcc15f012011-01-21 19:38:21 +00003942 // Perform overload resolution using the class's copy/move constructors.
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003943 DeclContext::lookup_iterator Con, ConEnd;
John McCall5769d612010-02-08 23:07:23 +00003944 OverloadCandidateSet CandidateSet(Loc);
Douglas Gregore5eee5a2010-07-02 23:12:18 +00003945 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(Class);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003946 Con != ConEnd; ++Con) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003947 // Only consider copy/move constructors and constructor templates. Per
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003948 // C++0x [dcl.init]p16, second bullet to class types, this
3949 // initialization is direct-initialization.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003950 CXXConstructorDecl *Constructor = 0;
3951
3952 if ((Constructor = dyn_cast<CXXConstructorDecl>(*Con))) {
Douglas Gregorcc15f012011-01-21 19:38:21 +00003953 // Handle copy/moveconstructors, only.
Douglas Gregor6493cc52010-11-08 17:16:59 +00003954 if (!Constructor || Constructor->isInvalidDecl() ||
Douglas Gregorcc15f012011-01-21 19:38:21 +00003955 !Constructor->isCopyOrMoveConstructor() ||
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003956 !Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003957 continue;
3958
3959 DeclAccessPair FoundDecl
3960 = DeclAccessPair::make(Constructor, Constructor->getAccess());
3961 S.AddOverloadCandidate(Constructor, FoundDecl,
3962 &CurInitExpr, 1, CandidateSet);
3963 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003964 }
Douglas Gregor6493cc52010-11-08 17:16:59 +00003965
3966 // Handle constructor templates.
3967 FunctionTemplateDecl *ConstructorTmpl = cast<FunctionTemplateDecl>(*Con);
3968 if (ConstructorTmpl->isInvalidDecl())
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003969 continue;
John McCall9aa472c2010-03-19 07:35:19 +00003970
Douglas Gregor6493cc52010-11-08 17:16:59 +00003971 Constructor = cast<CXXConstructorDecl>(
3972 ConstructorTmpl->getTemplatedDecl());
Douglas Gregor8ff338b2010-11-12 03:34:06 +00003973 if (!Constructor->isConvertingConstructor(/*AllowExplicit=*/true))
Douglas Gregor6493cc52010-11-08 17:16:59 +00003974 continue;
3975
3976 // FIXME: Do we need to limit this to copy-constructor-like
3977 // candidates?
John McCall9aa472c2010-03-19 07:35:19 +00003978 DeclAccessPair FoundDecl
Douglas Gregor6493cc52010-11-08 17:16:59 +00003979 = DeclAccessPair::make(ConstructorTmpl, ConstructorTmpl->getAccess());
3980 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 0,
3981 &CurInitExpr, 1, CandidateSet, true);
Douglas Gregor2f599792010-04-02 18:24:57 +00003982 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003983
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003984 OverloadCandidateSet::iterator Best;
Chandler Carruth25ca4212011-02-25 19:41:05 +00003985 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003986 case OR_Success:
3987 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003988
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003989 case OR_No_Viable_Function:
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003990 S.Diag(Loc, IsExtraneousCopy && !S.isSFINAEContext()
3991 ? diag::ext_rvalue_to_reference_temp_copy_no_viable
3992 : diag::err_temp_copy_no_viable)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00003993 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00003994 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00003995 CandidateSet.NoteCandidates(S, OCD_AllCandidates, &CurInitExpr, 1);
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003996 if (!IsExtraneousCopy || S.isSFINAEContext())
John McCallf312b1e2010-08-26 23:41:50 +00003997 return ExprError();
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00003998 return move(CurInit);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003999
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004000 case OR_Ambiguous:
4001 S.Diag(Loc, diag::err_temp_copy_ambiguous)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004002 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004003 << CurInitExpr->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004004 CandidateSet.NoteCandidates(S, OCD_ViableCandidates, &CurInitExpr, 1);
John McCallf312b1e2010-08-26 23:41:50 +00004005 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004006
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004007 case OR_Deleted:
4008 S.Diag(Loc, diag::err_temp_copy_deleted)
Douglas Gregor7abfbdb2009-12-19 03:01:41 +00004009 << (int)Entity.getKind() << CurInitExpr->getType()
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004010 << CurInitExpr->getSourceRange();
4011 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004012 << 1 << Best->Function->isDeleted();
John McCallf312b1e2010-08-26 23:41:50 +00004013 return ExprError();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004014 }
4015
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004016 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
John McCallca0408f2010-08-23 06:44:23 +00004017 ASTOwningVector<Expr*> ConstructorArgs(S);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004018 CurInit.release(); // Ownership transferred into MultiExprArg, below.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004019
Anders Carlsson9a68a672010-04-21 18:47:17 +00004020 S.CheckConstructorAccess(Loc, Constructor, Entity,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00004021 Best->FoundDecl.getAccess(), IsExtraneousCopy);
Douglas Gregor523d46a2010-04-18 07:40:54 +00004022
4023 if (IsExtraneousCopy) {
4024 // If this is a totally extraneous copy for C++03 reference
4025 // binding purposes, just return the original initialization
Douglas Gregor2559a702010-04-18 07:57:34 +00004026 // expression. We don't generate an (elided) copy operation here
4027 // because doing so would require us to pass down a flag to avoid
4028 // infinite recursion, where each step adds another extraneous,
4029 // elidable copy.
Douglas Gregor523d46a2010-04-18 07:40:54 +00004030
Douglas Gregor2559a702010-04-18 07:57:34 +00004031 // Instantiate the default arguments of any extra parameters in
4032 // the selected copy constructor, as if we were going to create a
4033 // proper call to the copy constructor.
4034 for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) {
4035 ParmVarDecl *Parm = Constructor->getParamDecl(I);
4036 if (S.RequireCompleteType(Loc, Parm->getType(),
4037 S.PDiag(diag::err_call_incomplete_argument)))
4038 break;
4039
4040 // Build the default argument expression; we don't actually care
4041 // if this succeeds or not, because this routine will complain
4042 // if there was a problem.
4043 S.BuildCXXDefaultArgExpr(Loc, Constructor, Parm);
4044 }
4045
Douglas Gregor523d46a2010-04-18 07:40:54 +00004046 return S.Owned(CurInitExpr);
4047 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004048
Chandler Carruth25ca4212011-02-25 19:41:05 +00004049 S.MarkDeclarationReferenced(Loc, Constructor);
4050
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004051 // Determine the arguments required to actually perform the
Douglas Gregor523d46a2010-04-18 07:40:54 +00004052 // constructor call (we might have derived-to-base conversions, or
4053 // the copy constructor may have default arguments).
John McCallf312b1e2010-08-26 23:41:50 +00004054 if (S.CompleteConstructorCall(Constructor, MultiExprArg(&CurInitExpr, 1),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004055 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004056 return ExprError();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004057
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004058 // Actually perform the constructor call.
4059 CurInit = S.BuildCXXConstructExpr(Loc, T, Constructor, Elidable,
John McCall7a1fad32010-08-24 07:32:53 +00004060 move_arg(ConstructorArgs),
4061 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004062 CXXConstructExpr::CK_Complete,
4063 SourceRange());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004065 // If we're supposed to bind temporaries, do so.
4066 if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity))
4067 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
4068 return move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004069}
Douglas Gregor20093b42009-12-09 23:02:17 +00004070
Douglas Gregora41a8c52010-04-22 00:20:18 +00004071void InitializationSequence::PrintInitLocationNote(Sema &S,
4072 const InitializedEntity &Entity) {
4073 if (Entity.getKind() == InitializedEntity::EK_Parameter && Entity.getDecl()) {
4074 if (Entity.getDecl()->getLocation().isInvalid())
4075 return;
4076
4077 if (Entity.getDecl()->getDeclName())
4078 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_named_here)
4079 << Entity.getDecl()->getDeclName();
4080 else
4081 S.Diag(Entity.getDecl()->getLocation(), diag::note_parameter_here);
4082 }
4083}
4084
Sebastian Redl3b802322011-07-14 19:07:55 +00004085static bool isReferenceBinding(const InitializationSequence::Step &s) {
4086 return s.Kind == InitializationSequence::SK_BindReference ||
4087 s.Kind == InitializationSequence::SK_BindReferenceToTemporary;
4088}
4089
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004090ExprResult
Douglas Gregor20093b42009-12-09 23:02:17 +00004091InitializationSequence::Perform(Sema &S,
4092 const InitializedEntity &Entity,
4093 const InitializationKind &Kind,
John McCallf312b1e2010-08-26 23:41:50 +00004094 MultiExprArg Args,
Douglas Gregord87b61f2009-12-10 17:56:55 +00004095 QualType *ResultType) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004096 if (Failed()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004097 unsigned NumArgs = Args.size();
4098 Diagnose(S, Entity, Kind, (Expr **)Args.release(), NumArgs);
John McCallf312b1e2010-08-26 23:41:50 +00004099 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004100 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004101
Sebastian Redl7491c492011-06-05 13:59:11 +00004102 if (getKind() == DependentSequence) {
Douglas Gregord87b61f2009-12-10 17:56:55 +00004103 // If the declaration is a non-dependent, incomplete array type
4104 // that has an initializer, then its type will be completed once
4105 // the initializer is instantiated.
Douglas Gregord6542d82009-12-22 15:35:07 +00004106 if (ResultType && !Entity.getType()->isDependentType() &&
Douglas Gregord87b61f2009-12-10 17:56:55 +00004107 Args.size() == 1) {
Douglas Gregord6542d82009-12-22 15:35:07 +00004108 QualType DeclType = Entity.getType();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004109 if (const IncompleteArrayType *ArrayT
4110 = S.Context.getAsIncompleteArrayType(DeclType)) {
4111 // FIXME: We don't currently have the ability to accurately
4112 // compute the length of an initializer list without
4113 // performing full type-checking of the initializer list
4114 // (since we have to determine where braces are implicitly
4115 // introduced and such). So, we fall back to making the array
4116 // type a dependently-sized array type with no specified
4117 // bound.
4118 if (isa<InitListExpr>((Expr *)Args.get()[0])) {
4119 SourceRange Brackets;
Douglas Gregord6542d82009-12-22 15:35:07 +00004120
Douglas Gregord87b61f2009-12-10 17:56:55 +00004121 // Scavange the location of the brackets from the entity, if we can.
Douglas Gregord6542d82009-12-22 15:35:07 +00004122 if (DeclaratorDecl *DD = Entity.getDecl()) {
4123 if (TypeSourceInfo *TInfo = DD->getTypeSourceInfo()) {
4124 TypeLoc TL = TInfo->getTypeLoc();
4125 if (IncompleteArrayTypeLoc *ArrayLoc
4126 = dyn_cast<IncompleteArrayTypeLoc>(&TL))
4127 Brackets = ArrayLoc->getBracketsRange();
4128 }
Douglas Gregord87b61f2009-12-10 17:56:55 +00004129 }
4130
4131 *ResultType
4132 = S.Context.getDependentSizedArrayType(ArrayT->getElementType(),
4133 /*NumElts=*/0,
4134 ArrayT->getSizeModifier(),
4135 ArrayT->getIndexTypeCVRQualifiers(),
4136 Brackets);
4137 }
4138
4139 }
4140 }
Manuel Klimek0d9106f2011-06-22 20:02:16 +00004141 assert(Kind.getKind() == InitializationKind::IK_Copy ||
4142 Kind.isExplicitCast());
4143 return ExprResult(Args.release()[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004144 }
4145
Sebastian Redl7491c492011-06-05 13:59:11 +00004146 // No steps means no initialization.
4147 if (Steps.empty())
Douglas Gregor99a2e602009-12-16 01:38:02 +00004148 return S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004149
Douglas Gregord6542d82009-12-22 15:35:07 +00004150 QualType DestType = Entity.getType().getNonReferenceType();
4151 // FIXME: Ugly hack around the fact that Entity.getType() is not
Eli Friedmana91eb542009-12-22 02:10:53 +00004152 // the same as Entity.getDecl()->getType() in cases involving type merging,
4153 // and we want latter when it makes sense.
Douglas Gregord87b61f2009-12-10 17:56:55 +00004154 if (ResultType)
Eli Friedmana91eb542009-12-22 02:10:53 +00004155 *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() :
Douglas Gregord6542d82009-12-22 15:35:07 +00004156 Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004157
John McCall60d7b3a2010-08-24 06:29:42 +00004158 ExprResult CurInit = S.Owned((Expr *)0);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004159
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004160 // For initialization steps that start with a single initializer,
Douglas Gregor99a2e602009-12-16 01:38:02 +00004161 // grab the only argument out the Args and place it into the "current"
4162 // initializer.
4163 switch (Steps.front().Kind) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004164 case SK_ResolveAddressOfOverloadedFunction:
4165 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004166 case SK_CastDerivedToBaseXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004167 case SK_CastDerivedToBaseLValue:
4168 case SK_BindReference:
4169 case SK_BindReferenceToTemporary:
Douglas Gregor523d46a2010-04-18 07:40:54 +00004170 case SK_ExtraneousCopyToTemporary:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004171 case SK_UserConversion:
4172 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004173 case SK_QualificationConversionXValue:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004174 case SK_QualificationConversionRValue:
4175 case SK_ConversionSequence:
4176 case SK_ListInitialization:
4177 case SK_CAssignment:
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004178 case SK_StringInit:
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004179 case SK_ObjCObjectConversion:
John McCallf85e1932011-06-15 23:02:42 +00004180 case SK_ArrayInit:
4181 case SK_PassByIndirectCopyRestore:
4182 case SK_PassByIndirectRestore:
4183 case SK_ProduceObjCObject: {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004184 assert(Args.size() == 1);
John Wiegley429bb272011-04-08 18:41:53 +00004185 CurInit = Args.get()[0];
4186 if (!CurInit.get()) return ExprError();
John McCallf6a16482010-12-04 03:47:34 +00004187
4188 // Read from a property when initializing something with it.
John Wiegley429bb272011-04-08 18:41:53 +00004189 if (CurInit.get()->getObjectKind() == OK_ObjCProperty) {
4190 CurInit = S.ConvertPropertyForRValue(CurInit.take());
4191 if (CurInit.isInvalid())
4192 return ExprError();
4193 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004194 break;
John McCallf6a16482010-12-04 03:47:34 +00004195 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004196
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004197 case SK_ConstructorInitialization:
4198 case SK_ZeroInitialization:
4199 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004201
4202 // Walk through the computed steps for the initialization sequence,
Douglas Gregor20093b42009-12-09 23:02:17 +00004203 // performing the specified conversions along the way.
Douglas Gregor16006c92009-12-16 18:50:27 +00004204 bool ConstructorInitRequiresZeroInit = false;
Douglas Gregor20093b42009-12-09 23:02:17 +00004205 for (step_iterator Step = step_begin(), StepEnd = step_end();
4206 Step != StepEnd; ++Step) {
4207 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004208 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004209
John Wiegley429bb272011-04-08 18:41:53 +00004210 QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004211
Douglas Gregor20093b42009-12-09 23:02:17 +00004212 switch (Step->Kind) {
4213 case SK_ResolveAddressOfOverloadedFunction:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004214 // Overload resolution determined which function invoke; update the
Douglas Gregor20093b42009-12-09 23:02:17 +00004215 // initializer to reflect that choice.
John Wiegley429bb272011-04-08 18:41:53 +00004216 S.CheckAddressOfMemberAccess(CurInit.get(), Step->Function.FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00004217 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Kind.getLocation());
John McCallb13b7372010-02-01 03:16:54 +00004218 CurInit = S.FixOverloadedFunctionReference(move(CurInit),
John McCall6bb80172010-03-30 21:47:33 +00004219 Step->Function.FoundDecl,
John McCall9aa472c2010-03-19 07:35:19 +00004220 Step->Function.Function);
Douglas Gregor20093b42009-12-09 23:02:17 +00004221 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004222
Douglas Gregor20093b42009-12-09 23:02:17 +00004223 case SK_CastDerivedToBaseRValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004224 case SK_CastDerivedToBaseXValue:
Douglas Gregor20093b42009-12-09 23:02:17 +00004225 case SK_CastDerivedToBaseLValue: {
4226 // We have a derived-to-base cast that produces either an rvalue or an
4227 // lvalue. Perform that cast.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004228
John McCallf871d0c2010-08-07 06:22:56 +00004229 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004230
Douglas Gregor20093b42009-12-09 23:02:17 +00004231 // Casts to inaccessible base classes are allowed with C-style casts.
4232 bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast();
4233 if (S.CheckDerivedToBaseConversion(SourceType, Step->Type,
John Wiegley429bb272011-04-08 18:41:53 +00004234 CurInit.get()->getLocStart(),
4235 CurInit.get()->getSourceRange(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00004236 &BasePath, IgnoreBaseAccess))
John McCallf312b1e2010-08-26 23:41:50 +00004237 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004238
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004239 if (S.BasePathInvolvesVirtualBase(BasePath)) {
4240 QualType T = SourceType;
4241 if (const PointerType *Pointer = T->getAs<PointerType>())
4242 T = Pointer->getPointeeType();
4243 if (const RecordType *RecordTy = T->getAs<RecordType>())
John Wiegley429bb272011-04-08 18:41:53 +00004244 S.MarkVTableUsed(CurInit.get()->getLocStart(),
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004245 cast<CXXRecordDecl>(RecordTy->getDecl()));
4246 }
4247
John McCall5baba9d2010-08-25 10:28:54 +00004248 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004249 Step->Kind == SK_CastDerivedToBaseLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004250 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004251 (Step->Kind == SK_CastDerivedToBaseXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004252 VK_XValue :
4253 VK_RValue);
John McCallf871d0c2010-08-07 06:22:56 +00004254 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
4255 Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004256 CK_DerivedToBase,
John McCall5baba9d2010-08-25 10:28:54 +00004257 CurInit.get(),
4258 &BasePath, VK));
Douglas Gregor20093b42009-12-09 23:02:17 +00004259 break;
4260 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004261
Douglas Gregor20093b42009-12-09 23:02:17 +00004262 case SK_BindReference:
John Wiegley429bb272011-04-08 18:41:53 +00004263 if (FieldDecl *BitField = CurInit.get()->getBitField()) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004264 // References cannot bind to bit fields (C++ [dcl.init.ref]p5).
4265 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_bitfield)
Douglas Gregord6542d82009-12-22 15:35:07 +00004266 << Entity.getType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004267 << BitField->getDeclName()
John Wiegley429bb272011-04-08 18:41:53 +00004268 << CurInit.get()->getSourceRange();
Douglas Gregor20093b42009-12-09 23:02:17 +00004269 S.Diag(BitField->getLocation(), diag::note_bitfield_decl);
John McCallf312b1e2010-08-26 23:41:50 +00004270 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004271 }
Anders Carlssona6fe0bf2010-01-29 02:47:33 +00004272
John Wiegley429bb272011-04-08 18:41:53 +00004273 if (CurInit.get()->refersToVectorElement()) {
John McCall41593e32010-02-02 19:02:38 +00004274 // References cannot bind to vector elements.
Anders Carlsson09380262010-01-31 17:18:49 +00004275 S.Diag(Kind.getLocation(), diag::err_reference_bind_to_vector_element)
4276 << Entity.getType().isVolatileQualified()
John Wiegley429bb272011-04-08 18:41:53 +00004277 << CurInit.get()->getSourceRange();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004278 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004279 return ExprError();
Anders Carlsson09380262010-01-31 17:18:49 +00004280 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004281
Douglas Gregor20093b42009-12-09 23:02:17 +00004282 // Reference binding does not have any corresponding ASTs.
4283
4284 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004285 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004286 return ExprError();
Anders Carlsson3aba0932010-01-31 18:34:51 +00004287
Douglas Gregor20093b42009-12-09 23:02:17 +00004288 break;
Anders Carlsson3aba0932010-01-31 18:34:51 +00004289
Douglas Gregor20093b42009-12-09 23:02:17 +00004290 case SK_BindReferenceToTemporary:
4291 // Check exception specifications
John Wiegley429bb272011-04-08 18:41:53 +00004292 if (S.CheckExceptionSpecCompatibility(CurInit.get(), DestType))
John McCallf312b1e2010-08-26 23:41:50 +00004293 return ExprError();
Douglas Gregor20093b42009-12-09 23:02:17 +00004294
Douglas Gregor03e80032011-06-21 17:03:29 +00004295 // Materialize the temporary into memory.
Douglas Gregorb4b7b502011-06-22 15:05:02 +00004296 CurInit = new (S.Context) MaterializeTemporaryExpr(
4297 Entity.getType().getNonReferenceType(),
4298 CurInit.get(),
Douglas Gregor03e80032011-06-21 17:03:29 +00004299 Entity.getType()->isLValueReferenceType());
Douglas Gregord7b23162011-06-22 16:12:01 +00004300
4301 // If we're binding to an Objective-C object that has lifetime, we
4302 // need cleanups.
4303 if (S.getLangOptions().ObjCAutoRefCount &&
4304 CurInit.get()->getType()->isObjCLifetimeType())
4305 S.ExprNeedsCleanups = true;
4306
Douglas Gregor20093b42009-12-09 23:02:17 +00004307 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004308
Douglas Gregor523d46a2010-04-18 07:40:54 +00004309 case SK_ExtraneousCopyToTemporary:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004310 CurInit = CopyObject(S, Step->Type, Entity, move(CurInit),
Douglas Gregor523d46a2010-04-18 07:40:54 +00004311 /*IsExtraneousCopy=*/true);
4312 break;
4313
Douglas Gregor20093b42009-12-09 23:02:17 +00004314 case SK_UserConversion: {
4315 // We have a user-defined conversion that invokes either a constructor
4316 // or a conversion function.
John McCalldaa8e4e2010-11-15 09:13:47 +00004317 CastKind CastKind;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004318 bool IsCopy = false;
John McCall9aa472c2010-03-19 07:35:19 +00004319 FunctionDecl *Fn = Step->Function.Function;
4320 DeclAccessPair FoundFn = Step->Function.FoundDecl;
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004321 bool CreatedObject = false;
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004322 bool IsLvalue = false;
John McCallb13b7372010-02-01 03:16:54 +00004323 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Fn)) {
Douglas Gregor20093b42009-12-09 23:02:17 +00004324 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004325 ASTOwningVector<Expr*> ConstructorArgs(S);
John Wiegley429bb272011-04-08 18:41:53 +00004326 SourceLocation Loc = CurInit.get()->getLocStart();
Douglas Gregor20093b42009-12-09 23:02:17 +00004327 CurInit.release(); // Ownership transferred into MultiExprArg, below.
John McCallb13b7372010-02-01 03:16:54 +00004328
Douglas Gregor20093b42009-12-09 23:02:17 +00004329 // Determine the arguments required to actually perform the constructor
4330 // call.
John Wiegley429bb272011-04-08 18:41:53 +00004331 Expr *Arg = CurInit.get();
Douglas Gregor20093b42009-12-09 23:02:17 +00004332 if (S.CompleteConstructorCall(Constructor,
John Wiegley429bb272011-04-08 18:41:53 +00004333 MultiExprArg(&Arg, 1),
Douglas Gregor20093b42009-12-09 23:02:17 +00004334 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004335 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004336
Douglas Gregor20093b42009-12-09 23:02:17 +00004337 // Build the an expression that constructs a temporary.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004338 CurInit = S.BuildCXXConstructExpr(Loc, Step->Type, Constructor,
John McCall7a1fad32010-08-24 07:32:53 +00004339 move_arg(ConstructorArgs),
4340 /*ZeroInit*/ false,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004341 CXXConstructExpr::CK_Complete,
4342 SourceRange());
Douglas Gregor20093b42009-12-09 23:02:17 +00004343 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004344 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004345
Anders Carlsson9a68a672010-04-21 18:47:17 +00004346 S.CheckConstructorAccess(Kind.getLocation(), Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004347 FoundFn.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004348 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004349
John McCall2de56d12010-08-25 11:45:40 +00004350 CastKind = CK_ConstructorConversion;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004351 QualType Class = S.Context.getTypeDeclType(Constructor->getParent());
4352 if (S.Context.hasSameUnqualifiedType(SourceType, Class) ||
4353 S.IsDerivedFrom(SourceType, Class))
4354 IsCopy = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004355
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004356 CreatedObject = true;
Douglas Gregor20093b42009-12-09 23:02:17 +00004357 } else {
4358 // Build a call to the conversion function.
John McCallb13b7372010-02-01 03:16:54 +00004359 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Fn);
Douglas Gregorf0e0b172010-03-25 00:20:38 +00004360 IsLvalue = Conversion->getResultType()->isLValueReferenceType();
John Wiegley429bb272011-04-08 18:41:53 +00004361 S.CheckMemberOperatorAccess(Kind.getLocation(), CurInit.get(), 0,
John McCall9aa472c2010-03-19 07:35:19 +00004362 FoundFn);
John McCallb697e082010-05-06 18:15:07 +00004363 S.DiagnoseUseOfDecl(FoundFn, Kind.getLocation());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004364
4365 // FIXME: Should we move this initialization into a separate
Douglas Gregor20093b42009-12-09 23:02:17 +00004366 // derived-to-base conversion? I believe the answer is "no", because
4367 // we don't want to turn off access control here for c-style casts.
John Wiegley429bb272011-04-08 18:41:53 +00004368 ExprResult CurInitExprRes =
4369 S.PerformObjectArgumentInitialization(CurInit.take(), /*Qualifier=*/0,
4370 FoundFn, Conversion);
4371 if(CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004372 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004373 CurInit = move(CurInitExprRes);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004374
Douglas Gregor20093b42009-12-09 23:02:17 +00004375 // Build the actual call to the conversion function.
John Wiegley429bb272011-04-08 18:41:53 +00004376 CurInit = S.BuildCXXMemberCallExpr(CurInit.get(), FoundFn, Conversion);
Douglas Gregor20093b42009-12-09 23:02:17 +00004377 if (CurInit.isInvalid() || !CurInit.get())
John McCallf312b1e2010-08-26 23:41:50 +00004378 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004379
John McCall2de56d12010-08-25 11:45:40 +00004380 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004381
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004382 CreatedObject = Conversion->getResultType()->isRecordType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004383 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004384
Sebastian Redl3b802322011-07-14 19:07:55 +00004385 bool RequiresCopy = !IsCopy && !isReferenceBinding(Steps.back());
Douglas Gregor2f599792010-04-02 18:24:57 +00004386 if (RequiresCopy || shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004387 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004388 else if (CreatedObject && shouldDestroyTemporary(Entity)) {
John Wiegley429bb272011-04-08 18:41:53 +00004389 QualType T = CurInit.get()->getType();
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004390 if (const RecordType *Record = T->getAs<RecordType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004391 CXXDestructorDecl *Destructor
Douglas Gregordb89f282010-07-01 22:47:18 +00004392 = S.LookupDestructor(cast<CXXRecordDecl>(Record->getDecl()));
John Wiegley429bb272011-04-08 18:41:53 +00004393 S.CheckDestructorAccess(CurInit.get()->getLocStart(), Destructor,
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004394 S.PDiag(diag::err_access_dtor_temp) << T);
John Wiegley429bb272011-04-08 18:41:53 +00004395 S.MarkDeclarationReferenced(CurInit.get()->getLocStart(), Destructor);
4396 S.DiagnoseUseOfDecl(Destructor, CurInit.get()->getLocStart());
Douglas Gregor4154e0b2010-04-24 23:45:46 +00004397 }
4398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004399
Sebastian Redl906082e2010-07-20 04:20:21 +00004400 // FIXME: xvalues
John McCallf871d0c2010-08-07 06:22:56 +00004401 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context,
John Wiegley429bb272011-04-08 18:41:53 +00004402 CurInit.get()->getType(),
4403 CastKind, CurInit.get(), 0,
John McCall5baba9d2010-08-25 10:28:54 +00004404 IsLvalue ? VK_LValue : VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004405
Douglas Gregor2f599792010-04-02 18:24:57 +00004406 if (RequiresCopy)
Douglas Gregor523d46a2010-04-18 07:40:54 +00004407 CurInit = CopyObject(S, Entity.getType().getNonReferenceType(), Entity,
4408 move(CurInit), /*IsExtraneousCopy=*/false);
Sebastian Redl906082e2010-07-20 04:20:21 +00004409
Douglas Gregor20093b42009-12-09 23:02:17 +00004410 break;
4411 }
Sebastian Redl906082e2010-07-20 04:20:21 +00004412
Douglas Gregor20093b42009-12-09 23:02:17 +00004413 case SK_QualificationConversionLValue:
Sebastian Redl906082e2010-07-20 04:20:21 +00004414 case SK_QualificationConversionXValue:
4415 case SK_QualificationConversionRValue: {
Douglas Gregor20093b42009-12-09 23:02:17 +00004416 // Perform a qualification conversion; these can never go wrong.
John McCall5baba9d2010-08-25 10:28:54 +00004417 ExprValueKind VK =
Sebastian Redl906082e2010-07-20 04:20:21 +00004418 Step->Kind == SK_QualificationConversionLValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004419 VK_LValue :
Sebastian Redl906082e2010-07-20 04:20:21 +00004420 (Step->Kind == SK_QualificationConversionXValue ?
John McCall5baba9d2010-08-25 10:28:54 +00004421 VK_XValue :
4422 VK_RValue);
John Wiegley429bb272011-04-08 18:41:53 +00004423 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type, CK_NoOp, VK);
Douglas Gregor20093b42009-12-09 23:02:17 +00004424 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00004425 }
4426
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004427 case SK_ConversionSequence: {
John McCallf85e1932011-06-15 23:02:42 +00004428 Sema::CheckedConversionKind CCK
4429 = Kind.isCStyleCast()? Sema::CCK_CStyleCast
4430 : Kind.isFunctionalCast()? Sema::CCK_FunctionalCast
4431 : Kind.isExplicitCast()? Sema::CCK_OtherCast
4432 : Sema::CCK_ImplicitConversion;
John Wiegley429bb272011-04-08 18:41:53 +00004433 ExprResult CurInitExprRes =
4434 S.PerformImplicitConversion(CurInit.get(), Step->Type, *Step->ICS,
John McCallf85e1932011-06-15 23:02:42 +00004435 getAssignmentAction(Entity), CCK);
John Wiegley429bb272011-04-08 18:41:53 +00004436 if (CurInitExprRes.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004437 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00004438 CurInit = move(CurInitExprRes);
Douglas Gregor20093b42009-12-09 23:02:17 +00004439 break;
Douglas Gregorf0e43e52010-04-16 19:30:02 +00004440 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004441
Douglas Gregord87b61f2009-12-10 17:56:55 +00004442 case SK_ListInitialization: {
John Wiegley429bb272011-04-08 18:41:53 +00004443 InitListExpr *InitList = cast<InitListExpr>(CurInit.get());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004444 QualType Ty = Step->Type;
Douglas Gregorcb57fb92009-12-16 06:35:08 +00004445 if (S.CheckInitList(Entity, InitList, ResultType? *ResultType : Ty))
John McCallf312b1e2010-08-26 23:41:50 +00004446 return ExprError();
Douglas Gregord87b61f2009-12-10 17:56:55 +00004447
4448 CurInit.release();
4449 CurInit = S.Owned(InitList);
4450 break;
4451 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004452
4453 case SK_ConstructorInitialization: {
Douglas Gregord6e44a32010-04-16 22:09:46 +00004454 unsigned NumArgs = Args.size();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004455 CXXConstructorDecl *Constructor
John McCall9aa472c2010-03-19 07:35:19 +00004456 = cast<CXXConstructorDecl>(Step->Function.Function);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004457
Douglas Gregor51c56d62009-12-14 20:49:26 +00004458 // Build a call to the selected constructor.
John McCallca0408f2010-08-23 06:44:23 +00004459 ASTOwningVector<Expr*> ConstructorArgs(S);
Fariborz Jahanian0a2eb562010-07-21 18:40:47 +00004460 SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid())
4461 ? Kind.getEqualLoc()
4462 : Kind.getLocation();
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004463
4464 if (Kind.getKind() == InitializationKind::IK_Default) {
4465 // Force even a trivial, implicit default constructor to be
4466 // semantically checked. We do this explicitly because we don't build
4467 // the definition for completely trivial constructors.
4468 CXXRecordDecl *ClassDecl = Constructor->getParent();
4469 assert(ClassDecl && "No parent class for constructor.");
Sean Hunt1e238652011-05-12 03:51:51 +00004470 if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +00004471 ClassDecl->hasTrivialDefaultConstructor() &&
4472 !Constructor->isUsed(false))
Chandler Carruth4e6fbce2010-08-23 07:55:51 +00004473 S.DefineImplicitDefaultConstructor(Loc, Constructor);
4474 }
4475
Douglas Gregor51c56d62009-12-14 20:49:26 +00004476 // Determine the arguments required to actually perform the constructor
4477 // call.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004478 if (S.CompleteConstructorCall(Constructor, move(Args),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004479 Loc, ConstructorArgs))
John McCallf312b1e2010-08-26 23:41:50 +00004480 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004481
4482
Douglas Gregor91be6f52010-03-02 17:18:33 +00004483 if (Entity.getKind() == InitializedEntity::EK_Temporary &&
Douglas Gregord6e44a32010-04-16 22:09:46 +00004484 NumArgs != 1 && // FIXME: Hack to work around cast weirdness
Douglas Gregor91be6f52010-03-02 17:18:33 +00004485 (Kind.getKind() == InitializationKind::IK_Direct ||
4486 Kind.getKind() == InitializationKind::IK_Value)) {
4487 // An explicitly-constructed temporary, e.g., X(1, 2).
4488 unsigned NumExprs = ConstructorArgs.size();
4489 Expr **Exprs = (Expr **)ConstructorArgs.take();
Fariborz Jahanian10f8e312010-07-21 18:31:47 +00004490 S.MarkDeclarationReferenced(Loc, Constructor);
Douglas Gregor9b623632010-10-12 23:32:35 +00004491 S.DiagnoseUseOfDecl(Constructor, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492
Douglas Gregorab6677e2010-09-08 00:15:04 +00004493 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4494 if (!TSInfo)
4495 TSInfo = S.Context.getTrivialTypeSourceInfo(Entity.getType(), Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004496
Douglas Gregor91be6f52010-03-02 17:18:33 +00004497 CurInit = S.Owned(new (S.Context) CXXTemporaryObjectExpr(S.Context,
4498 Constructor,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004499 TSInfo,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500 Exprs,
Douglas Gregor91be6f52010-03-02 17:18:33 +00004501 NumExprs,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004502 Kind.getParenRange(),
Douglas Gregor1c63b9c2010-04-27 20:36:09 +00004503 ConstructorInitRequiresZeroInit));
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004504 } else {
4505 CXXConstructExpr::ConstructionKind ConstructKind =
4506 CXXConstructExpr::CK_Complete;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004507
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004508 if (Entity.getKind() == InitializedEntity::EK_Base) {
4509 ConstructKind = Entity.getBaseSpecifier()->isVirtual() ?
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510 CXXConstructExpr::CK_VirtualBase :
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004511 CXXConstructExpr::CK_NonVirtualBase;
Sean Huntd49bd552011-05-03 20:19:28 +00004512 } else if (Entity.getKind() == InitializedEntity::EK_Delegating) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00004513 ConstructKind = CXXConstructExpr::CK_Delegating;
4514 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004515
Chandler Carruth428edaf2010-10-25 08:47:36 +00004516 // Only get the parenthesis range if it is a direct construction.
4517 SourceRange parenRange =
4518 Kind.getKind() == InitializationKind::IK_Direct ?
4519 Kind.getParenRange() : SourceRange();
4520
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004521 // If the entity allows NRVO, mark the construction as elidable
4522 // unconditionally.
4523 if (Entity.allowsNRVO())
4524 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
4525 Constructor, /*Elidable=*/true,
4526 move_arg(ConstructorArgs),
4527 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004528 ConstructKind,
4529 parenRange);
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004530 else
4531 CurInit = S.BuildCXXConstructExpr(Loc, Entity.getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004532 Constructor,
Douglas Gregor3c9034c2010-05-15 00:13:29 +00004533 move_arg(ConstructorArgs),
4534 ConstructorInitRequiresZeroInit,
Chandler Carruth428edaf2010-10-25 08:47:36 +00004535 ConstructKind,
4536 parenRange);
Anders Carlsson72e96fd2010-05-02 22:54:08 +00004537 }
Douglas Gregor51c56d62009-12-14 20:49:26 +00004538 if (CurInit.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00004539 return ExprError();
John McCallb13b7372010-02-01 03:16:54 +00004540
4541 // Only check access if all of that succeeded.
Anders Carlsson9a68a672010-04-21 18:47:17 +00004542 S.CheckConstructorAccess(Loc, Constructor, Entity,
John McCall9aa472c2010-03-19 07:35:19 +00004543 Step->Function.FoundDecl.getAccess());
John McCallb697e082010-05-06 18:15:07 +00004544 S.DiagnoseUseOfDecl(Step->Function.FoundDecl, Loc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004545
Douglas Gregor2f599792010-04-02 18:24:57 +00004546 if (shouldBindAsTemporary(Entity))
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004547 CurInit = S.MaybeBindToTemporary(CurInit.takeAs<Expr>());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004548
Douglas Gregor51c56d62009-12-14 20:49:26 +00004549 break;
4550 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004551
Douglas Gregor71d17402009-12-15 00:01:57 +00004552 case SK_ZeroInitialization: {
Douglas Gregor16006c92009-12-16 18:50:27 +00004553 step_iterator NextStep = Step;
4554 ++NextStep;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004555 if (NextStep != StepEnd &&
Douglas Gregor16006c92009-12-16 18:50:27 +00004556 NextStep->Kind == SK_ConstructorInitialization) {
4557 // The need for zero-initialization is recorded directly into
4558 // the call to the object's constructor within the next step.
4559 ConstructorInitRequiresZeroInit = true;
4560 } else if (Kind.getKind() == InitializationKind::IK_Value &&
4561 S.getLangOptions().CPlusPlus &&
4562 !Kind.isImplicitValueInit()) {
Douglas Gregorab6677e2010-09-08 00:15:04 +00004563 TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo();
4564 if (!TSInfo)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004565 TSInfo = S.Context.getTrivialTypeSourceInfo(Step->Type,
Douglas Gregorab6677e2010-09-08 00:15:04 +00004566 Kind.getRange().getBegin());
4567
4568 CurInit = S.Owned(new (S.Context) CXXScalarValueInitExpr(
4569 TSInfo->getType().getNonLValueExprType(S.Context),
4570 TSInfo,
Douglas Gregor71d17402009-12-15 00:01:57 +00004571 Kind.getRange().getEnd()));
Douglas Gregor16006c92009-12-16 18:50:27 +00004572 } else {
Douglas Gregor71d17402009-12-15 00:01:57 +00004573 CurInit = S.Owned(new (S.Context) ImplicitValueInitExpr(Step->Type));
Douglas Gregor16006c92009-12-16 18:50:27 +00004574 }
Douglas Gregor71d17402009-12-15 00:01:57 +00004575 break;
4576 }
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004577
4578 case SK_CAssignment: {
John Wiegley429bb272011-04-08 18:41:53 +00004579 QualType SourceType = CurInit.get()->getType();
4580 ExprResult Result = move(CurInit);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004581 Sema::AssignConvertType ConvTy =
John Wiegley429bb272011-04-08 18:41:53 +00004582 S.CheckSingleAssignmentConstraints(Step->Type, Result);
4583 if (Result.isInvalid())
4584 return ExprError();
4585 CurInit = move(Result);
Douglas Gregoraa037312009-12-22 07:24:36 +00004586
4587 // If this is a call, allow conversion to a transparent union.
John Wiegley429bb272011-04-08 18:41:53 +00004588 ExprResult CurInitExprRes = move(CurInit);
Douglas Gregoraa037312009-12-22 07:24:36 +00004589 if (ConvTy != Sema::Compatible &&
4590 Entity.getKind() == InitializedEntity::EK_Parameter &&
John Wiegley429bb272011-04-08 18:41:53 +00004591 S.CheckTransparentUnionArgumentConstraints(Step->Type, CurInitExprRes)
Douglas Gregoraa037312009-12-22 07:24:36 +00004592 == Sema::Compatible)
4593 ConvTy = Sema::Compatible;
John Wiegley429bb272011-04-08 18:41:53 +00004594 if (CurInitExprRes.isInvalid())
4595 return ExprError();
4596 CurInit = move(CurInitExprRes);
Douglas Gregoraa037312009-12-22 07:24:36 +00004597
Douglas Gregora41a8c52010-04-22 00:20:18 +00004598 bool Complained;
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004599 if (S.DiagnoseAssignmentResult(ConvTy, Kind.getLocation(),
4600 Step->Type, SourceType,
John Wiegley429bb272011-04-08 18:41:53 +00004601 CurInit.get(),
Douglas Gregora41a8c52010-04-22 00:20:18 +00004602 getAssignmentAction(Entity),
4603 &Complained)) {
4604 PrintInitLocationNote(S, Entity);
John McCallf312b1e2010-08-26 23:41:50 +00004605 return ExprError();
Douglas Gregora41a8c52010-04-22 00:20:18 +00004606 } else if (Complained)
4607 PrintInitLocationNote(S, Entity);
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004608 break;
4609 }
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004610
4611 case SK_StringInit: {
4612 QualType Ty = Step->Type;
John Wiegley429bb272011-04-08 18:41:53 +00004613 CheckStringInit(CurInit.get(), ResultType ? *ResultType : Ty,
John McCallfef8b342011-02-21 07:57:55 +00004614 S.Context.getAsArrayType(Ty), S);
Eli Friedmancfdc81a2009-12-19 08:11:05 +00004615 break;
4616 }
Douglas Gregor569c3162010-08-07 11:51:51 +00004617
4618 case SK_ObjCObjectConversion:
John Wiegley429bb272011-04-08 18:41:53 +00004619 CurInit = S.ImpCastExprToType(CurInit.take(), Step->Type,
John McCall2de56d12010-08-25 11:45:40 +00004620 CK_ObjCObjectLValueCast,
John Wiegley429bb272011-04-08 18:41:53 +00004621 S.CastCategory(CurInit.get()));
Douglas Gregor569c3162010-08-07 11:51:51 +00004622 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004623
4624 case SK_ArrayInit:
4625 // Okay: we checked everything before creating this step. Note that
4626 // this is a GNU extension.
4627 S.Diag(Kind.getLocation(), diag::ext_array_init_copy)
John Wiegley429bb272011-04-08 18:41:53 +00004628 << Step->Type << CurInit.get()->getType()
4629 << CurInit.get()->getSourceRange();
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004630
4631 // If the destination type is an incomplete array type, update the
4632 // type accordingly.
4633 if (ResultType) {
4634 if (const IncompleteArrayType *IncompleteDest
4635 = S.Context.getAsIncompleteArrayType(Step->Type)) {
4636 if (const ConstantArrayType *ConstantSource
John Wiegley429bb272011-04-08 18:41:53 +00004637 = S.Context.getAsConstantArrayType(CurInit.get()->getType())) {
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004638 *ResultType = S.Context.getConstantArrayType(
4639 IncompleteDest->getElementType(),
4640 ConstantSource->getSize(),
4641 ArrayType::Normal, 0);
4642 }
4643 }
4644 }
John McCallf85e1932011-06-15 23:02:42 +00004645 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004646
John McCallf85e1932011-06-15 23:02:42 +00004647 case SK_PassByIndirectCopyRestore:
4648 case SK_PassByIndirectRestore:
4649 checkIndirectCopyRestoreSource(S, CurInit.get());
4650 CurInit = S.Owned(new (S.Context)
4651 ObjCIndirectCopyRestoreExpr(CurInit.take(), Step->Type,
4652 Step->Kind == SK_PassByIndirectCopyRestore));
4653 break;
4654
4655 case SK_ProduceObjCObject:
4656 CurInit = S.Owned(ImplicitCastExpr::Create(S.Context, Step->Type,
4657 CK_ObjCProduceObject,
4658 CurInit.take(), 0, VK_RValue));
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004659 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004660 }
4661 }
John McCall15d7d122010-11-11 03:21:53 +00004662
4663 // Diagnose non-fatal problems with the completed initialization.
4664 if (Entity.getKind() == InitializedEntity::EK_Member &&
4665 cast<FieldDecl>(Entity.getDecl())->isBitField())
4666 S.CheckBitFieldInitialization(Kind.getLocation(),
4667 cast<FieldDecl>(Entity.getDecl()),
4668 CurInit.get());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004669
Douglas Gregor20093b42009-12-09 23:02:17 +00004670 return move(CurInit);
4671}
4672
4673//===----------------------------------------------------------------------===//
4674// Diagnose initialization failures
4675//===----------------------------------------------------------------------===//
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004676bool InitializationSequence::Diagnose(Sema &S,
Douglas Gregor20093b42009-12-09 23:02:17 +00004677 const InitializedEntity &Entity,
4678 const InitializationKind &Kind,
4679 Expr **Args, unsigned NumArgs) {
Sebastian Redld695d6b2011-06-05 13:59:05 +00004680 if (!Failed())
Douglas Gregor20093b42009-12-09 23:02:17 +00004681 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004682
Douglas Gregord6542d82009-12-22 15:35:07 +00004683 QualType DestType = Entity.getType();
Douglas Gregor20093b42009-12-09 23:02:17 +00004684 switch (Failure) {
4685 case FK_TooManyInitsForReference:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004686 // FIXME: Customize for the initialized entity?
4687 if (NumArgs == 0)
4688 S.Diag(Kind.getLocation(), diag::err_reference_without_init)
4689 << DestType.getNonReferenceType();
4690 else // FIXME: diagnostic below could be better!
4691 S.Diag(Kind.getLocation(), diag::err_reference_has_multiple_inits)
4692 << SourceRange(Args[0]->getLocStart(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregor20093b42009-12-09 23:02:17 +00004693 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004694
Douglas Gregor20093b42009-12-09 23:02:17 +00004695 case FK_ArrayNeedsInitList:
4696 case FK_ArrayNeedsInitListOrStringLiteral:
4697 S.Diag(Kind.getLocation(), diag::err_array_init_not_init_list)
4698 << (Failure == FK_ArrayNeedsInitListOrStringLiteral);
4699 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004700
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004701 case FK_ArrayTypeMismatch:
4702 case FK_NonConstantArrayInit:
4703 S.Diag(Kind.getLocation(),
4704 (Failure == FK_ArrayTypeMismatch
4705 ? diag::err_array_init_different_type
4706 : diag::err_array_init_non_constant_array))
4707 << DestType.getNonReferenceType()
4708 << Args[0]->getType()
4709 << Args[0]->getSourceRange();
4710 break;
4711
John McCall6bb80172010-03-30 21:47:33 +00004712 case FK_AddressOfOverloadFailed: {
4713 DeclAccessPair Found;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004714 S.ResolveAddressOfOverloadedFunction(Args[0],
Douglas Gregor20093b42009-12-09 23:02:17 +00004715 DestType.getNonReferenceType(),
John McCall6bb80172010-03-30 21:47:33 +00004716 true,
4717 Found);
Douglas Gregor20093b42009-12-09 23:02:17 +00004718 break;
John McCall6bb80172010-03-30 21:47:33 +00004719 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004720
Douglas Gregor20093b42009-12-09 23:02:17 +00004721 case FK_ReferenceInitOverloadFailed:
Douglas Gregor4a520a22009-12-14 17:27:33 +00004722 case FK_UserConversionOverloadFailed:
Douglas Gregor20093b42009-12-09 23:02:17 +00004723 switch (FailedOverloadResult) {
4724 case OR_Ambiguous:
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004725 if (Failure == FK_UserConversionOverloadFailed)
4726 S.Diag(Kind.getLocation(), diag::err_typecheck_ambiguous_condition)
4727 << Args[0]->getType() << DestType
4728 << Args[0]->getSourceRange();
4729 else
4730 S.Diag(Kind.getLocation(), diag::err_ref_init_ambiguous)
4731 << DestType << Args[0]->getType()
4732 << Args[0]->getSourceRange();
4733
John McCall120d63c2010-08-24 20:38:10 +00004734 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004735 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004736
Douglas Gregor20093b42009-12-09 23:02:17 +00004737 case OR_No_Viable_Function:
4738 S.Diag(Kind.getLocation(), diag::err_typecheck_nonviable_condition)
4739 << Args[0]->getType() << DestType.getNonReferenceType()
4740 << Args[0]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00004741 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor20093b42009-12-09 23:02:17 +00004742 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004743
Douglas Gregor20093b42009-12-09 23:02:17 +00004744 case OR_Deleted: {
4745 S.Diag(Kind.getLocation(), diag::err_typecheck_deleted_function)
4746 << Args[0]->getType() << DestType.getNonReferenceType()
4747 << Args[0]->getSourceRange();
4748 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004749 OverloadingResult Ovl
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004750 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best,
4751 true);
Douglas Gregor20093b42009-12-09 23:02:17 +00004752 if (Ovl == OR_Deleted) {
4753 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004754 << 1 << Best->Function->isDeleted();
Douglas Gregor20093b42009-12-09 23:02:17 +00004755 } else {
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004756 llvm_unreachable("Inconsistent overload resolution?");
Douglas Gregor20093b42009-12-09 23:02:17 +00004757 }
4758 break;
4759 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004760
Douglas Gregor20093b42009-12-09 23:02:17 +00004761 case OR_Success:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00004762 llvm_unreachable("Conversion did not fail!");
Douglas Gregor20093b42009-12-09 23:02:17 +00004763 break;
4764 }
4765 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004766
Douglas Gregor20093b42009-12-09 23:02:17 +00004767 case FK_NonConstLValueReferenceBindingToTemporary:
4768 case FK_NonConstLValueReferenceBindingToUnrelated:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004769 S.Diag(Kind.getLocation(),
Douglas Gregor20093b42009-12-09 23:02:17 +00004770 Failure == FK_NonConstLValueReferenceBindingToTemporary
4771 ? diag::err_lvalue_reference_bind_to_temporary
4772 : diag::err_lvalue_reference_bind_to_unrelated)
Douglas Gregoref06e242010-01-29 19:39:15 +00004773 << DestType.getNonReferenceType().isVolatileQualified()
Douglas Gregor20093b42009-12-09 23:02:17 +00004774 << DestType.getNonReferenceType()
4775 << Args[0]->getType()
4776 << Args[0]->getSourceRange();
4777 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004778
Douglas Gregor20093b42009-12-09 23:02:17 +00004779 case FK_RValueReferenceBindingToLValue:
4780 S.Diag(Kind.getLocation(), diag::err_lvalue_to_rvalue_ref)
Douglas Gregorfb5d7ef2011-01-21 01:04:33 +00004781 << DestType.getNonReferenceType() << Args[0]->getType()
Douglas Gregor20093b42009-12-09 23:02:17 +00004782 << Args[0]->getSourceRange();
4783 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004784
Douglas Gregor20093b42009-12-09 23:02:17 +00004785 case FK_ReferenceInitDropsQualifiers:
4786 S.Diag(Kind.getLocation(), diag::err_reference_bind_drops_quals)
4787 << DestType.getNonReferenceType()
4788 << Args[0]->getType()
4789 << Args[0]->getSourceRange();
4790 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004791
Douglas Gregor20093b42009-12-09 23:02:17 +00004792 case FK_ReferenceInitFailed:
4793 S.Diag(Kind.getLocation(), diag::err_reference_bind_failed)
4794 << DestType.getNonReferenceType()
John McCall7eb0a9e2010-11-24 05:12:34 +00004795 << Args[0]->isLValue()
Douglas Gregor20093b42009-12-09 23:02:17 +00004796 << Args[0]->getType()
4797 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004798 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4799 Args[0]->getType()->isObjCObjectPointerType())
4800 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregor20093b42009-12-09 23:02:17 +00004801 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004802
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004803 case FK_ConversionFailed: {
4804 QualType FromType = Args[0]->getType();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004805 S.Diag(Kind.getLocation(), diag::err_init_conversion_failed)
4806 << (int)Entity.getKind()
Douglas Gregor20093b42009-12-09 23:02:17 +00004807 << DestType
John McCall7eb0a9e2010-11-24 05:12:34 +00004808 << Args[0]->isLValue()
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004809 << FromType
Douglas Gregor20093b42009-12-09 23:02:17 +00004810 << Args[0]->getSourceRange();
Douglas Gregor926df6c2011-06-11 01:09:30 +00004811 if (DestType.getNonReferenceType()->isObjCObjectPointerType() &&
4812 Args[0]->getType()->isObjCObjectPointerType())
4813 S.EmitRelatedResultTypeNote(Args[0]);
Douglas Gregord87b61f2009-12-10 17:56:55 +00004814 break;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00004815 }
John Wiegley429bb272011-04-08 18:41:53 +00004816
4817 case FK_ConversionFromPropertyFailed:
4818 // No-op. This error has already been reported.
4819 break;
4820
Douglas Gregord87b61f2009-12-10 17:56:55 +00004821 case FK_TooManyInitsForScalar: {
Douglas Gregor99a2e602009-12-16 01:38:02 +00004822 SourceRange R;
4823
4824 if (InitListExpr *InitList = dyn_cast<InitListExpr>(Args[0]))
Douglas Gregor19311e72010-09-08 21:40:08 +00004825 R = SourceRange(InitList->getInit(0)->getLocEnd(),
Douglas Gregor99a2e602009-12-16 01:38:02 +00004826 InitList->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004827 else
Douglas Gregor19311e72010-09-08 21:40:08 +00004828 R = SourceRange(Args[0]->getLocEnd(), Args[NumArgs - 1]->getLocEnd());
Douglas Gregord87b61f2009-12-10 17:56:55 +00004829
Douglas Gregor19311e72010-09-08 21:40:08 +00004830 R.setBegin(S.PP.getLocForEndOfToken(R.getBegin()));
4831 if (Kind.isCStyleOrFunctionalCast())
4832 S.Diag(Kind.getLocation(), diag::err_builtin_func_cast_more_than_one_arg)
4833 << R;
4834 else
4835 S.Diag(Kind.getLocation(), diag::err_excess_initializers)
4836 << /*scalar=*/2 << R;
Douglas Gregord87b61f2009-12-10 17:56:55 +00004837 break;
4838 }
4839
4840 case FK_ReferenceBindingToInitList:
4841 S.Diag(Kind.getLocation(), diag::err_reference_bind_init_list)
4842 << DestType.getNonReferenceType() << Args[0]->getSourceRange();
4843 break;
4844
4845 case FK_InitListBadDestinationType:
4846 S.Diag(Kind.getLocation(), diag::err_init_list_bad_dest_type)
4847 << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange();
4848 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004849
Douglas Gregor51c56d62009-12-14 20:49:26 +00004850 case FK_ConstructorOverloadFailed: {
4851 SourceRange ArgsRange;
4852 if (NumArgs)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004853 ArgsRange = SourceRange(Args[0]->getLocStart(),
Douglas Gregor51c56d62009-12-14 20:49:26 +00004854 Args[NumArgs - 1]->getLocEnd());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004855
Douglas Gregor51c56d62009-12-14 20:49:26 +00004856 // FIXME: Using "DestType" for the entity we're printing is probably
4857 // bad.
4858 switch (FailedOverloadResult) {
4859 case OR_Ambiguous:
4860 S.Diag(Kind.getLocation(), diag::err_ovl_ambiguous_init)
4861 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004862 FailedCandidateSet.NoteCandidates(S, OCD_ViableCandidates,
4863 Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004864 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004865
Douglas Gregor51c56d62009-12-14 20:49:26 +00004866 case OR_No_Viable_Function:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004867 if (Kind.getKind() == InitializationKind::IK_Default &&
4868 (Entity.getKind() == InitializedEntity::EK_Base ||
4869 Entity.getKind() == InitializedEntity::EK_Member) &&
4870 isa<CXXConstructorDecl>(S.CurContext)) {
4871 // This is implicit default initialization of a member or
4872 // base within a constructor. If no viable function was
4873 // found, notify the user that she needs to explicitly
4874 // initialize this base/member.
4875 CXXConstructorDecl *Constructor
4876 = cast<CXXConstructorDecl>(S.CurContext);
4877 if (Entity.getKind() == InitializedEntity::EK_Base) {
4878 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4879 << Constructor->isImplicit()
4880 << S.Context.getTypeDeclType(Constructor->getParent())
4881 << /*base=*/0
4882 << Entity.getType();
4883
4884 RecordDecl *BaseDecl
4885 = Entity.getBaseSpecifier()->getType()->getAs<RecordType>()
4886 ->getDecl();
4887 S.Diag(BaseDecl->getLocation(), diag::note_previous_decl)
4888 << S.Context.getTagDeclType(BaseDecl);
4889 } else {
4890 S.Diag(Kind.getLocation(), diag::err_missing_default_ctor)
4891 << Constructor->isImplicit()
4892 << S.Context.getTypeDeclType(Constructor->getParent())
4893 << /*member=*/1
4894 << Entity.getName();
4895 S.Diag(Entity.getDecl()->getLocation(), diag::note_field_decl);
4896
4897 if (const RecordType *Record
4898 = Entity.getType()->getAs<RecordType>())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004899 S.Diag(Record->getDecl()->getLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004900 diag::note_previous_decl)
4901 << S.Context.getTagDeclType(Record->getDecl());
4902 }
4903 break;
4904 }
4905
Douglas Gregor51c56d62009-12-14 20:49:26 +00004906 S.Diag(Kind.getLocation(), diag::err_ovl_no_viable_function_in_init)
4907 << DestType << ArgsRange;
John McCall120d63c2010-08-24 20:38:10 +00004908 FailedCandidateSet.NoteCandidates(S, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004909 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004910
Douglas Gregor51c56d62009-12-14 20:49:26 +00004911 case OR_Deleted: {
4912 S.Diag(Kind.getLocation(), diag::err_ovl_deleted_init)
4913 << true << DestType << ArgsRange;
4914 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00004915 OverloadingResult Ovl
4916 = FailedCandidateSet.BestViableFunction(S, Kind.getLocation(), Best);
Douglas Gregor51c56d62009-12-14 20:49:26 +00004917 if (Ovl == OR_Deleted) {
4918 S.Diag(Best->Function->getLocation(), diag::note_unavailable_here)
John McCallf85e1932011-06-15 23:02:42 +00004919 << 1 << Best->Function->isDeleted();
Douglas Gregor51c56d62009-12-14 20:49:26 +00004920 } else {
4921 llvm_unreachable("Inconsistent overload resolution?");
4922 }
4923 break;
4924 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004925
Douglas Gregor51c56d62009-12-14 20:49:26 +00004926 case OR_Success:
4927 llvm_unreachable("Conversion did not fail!");
4928 break;
4929 }
4930 break;
4931 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004932
Douglas Gregor99a2e602009-12-16 01:38:02 +00004933 case FK_DefaultInitOfConst:
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00004934 if (Entity.getKind() == InitializedEntity::EK_Member &&
4935 isa<CXXConstructorDecl>(S.CurContext)) {
4936 // This is implicit default-initialization of a const member in
4937 // a constructor. Complain that it needs to be explicitly
4938 // initialized.
4939 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(S.CurContext);
4940 S.Diag(Kind.getLocation(), diag::err_uninitialized_member_in_ctor)
4941 << Constructor->isImplicit()
4942 << S.Context.getTypeDeclType(Constructor->getParent())
4943 << /*const=*/1
4944 << Entity.getName();
4945 S.Diag(Entity.getDecl()->getLocation(), diag::note_previous_decl)
4946 << Entity.getName();
4947 } else {
4948 S.Diag(Kind.getLocation(), diag::err_default_init_const)
4949 << DestType << (bool)DestType->getAs<RecordType>();
4950 }
Douglas Gregor99a2e602009-12-16 01:38:02 +00004951 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004952
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004953 case FK_Incomplete:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004954 S.RequireCompleteType(Kind.getLocation(), DestType,
Douglas Gregor72a43bb2010-05-20 22:12:02 +00004955 diag::err_init_incomplete_type);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004956 break;
Douglas Gregor20093b42009-12-09 23:02:17 +00004957 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004958
Douglas Gregora41a8c52010-04-22 00:20:18 +00004959 PrintInitLocationNote(S, Entity);
Douglas Gregor20093b42009-12-09 23:02:17 +00004960 return true;
4961}
Douglas Gregor18ef5e22009-12-18 05:02:21 +00004962
Chris Lattner5f9e2722011-07-23 10:55:15 +00004963void InitializationSequence::dump(raw_ostream &OS) const {
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004964 switch (SequenceKind) {
4965 case FailedSequence: {
4966 OS << "Failed sequence: ";
4967 switch (Failure) {
4968 case FK_TooManyInitsForReference:
4969 OS << "too many initializers for reference";
4970 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004971
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004972 case FK_ArrayNeedsInitList:
4973 OS << "array requires initializer list";
4974 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004975
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004976 case FK_ArrayNeedsInitListOrStringLiteral:
4977 OS << "array requires initializer list or string literal";
4978 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004979
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00004980 case FK_ArrayTypeMismatch:
4981 OS << "array type mismatch";
4982 break;
4983
4984 case FK_NonConstantArrayInit:
4985 OS << "non-constant array initializer";
4986 break;
4987
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004988 case FK_AddressOfOverloadFailed:
4989 OS << "address of overloaded function failed";
4990 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004991
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004992 case FK_ReferenceInitOverloadFailed:
4993 OS << "overload resolution for reference initialization failed";
4994 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004995
Douglas Gregorde4b1d82010-01-29 19:14:02 +00004996 case FK_NonConstLValueReferenceBindingToTemporary:
4997 OS << "non-const lvalue reference bound to temporary";
4998 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004999
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005000 case FK_NonConstLValueReferenceBindingToUnrelated:
5001 OS << "non-const lvalue reference bound to unrelated type";
5002 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005003
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005004 case FK_RValueReferenceBindingToLValue:
5005 OS << "rvalue reference bound to an lvalue";
5006 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005007
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005008 case FK_ReferenceInitDropsQualifiers:
5009 OS << "reference initialization drops qualifiers";
5010 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005011
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005012 case FK_ReferenceInitFailed:
5013 OS << "reference initialization failed";
5014 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005016 case FK_ConversionFailed:
5017 OS << "conversion failed";
5018 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005019
John Wiegley429bb272011-04-08 18:41:53 +00005020 case FK_ConversionFromPropertyFailed:
5021 OS << "conversion from property failed";
5022 break;
5023
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005024 case FK_TooManyInitsForScalar:
5025 OS << "too many initializers for scalar";
5026 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005027
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005028 case FK_ReferenceBindingToInitList:
5029 OS << "referencing binding to initializer list";
5030 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005031
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005032 case FK_InitListBadDestinationType:
5033 OS << "initializer list for non-aggregate, non-scalar type";
5034 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005035
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005036 case FK_UserConversionOverloadFailed:
5037 OS << "overloading failed for user-defined conversion";
5038 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005039
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005040 case FK_ConstructorOverloadFailed:
5041 OS << "constructor overloading failed";
5042 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005043
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005044 case FK_DefaultInitOfConst:
5045 OS << "default initialization of a const variable";
5046 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005047
Douglas Gregor72a43bb2010-05-20 22:12:02 +00005048 case FK_Incomplete:
5049 OS << "initialization of incomplete type";
5050 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005051 }
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005052 OS << '\n';
5053 return;
5054 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005055
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005056 case DependentSequence:
Sebastian Redl7491c492011-06-05 13:59:11 +00005057 OS << "Dependent sequence\n";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005058 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005059
Sebastian Redl7491c492011-06-05 13:59:11 +00005060 case NormalSequence:
5061 OS << "Normal sequence: ";
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005062 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005063 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005064
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005065 for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) {
5066 if (S != step_begin()) {
5067 OS << " -> ";
5068 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005069
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005070 switch (S->Kind) {
5071 case SK_ResolveAddressOfOverloadedFunction:
5072 OS << "resolve address of overloaded function";
5073 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005074
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005075 case SK_CastDerivedToBaseRValue:
5076 OS << "derived-to-base case (rvalue" << S->Type.getAsString() << ")";
5077 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005078
Sebastian Redl906082e2010-07-20 04:20:21 +00005079 case SK_CastDerivedToBaseXValue:
5080 OS << "derived-to-base case (xvalue" << S->Type.getAsString() << ")";
5081 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005082
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005083 case SK_CastDerivedToBaseLValue:
5084 OS << "derived-to-base case (lvalue" << S->Type.getAsString() << ")";
5085 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005086
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005087 case SK_BindReference:
5088 OS << "bind reference to lvalue";
5089 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005090
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005091 case SK_BindReferenceToTemporary:
5092 OS << "bind reference to a temporary";
5093 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005094
Douglas Gregor523d46a2010-04-18 07:40:54 +00005095 case SK_ExtraneousCopyToTemporary:
5096 OS << "extraneous C++03 copy to temporary";
5097 break;
5098
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005099 case SK_UserConversion:
Benjamin Kramer900fc632010-04-17 09:33:03 +00005100 OS << "user-defined conversion via " << S->Function.Function;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005101 break;
Sebastian Redl906082e2010-07-20 04:20:21 +00005102
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005103 case SK_QualificationConversionRValue:
5104 OS << "qualification conversion (rvalue)";
5105
Sebastian Redl906082e2010-07-20 04:20:21 +00005106 case SK_QualificationConversionXValue:
5107 OS << "qualification conversion (xvalue)";
5108
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005109 case SK_QualificationConversionLValue:
5110 OS << "qualification conversion (lvalue)";
5111 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005112
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005113 case SK_ConversionSequence:
5114 OS << "implicit conversion sequence (";
5115 S->ICS->DebugPrint(); // FIXME: use OS
5116 OS << ")";
5117 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005118
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005119 case SK_ListInitialization:
5120 OS << "list initialization";
5121 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005122
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005123 case SK_ConstructorInitialization:
5124 OS << "constructor initialization";
5125 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005126
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005127 case SK_ZeroInitialization:
5128 OS << "zero initialization";
5129 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005130
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005131 case SK_CAssignment:
5132 OS << "C assignment";
5133 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005134
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005135 case SK_StringInit:
5136 OS << "string initialization";
5137 break;
Douglas Gregor569c3162010-08-07 11:51:51 +00005138
5139 case SK_ObjCObjectConversion:
5140 OS << "Objective-C object conversion";
5141 break;
Douglas Gregorcd9ec3b2011-02-22 18:29:51 +00005142
5143 case SK_ArrayInit:
5144 OS << "array initialization";
5145 break;
John McCallf85e1932011-06-15 23:02:42 +00005146
5147 case SK_PassByIndirectCopyRestore:
5148 OS << "pass by indirect copy and restore";
5149 break;
5150
5151 case SK_PassByIndirectRestore:
5152 OS << "pass by indirect restore";
5153 break;
5154
5155 case SK_ProduceObjCObject:
5156 OS << "Objective-C object retension";
5157 break;
Douglas Gregorde4b1d82010-01-29 19:14:02 +00005158 }
5159 }
5160}
5161
5162void InitializationSequence::dump() const {
5163 dump(llvm::errs());
5164}
5165
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005166static void DiagnoseNarrowingInInitList(
5167 Sema& S, QualType EntityType, const Expr *InitE,
5168 bool Constant, const APValue &ConstantValue) {
5169 if (Constant) {
5170 S.Diag(InitE->getLocStart(),
Francois Pichetb0a58cd2011-08-18 00:04:08 +00005171 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005172 ? diag::err_init_list_constant_narrowing
5173 : diag::warn_init_list_constant_narrowing)
5174 << InitE->getSourceRange()
5175 << ConstantValue
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005176 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005177 } else
5178 S.Diag(InitE->getLocStart(),
Francois Pichetb0a58cd2011-08-18 00:04:08 +00005179 S.getLangOptions().CPlusPlus0x && !S.getLangOptions().Microsoft
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005180 ? diag::err_init_list_variable_narrowing
5181 : diag::warn_init_list_variable_narrowing)
5182 << InitE->getSourceRange()
Jeffrey Yasskin99061492011-08-29 15:59:37 +00005183 << InitE->getType().getLocalUnqualifiedType()
5184 << EntityType.getLocalUnqualifiedType();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005185
5186 llvm::SmallString<128> StaticCast;
5187 llvm::raw_svector_ostream OS(StaticCast);
5188 OS << "static_cast<";
5189 if (const TypedefType *TT = EntityType->getAs<TypedefType>()) {
5190 // It's important to use the typedef's name if there is one so that the
5191 // fixit doesn't break code using types like int64_t.
5192 //
5193 // FIXME: This will break if the typedef requires qualification. But
5194 // getQualifiedNameAsString() includes non-machine-parsable components.
5195 OS << TT->getDecl();
5196 } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>())
5197 OS << BT->getName(S.getLangOptions());
5198 else {
5199 // Oops, we didn't find the actual type of the variable. Don't emit a fixit
5200 // with a broken cast.
5201 return;
5202 }
5203 OS << ">(";
5204 S.Diag(InitE->getLocStart(), diag::note_init_list_narrowing_override)
5205 << InitE->getSourceRange()
5206 << FixItHint::CreateInsertion(InitE->getLocStart(), OS.str())
5207 << FixItHint::CreateInsertion(
5208 S.getPreprocessor().getLocForEndOfToken(InitE->getLocEnd()), ")");
5209}
5210
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005211//===----------------------------------------------------------------------===//
5212// Initialization helper functions
5213//===----------------------------------------------------------------------===//
Sean Hunt2be7e902011-05-12 22:46:29 +00005214bool
5215Sema::CanPerformCopyInitialization(const InitializedEntity &Entity,
5216 ExprResult Init) {
5217 if (Init.isInvalid())
5218 return false;
5219
5220 Expr *InitE = Init.get();
5221 assert(InitE && "No initialization expression");
5222
5223 InitializationKind Kind = InitializationKind::CreateCopy(SourceLocation(),
5224 SourceLocation());
5225 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
Sebastian Redl383616c2011-06-05 12:23:28 +00005226 return !Seq.Failed();
Sean Hunt2be7e902011-05-12 22:46:29 +00005227}
5228
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005229ExprResult
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005230Sema::PerformCopyInitialization(const InitializedEntity &Entity,
5231 SourceLocation EqualLoc,
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005232 ExprResult Init,
5233 bool TopLevelOfInitList) {
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005234 if (Init.isInvalid())
5235 return ExprError();
5236
John McCall15d7d122010-11-11 03:21:53 +00005237 Expr *InitE = Init.get();
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005238 assert(InitE && "No initialization expression?");
5239
5240 if (EqualLoc.isInvalid())
5241 EqualLoc = InitE->getLocStart();
5242
5243 InitializationKind Kind = InitializationKind::CreateCopy(InitE->getLocStart(),
5244 EqualLoc);
5245 InitializationSequence Seq(*this, Entity, Kind, &InitE, 1);
5246 Init.release();
Jeffrey Yasskin19159132011-07-26 23:20:30 +00005247
5248 bool Constant = false;
5249 APValue Result;
5250 if (TopLevelOfInitList &&
5251 Seq.endsWithNarrowing(Context, InitE, &Constant, &Result)) {
5252 DiagnoseNarrowingInInitList(*this, Entity.getType(), InitE,
5253 Constant, Result);
5254 }
John McCallf312b1e2010-08-26 23:41:50 +00005255 return Seq.Perform(*this, Entity, Kind, MultiExprArg(&InitE, 1));
Douglas Gregor18ef5e22009-12-18 05:02:21 +00005256}