blob: 2d4b01f26b0de8e6adcdbd5f422e8586b6d6c5c4 [file] [log] [blame]
Douglas Gregord87b61f2009-12-10 17:56:55 +00001//===--- SemaInit.h - Semantic Analysis for Initializers --------*- C++ -*-===//
Douglas Gregor20093b42009-12-09 23:02:17 +00002//
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//
10// This file provides supporting data types for initialization of objects.
11//
12//===----------------------------------------------------------------------===//
13#ifndef LLVM_CLANG_SEMA_INIT_H
14#define LLVM_CLANG_SEMA_INIT_H
15
16#include "SemaOverload.h"
17#include "clang/AST/TypeLoc.h"
18#include "clang/Parse/Action.h"
19#include "clang/Basic/SourceLocation.h"
20#include "llvm/ADT/PointerIntPair.h"
21#include "llvm/ADT/SmallVector.h"
22#include <cassert>
23
24namespace clang {
25
26class CXXBaseSpecifier;
27class DeclaratorDecl;
28class DeclaratorInfo;
29class FieldDecl;
30class FunctionDecl;
31class ParmVarDecl;
32class Sema;
33class TypeLoc;
34class VarDecl;
35
36/// \brief Describes an entity that is being initialized.
37class InitializedEntity {
38public:
39 /// \brief Specifies the kind of entity being initialized.
40 enum EntityKind {
41 /// \brief The entity being initialized is a variable.
42 EK_Variable,
43 /// \brief The entity being initialized is a function parameter.
44 EK_Parameter,
45 /// \brief The entity being initialized is the result of a function call.
46 EK_Result,
47 /// \brief The entity being initialized is an exception object that
48 /// is being thrown.
49 EK_Exception,
50 /// \brief The entity being initialized is a temporary object.
51 EK_Temporary,
52 /// \brief The entity being initialized is a base member subobject.
53 EK_Base,
54 /// \brief The entity being initialized is a non-static data member
55 /// subobject.
56 EK_Member
57 };
58
59private:
60 /// \brief The kind of entity being initialized.
61 EntityKind Kind;
62
63 /// \brief The type of the object or reference being initialized along with
64 /// its location information.
65 TypeLoc TL;
66
67 union {
68 /// \brief When Kind == EK_Variable, EK_Parameter, or EK_Member,
69 /// the VarDecl, ParmVarDecl, or FieldDecl, respectively.
70 DeclaratorDecl *VariableOrMember;
71
72 /// \brief When Kind == EK_Result or EK_Exception, the location of the
73 /// 'return' or 'throw' keyword, respectively. When Kind == EK_Temporary,
74 /// the location where the temporary is being created.
75 unsigned Location;
76
77 /// \brief When Kind == EK_Base, the base specifier that provides the
78 /// base class.
79 CXXBaseSpecifier *Base;
80 };
81
82 InitializedEntity() { }
83
84 /// \brief Create the initialization entity for a variable.
85 InitializedEntity(VarDecl *Var)
86 : Kind(EK_Variable),
87 VariableOrMember(reinterpret_cast<DeclaratorDecl*>(Var))
88 {
89 InitDeclLoc();
90 }
91
92 /// \brief Create the initialization entity for a parameter.
93 InitializedEntity(ParmVarDecl *Parm)
94 : Kind(EK_Parameter),
95 VariableOrMember(reinterpret_cast<DeclaratorDecl*>(Parm))
96 {
97 InitDeclLoc();
98 }
99
100 /// \brief Create the initialization entity for the result of a function,
101 /// throwing an object, or performing an explicit cast.
102 InitializedEntity(EntityKind Kind, SourceLocation Loc, TypeLoc TL)
103 : Kind(Kind), TL(TL), Location(Loc.getRawEncoding()) { }
104
105 /// \brief Create the initialization entity for a member subobject.
106 InitializedEntity(FieldDecl *Member)
107 : Kind(EK_Member),
108 VariableOrMember(reinterpret_cast<DeclaratorDecl*>(Member))
109 {
110 InitDeclLoc();
111 }
112
113 /// \brief Initialize type-location information from a declaration.
114 void InitDeclLoc();
115
116public:
117 /// \brief Create the initialization entity for a variable.
118 static InitializedEntity InitializeVariable(VarDecl *Var) {
119 return InitializedEntity(Var);
120 }
121
122 /// \brief Create the initialization entity for a parameter.
123 static InitializedEntity InitializeParameter(ParmVarDecl *Parm) {
124 return InitializedEntity(Parm);
125 }
126
127 /// \brief Create the initialization entity for the result of a function.
128 static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
129 TypeLoc TL) {
130 return InitializedEntity(EK_Result, ReturnLoc, TL);
131 }
132
133 /// \brief Create the initialization entity for an exception object.
134 static InitializedEntity InitializeException(SourceLocation ThrowLoc,
135 TypeLoc TL) {
136 return InitializedEntity(EK_Exception, ThrowLoc, TL);
137 }
138
139 /// \brief Create the initialization entity for a temporary.
140 static InitializedEntity InitializeTemporary(EntityKind Kind, TypeLoc TL) {
141 return InitializedEntity(Kind, SourceLocation(), TL);
142 }
143
144 /// \brief Create the initialization entity for a base class subobject.
145 static InitializedEntity InitializeBase(ASTContext &Context,
146 CXXBaseSpecifier *Base);
147
148 /// \brief Create the initialize entity for a member subobject.
149 static InitializedEntity InitializeMember(FieldDecl *Member) {
150 return InitializedEntity(Member);
151 }
152
153 /// \brief Determine the kind of initialization.
154 EntityKind getKind() const { return Kind; }
155
156 /// \brief Retrieve type being initialized.
157 TypeLoc getType() const { return TL; }
158
159 /// \brief Determine the location of the 'return' keyword when initializing
160 /// the result of a function call.
161 SourceLocation getReturnLoc() const {
162 assert(getKind() == EK_Result && "No 'return' location!");
163 return SourceLocation::getFromRawEncoding(Location);
164 }
165
166 /// \brief Determine the location of the 'throw' keyword when initializing
167 /// an exception object.
168 SourceLocation getThrowLoc() const {
169 assert(getKind() == EK_Exception && "No 'throw' location!");
170 return SourceLocation::getFromRawEncoding(Location);
171 }
172};
173
174/// \brief Describes the kind of initialization being performed, along with
175/// location information for tokens related to the initialization (equal sign,
176/// parentheses).
177class InitializationKind {
178public:
179 /// \brief The kind of initialization being performed.
180 enum InitKind {
181 IK_Direct, ///< Direct initialization
182 IK_Copy, ///< Copy initialization
183 IK_Default, ///< Default initialization
184 IK_Value ///< Value initialization
185 };
186
187private:
188 /// \brief The kind of initialization that we're storing.
189 enum StoredInitKind {
190 SIK_Direct = IK_Direct, ///< Direct initialization
191 SIK_Copy = IK_Copy, ///< Copy initialization
192 SIK_Default = IK_Default, ///< Default initialization
193 SIK_Value = IK_Value, ///< Value initialization
194 SIK_DirectCast, ///< Direct initialization due to a cast
195 /// \brief Direct initialization due to a C-style or functional cast.
196 SIK_DirectCStyleOrFunctionalCast
197 };
198
199 /// \brief The kind of initialization being performed.
200 StoredInitKind Kind;
201
202 /// \brief The source locations involved in the initialization.
203 SourceLocation Locations[3];
204
205 InitializationKind(StoredInitKind Kind, SourceLocation Loc1,
206 SourceLocation Loc2, SourceLocation Loc3)
207 : Kind(Kind)
208 {
209 Locations[0] = Loc1;
210 Locations[1] = Loc2;
211 Locations[2] = Loc3;
212 }
213
214public:
215 /// \brief Create a direct initialization.
216 static InitializationKind CreateDirect(SourceLocation InitLoc,
217 SourceLocation LParenLoc,
218 SourceLocation RParenLoc) {
219 return InitializationKind(SIK_Direct, InitLoc, LParenLoc, RParenLoc);
220 }
221
222 /// \brief Create a direct initialization due to a cast.
223 static InitializationKind CreateCast(SourceRange TypeRange,
224 bool IsCStyleCast) {
225 return InitializationKind(IsCStyleCast? SIK_DirectCStyleOrFunctionalCast
226 : SIK_DirectCast,
227 TypeRange.getBegin(), TypeRange.getBegin(),
228 TypeRange.getEnd());
229 }
230
231 /// \brief Create a copy initialization.
232 static InitializationKind CreateCopy(SourceLocation InitLoc,
233 SourceLocation EqualLoc) {
234 return InitializationKind(SIK_Copy, InitLoc, EqualLoc, EqualLoc);
235 }
236
237 /// \brief Create a default initialization.
238 static InitializationKind CreateDefault(SourceLocation InitLoc) {
239 return InitializationKind(SIK_Default, InitLoc, InitLoc, InitLoc);
240 }
241
242 /// \brief Create a value initialization.
243 static InitializationKind CreateValue(SourceLocation InitLoc,
244 SourceLocation LParenLoc,
245 SourceLocation RParenLoc) {
246 return InitializationKind(SIK_Value, InitLoc, LParenLoc, RParenLoc);
247 }
248
249 /// \brief Determine the initialization kind.
250 InitKind getKind() const {
251 if (Kind > SIK_Value)
252 return IK_Direct;
253
254 return (InitKind)Kind;
255 }
256
257 /// \brief Determine whether this initialization is an explicit cast.
258 bool isExplicitCast() const {
259 return Kind == SIK_DirectCast || Kind == SIK_DirectCStyleOrFunctionalCast;
260 }
261
262 /// \brief Determine whether this initialization is a C-style cast.
263 bool isCStyleOrFunctionalCast() const {
264 return Kind == SIK_DirectCStyleOrFunctionalCast;
265 }
266
267 /// \brief Retrieve the location at which initialization is occurring.
268 SourceLocation getLocation() const { return Locations[0]; }
269
270 /// \brief Retrieve the source range that covers the initialization.
271 SourceRange getRange() const {
Douglas Gregor71d17402009-12-15 00:01:57 +0000272 return SourceRange(Locations[0], Locations[2]);
Douglas Gregor20093b42009-12-09 23:02:17 +0000273 }
274
275 /// \brief Retrieve the location of the equal sign for copy initialization
276 /// (if present).
277 SourceLocation getEqualLoc() const {
278 assert(Kind == SIK_Copy && "Only copy initialization has an '='");
279 return Locations[1];
280 }
281
282 /// \brief Retrieve the source range containing the locations of the open
283 /// and closing parentheses for value and direct initializations.
284 SourceRange getParenRange() const {
285 assert((getKind() == IK_Direct || Kind == SIK_Value) &&
286 "Only direct- and value-initialization have parentheses");
287 return SourceRange(Locations[1], Locations[2]);
288 }
289};
290
291/// \brief Describes the sequence of initializations required to initialize
292/// a given object or reference with a set of arguments.
293class InitializationSequence {
294public:
295 /// \brief Describes the kind of initialization sequence computed.
Douglas Gregor71d17402009-12-15 00:01:57 +0000296 ///
297 /// FIXME: Much of this information is in the initialization steps... why is
298 /// it duplicated here?
Douglas Gregor20093b42009-12-09 23:02:17 +0000299 enum SequenceKind {
300 /// \brief A failed initialization sequence. The failure kind tells what
301 /// happened.
302 FailedSequence = 0,
303
304 /// \brief A dependent initialization, which could not be
305 /// type-checked due to the presence of dependent types or
306 /// dependently-type expressions.
307 DependentSequence,
308
Douglas Gregor4a520a22009-12-14 17:27:33 +0000309 /// \brief A user-defined conversion sequence.
310 UserDefinedConversion,
311
Douglas Gregor51c56d62009-12-14 20:49:26 +0000312 /// \brief A constructor call.
Douglas Gregora6ca6502009-12-14 20:57:13 +0000313 ConstructorInitialization,
Douglas Gregor51c56d62009-12-14 20:49:26 +0000314
Douglas Gregor20093b42009-12-09 23:02:17 +0000315 /// \brief A reference binding.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000316 ReferenceBinding,
317
318 /// \brief List initialization
Douglas Gregor71d17402009-12-15 00:01:57 +0000319 ListInitialization,
320
321 /// \brief Zero-initialization.
322 ZeroInitialization
Douglas Gregor20093b42009-12-09 23:02:17 +0000323 };
324
325 /// \brief Describes the kind of a particular step in an initialization
326 /// sequence.
327 enum StepKind {
328 /// \brief Resolve the address of an overloaded function to a specific
329 /// function declaration.
330 SK_ResolveAddressOfOverloadedFunction,
331 /// \brief Perform a derived-to-base cast, producing an rvalue.
332 SK_CastDerivedToBaseRValue,
333 /// \brief Perform a derived-to-base cast, producing an lvalue.
334 SK_CastDerivedToBaseLValue,
335 /// \brief Reference binding to an lvalue.
336 SK_BindReference,
337 /// \brief Reference binding to a temporary.
338 SK_BindReferenceToTemporary,
339 /// \brief Perform a user-defined conversion, either via a conversion
340 /// function or via a constructor.
341 SK_UserConversion,
342 /// \brief Perform a qualification conversion, producing an rvalue.
343 SK_QualificationConversionRValue,
344 /// \brief Perform a qualification conversion, producing an lvalue.
345 SK_QualificationConversionLValue,
346 /// \brief Perform an implicit conversion sequence.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000347 SK_ConversionSequence,
348 /// \brief Perform list-initialization
Douglas Gregor51c56d62009-12-14 20:49:26 +0000349 SK_ListInitialization,
350 /// \brief Perform initialization via a constructor.
Douglas Gregor71d17402009-12-15 00:01:57 +0000351 SK_ConstructorInitialization,
352 /// \brief Zero-initialize the object
353 SK_ZeroInitialization
Douglas Gregor20093b42009-12-09 23:02:17 +0000354 };
355
356 /// \brief A single step in the initialization sequence.
357 class Step {
358 public:
359 /// \brief The kind of conversion or initialization step we are taking.
360 StepKind Kind;
361
362 // \brief The type that results from this initialization.
363 QualType Type;
364
365 union {
366 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
367 /// SK_UserConversion, the function that the expression should be
368 /// resolved to or the conversion function to call, respectively.
369 FunctionDecl *Function;
370
371 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
372 /// sequence
373 ImplicitConversionSequence *ICS;
374 };
375
376 void Destroy();
377 };
378
379private:
380 /// \brief The kind of initialization sequence computed.
381 enum SequenceKind SequenceKind;
382
383 /// \brief Steps taken by this initialization.
384 llvm::SmallVector<Step, 4> Steps;
385
386public:
387 /// \brief Describes why initialization failed.
388 enum FailureKind {
389 /// \brief Too many initializers provided for a reference.
390 FK_TooManyInitsForReference,
391 /// \brief Array must be initialized with an initializer list.
392 FK_ArrayNeedsInitList,
393 /// \brief Array must be initialized with an initializer list or a
394 /// string literal.
395 FK_ArrayNeedsInitListOrStringLiteral,
396 /// \brief Cannot resolve the address of an overloaded function.
397 FK_AddressOfOverloadFailed,
398 /// \brief Overloading due to reference initialization failed.
399 FK_ReferenceInitOverloadFailed,
400 /// \brief Non-const lvalue reference binding to a temporary.
401 FK_NonConstLValueReferenceBindingToTemporary,
402 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
403 /// type.
404 FK_NonConstLValueReferenceBindingToUnrelated,
405 /// \brief Rvalue reference binding to an lvalue.
406 FK_RValueReferenceBindingToLValue,
407 /// \brief Reference binding drops qualifiers.
408 FK_ReferenceInitDropsQualifiers,
409 /// \brief Reference binding failed.
410 FK_ReferenceInitFailed,
411 /// \brief Implicit conversion failed.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000412 FK_ConversionFailed,
413 /// \brief Too many initializers for scalar
414 FK_TooManyInitsForScalar,
415 /// \brief Reference initialization from an initializer list
416 FK_ReferenceBindingToInitList,
417 /// \brief Initialization of some unused destination type with an
418 /// initializer list.
Douglas Gregor4a520a22009-12-14 17:27:33 +0000419 FK_InitListBadDestinationType,
420 /// \brief Overloading for a user-defined conversion failed.
Douglas Gregor51c56d62009-12-14 20:49:26 +0000421 FK_UserConversionOverloadFailed,
422 /// \brief Overloaded for initialization by constructor failed.
423 FK_ConstructorOverloadFailed
Douglas Gregor20093b42009-12-09 23:02:17 +0000424 };
425
426private:
427 /// \brief The reason why initialization failued.
428 FailureKind Failure;
429
430 /// \brief The failed result of overload resolution.
431 OverloadingResult FailedOverloadResult;
432
433 /// \brief The candidate set created when initialization failed.
434 OverloadCandidateSet FailedCandidateSet;
435
436public:
437 /// \brief Try to perform initialization of the given entity, creating a
438 /// record of the steps required to perform the initialization.
439 ///
440 /// The generated initialization sequence will either contain enough
441 /// information to diagnose
442 ///
443 /// \param S the semantic analysis object.
444 ///
445 /// \param Entity the entity being initialized.
446 ///
447 /// \param Kind the kind of initialization being performed.
448 ///
449 /// \param Args the argument(s) provided for initialization.
450 ///
451 /// \param NumArgs the number of arguments provided for initialization.
452 InitializationSequence(Sema &S,
453 const InitializedEntity &Entity,
454 const InitializationKind &Kind,
455 Expr **Args,
456 unsigned NumArgs);
457
458 ~InitializationSequence();
459
460 /// \brief Perform the actual initialization of the given entity based on
461 /// the computed initialization sequence.
462 ///
463 /// \param S the semantic analysis object.
464 ///
465 /// \param Entity the entity being initialized.
466 ///
467 /// \param Kind the kind of initialization being performed.
468 ///
469 /// \param Args the argument(s) provided for initialization, ownership of
470 /// which is transfered into the routine.
471 ///
Douglas Gregord87b61f2009-12-10 17:56:55 +0000472 /// \param ResultType if non-NULL, will be set to the type of the
473 /// initialized object, which is the type of the declaration in most
474 /// cases. However, when the initialized object is a variable of
475 /// incomplete array type and the initializer is an initializer
476 /// list, this type will be set to the completed array type.
477 ///
Douglas Gregor20093b42009-12-09 23:02:17 +0000478 /// \returns an expression that performs the actual object initialization, if
479 /// the initialization is well-formed. Otherwise, emits diagnostics
480 /// and returns an invalid expression.
481 Action::OwningExprResult Perform(Sema &S,
482 const InitializedEntity &Entity,
483 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +0000484 Action::MultiExprArg Args,
485 QualType *ResultType = 0);
Douglas Gregor20093b42009-12-09 23:02:17 +0000486
487 /// \brief Diagnose an potentially-invalid initialization sequence.
488 ///
489 /// \returns true if the initialization sequence was ill-formed,
490 /// false otherwise.
491 bool Diagnose(Sema &S,
492 const InitializedEntity &Entity,
493 const InitializationKind &Kind,
494 Expr **Args, unsigned NumArgs);
495
496 /// \brief Determine the kind of initialization sequence computed.
497 enum SequenceKind getKind() const { return SequenceKind; }
498
499 /// \brief Set the kind of sequence computed.
500 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
501
502 /// \brief Determine whether the initialization sequence is valid.
503 operator bool() const { return SequenceKind != FailedSequence; }
504
505 typedef llvm::SmallVector<Step, 4>::const_iterator step_iterator;
506 step_iterator step_begin() const { return Steps.begin(); }
507 step_iterator step_end() const { return Steps.end(); }
508
509 /// \brief Add a new step in the initialization that resolves the address
510 /// of an overloaded function to a specific function declaration.
511 ///
512 /// \param Function the function to which the overloaded function reference
513 /// resolves.
514 void AddAddressOverloadResolutionStep(FunctionDecl *Function);
515
516 /// \brief Add a new step in the initialization that performs a derived-to-
517 /// base cast.
518 ///
519 /// \param BaseType the base type to which we will be casting.
520 ///
521 /// \param IsLValue true if the result of this cast will be treated as
522 /// an lvalue.
523 void AddDerivedToBaseCastStep(QualType BaseType, bool IsLValue);
524
525 /// \brief Add a new step binding a reference to an object.
526 ///
527 /// \param BindingTemporary true if we are binding a reference to a temporary
528 /// object (thereby extending its lifetime); false if we are binding to an
529 /// lvalue or an lvalue treated as an rvalue.
530 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
531
532 /// \brief Add a new step invoking a conversion function, which is either
533 /// a constructor or a conversion function.
Eli Friedman03981012009-12-11 02:42:07 +0000534 void AddUserConversionStep(FunctionDecl *Function, QualType T);
Douglas Gregor20093b42009-12-09 23:02:17 +0000535
536 /// \brief Add a new step that performs a qualification conversion to the
537 /// given type.
538 void AddQualificationConversionStep(QualType Ty, bool IsLValue);
539
540 /// \brief Add a new step that applies an implicit conversion sequence.
541 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
542 QualType T);
Douglas Gregord87b61f2009-12-10 17:56:55 +0000543
544 /// \brief Add a list-initialiation step
545 void AddListInitializationStep(QualType T);
546
Douglas Gregor71d17402009-12-15 00:01:57 +0000547 /// \brief Add a constructor-initialization step.
Douglas Gregor51c56d62009-12-14 20:49:26 +0000548 void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
549 QualType T);
Douglas Gregor71d17402009-12-15 00:01:57 +0000550
551 /// \brief Add a zero-initialization step.
552 void AddZeroInitializationStep(QualType T);
Douglas Gregor51c56d62009-12-14 20:49:26 +0000553
Douglas Gregor20093b42009-12-09 23:02:17 +0000554 /// \brief Note that this initialization sequence failed.
555 void SetFailed(FailureKind Failure) {
556 SequenceKind = FailedSequence;
557 this->Failure = Failure;
558 }
559
560 /// \brief Note that this initialization sequence failed due to failed
561 /// overload resolution.
562 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
563
564 /// \brief Retrieve a reference to the candidate set when overload
565 /// resolution fails.
566 OverloadCandidateSet &getFailedCandidateSet() {
567 return FailedCandidateSet;
568 }
569
570 /// \brief Determine why initialization failed.
571 FailureKind getFailureKind() const {
572 assert(getKind() == FailedSequence && "Not an initialization failure!");
573 return Failure;
574 }
575};
576
577} // end namespace clang
578
579#endif // LLVM_CLANG_SEMA_INIT_H