blob: c084025b817b6ef5616e36ba8d9bf40172434e61 [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.
Douglas Gregor99a2e602009-12-16 01:38:02 +0000140 static InitializedEntity InitializeTemporary(TypeLoc TL) {
141 return InitializedEntity(EK_Temporary, SourceLocation(), TL);
Douglas Gregor20093b42009-12-09 23:02:17 +0000142 }
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
Douglas Gregor99a2e602009-12-16 01:38:02 +0000159 /// \brief Retrieve the name of the entity being initialized.
160 DeclarationName getName() const;
161
Douglas Gregor20093b42009-12-09 23:02:17 +0000162 /// \brief Determine the location of the 'return' keyword when initializing
163 /// the result of a function call.
164 SourceLocation getReturnLoc() const {
165 assert(getKind() == EK_Result && "No 'return' location!");
166 return SourceLocation::getFromRawEncoding(Location);
167 }
168
169 /// \brief Determine the location of the 'throw' keyword when initializing
170 /// an exception object.
171 SourceLocation getThrowLoc() const {
172 assert(getKind() == EK_Exception && "No 'throw' location!");
173 return SourceLocation::getFromRawEncoding(Location);
174 }
175};
176
177/// \brief Describes the kind of initialization being performed, along with
178/// location information for tokens related to the initialization (equal sign,
179/// parentheses).
180class InitializationKind {
181public:
182 /// \brief The kind of initialization being performed.
183 enum InitKind {
184 IK_Direct, ///< Direct initialization
185 IK_Copy, ///< Copy initialization
186 IK_Default, ///< Default initialization
187 IK_Value ///< Value initialization
188 };
189
190private:
191 /// \brief The kind of initialization that we're storing.
192 enum StoredInitKind {
193 SIK_Direct = IK_Direct, ///< Direct initialization
194 SIK_Copy = IK_Copy, ///< Copy initialization
195 SIK_Default = IK_Default, ///< Default initialization
196 SIK_Value = IK_Value, ///< Value initialization
197 SIK_DirectCast, ///< Direct initialization due to a cast
198 /// \brief Direct initialization due to a C-style or functional cast.
199 SIK_DirectCStyleOrFunctionalCast
200 };
201
202 /// \brief The kind of initialization being performed.
203 StoredInitKind Kind;
204
205 /// \brief The source locations involved in the initialization.
206 SourceLocation Locations[3];
207
208 InitializationKind(StoredInitKind Kind, SourceLocation Loc1,
209 SourceLocation Loc2, SourceLocation Loc3)
210 : Kind(Kind)
211 {
212 Locations[0] = Loc1;
213 Locations[1] = Loc2;
214 Locations[2] = Loc3;
215 }
216
217public:
218 /// \brief Create a direct initialization.
219 static InitializationKind CreateDirect(SourceLocation InitLoc,
220 SourceLocation LParenLoc,
221 SourceLocation RParenLoc) {
222 return InitializationKind(SIK_Direct, InitLoc, LParenLoc, RParenLoc);
223 }
224
225 /// \brief Create a direct initialization due to a cast.
226 static InitializationKind CreateCast(SourceRange TypeRange,
227 bool IsCStyleCast) {
228 return InitializationKind(IsCStyleCast? SIK_DirectCStyleOrFunctionalCast
229 : SIK_DirectCast,
230 TypeRange.getBegin(), TypeRange.getBegin(),
231 TypeRange.getEnd());
232 }
233
234 /// \brief Create a copy initialization.
235 static InitializationKind CreateCopy(SourceLocation InitLoc,
236 SourceLocation EqualLoc) {
237 return InitializationKind(SIK_Copy, InitLoc, EqualLoc, EqualLoc);
238 }
239
240 /// \brief Create a default initialization.
241 static InitializationKind CreateDefault(SourceLocation InitLoc) {
242 return InitializationKind(SIK_Default, InitLoc, InitLoc, InitLoc);
243 }
244
245 /// \brief Create a value initialization.
246 static InitializationKind CreateValue(SourceLocation InitLoc,
247 SourceLocation LParenLoc,
248 SourceLocation RParenLoc) {
249 return InitializationKind(SIK_Value, InitLoc, LParenLoc, RParenLoc);
250 }
251
252 /// \brief Determine the initialization kind.
253 InitKind getKind() const {
254 if (Kind > SIK_Value)
255 return IK_Direct;
256
257 return (InitKind)Kind;
258 }
259
260 /// \brief Determine whether this initialization is an explicit cast.
261 bool isExplicitCast() const {
262 return Kind == SIK_DirectCast || Kind == SIK_DirectCStyleOrFunctionalCast;
263 }
264
265 /// \brief Determine whether this initialization is a C-style cast.
266 bool isCStyleOrFunctionalCast() const {
267 return Kind == SIK_DirectCStyleOrFunctionalCast;
268 }
269
270 /// \brief Retrieve the location at which initialization is occurring.
271 SourceLocation getLocation() const { return Locations[0]; }
272
273 /// \brief Retrieve the source range that covers the initialization.
274 SourceRange getRange() const {
Douglas Gregor71d17402009-12-15 00:01:57 +0000275 return SourceRange(Locations[0], Locations[2]);
Douglas Gregor20093b42009-12-09 23:02:17 +0000276 }
277
278 /// \brief Retrieve the location of the equal sign for copy initialization
279 /// (if present).
280 SourceLocation getEqualLoc() const {
281 assert(Kind == SIK_Copy && "Only copy initialization has an '='");
282 return Locations[1];
283 }
284
285 /// \brief Retrieve the source range containing the locations of the open
286 /// and closing parentheses for value and direct initializations.
287 SourceRange getParenRange() const {
288 assert((getKind() == IK_Direct || Kind == SIK_Value) &&
289 "Only direct- and value-initialization have parentheses");
290 return SourceRange(Locations[1], Locations[2]);
291 }
292};
293
294/// \brief Describes the sequence of initializations required to initialize
295/// a given object or reference with a set of arguments.
296class InitializationSequence {
297public:
298 /// \brief Describes the kind of initialization sequence computed.
Douglas Gregor71d17402009-12-15 00:01:57 +0000299 ///
300 /// FIXME: Much of this information is in the initialization steps... why is
301 /// it duplicated here?
Douglas Gregor20093b42009-12-09 23:02:17 +0000302 enum SequenceKind {
303 /// \brief A failed initialization sequence. The failure kind tells what
304 /// happened.
305 FailedSequence = 0,
306
307 /// \brief A dependent initialization, which could not be
308 /// type-checked due to the presence of dependent types or
309 /// dependently-type expressions.
310 DependentSequence,
311
Douglas Gregor4a520a22009-12-14 17:27:33 +0000312 /// \brief A user-defined conversion sequence.
313 UserDefinedConversion,
314
Douglas Gregor51c56d62009-12-14 20:49:26 +0000315 /// \brief A constructor call.
Douglas Gregora6ca6502009-12-14 20:57:13 +0000316 ConstructorInitialization,
Douglas Gregor51c56d62009-12-14 20:49:26 +0000317
Douglas Gregor20093b42009-12-09 23:02:17 +0000318 /// \brief A reference binding.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000319 ReferenceBinding,
320
321 /// \brief List initialization
Douglas Gregor71d17402009-12-15 00:01:57 +0000322 ListInitialization,
323
324 /// \brief Zero-initialization.
Douglas Gregor99a2e602009-12-16 01:38:02 +0000325 ZeroInitialization,
326
327 /// \brief No initialization required.
328 NoInitialization,
329
330 /// \brief Standard conversion sequence.
331 StandardConversion
Douglas Gregor20093b42009-12-09 23:02:17 +0000332 };
333
334 /// \brief Describes the kind of a particular step in an initialization
335 /// sequence.
336 enum StepKind {
337 /// \brief Resolve the address of an overloaded function to a specific
338 /// function declaration.
339 SK_ResolveAddressOfOverloadedFunction,
340 /// \brief Perform a derived-to-base cast, producing an rvalue.
341 SK_CastDerivedToBaseRValue,
342 /// \brief Perform a derived-to-base cast, producing an lvalue.
343 SK_CastDerivedToBaseLValue,
344 /// \brief Reference binding to an lvalue.
345 SK_BindReference,
346 /// \brief Reference binding to a temporary.
347 SK_BindReferenceToTemporary,
348 /// \brief Perform a user-defined conversion, either via a conversion
349 /// function or via a constructor.
350 SK_UserConversion,
351 /// \brief Perform a qualification conversion, producing an rvalue.
352 SK_QualificationConversionRValue,
353 /// \brief Perform a qualification conversion, producing an lvalue.
354 SK_QualificationConversionLValue,
355 /// \brief Perform an implicit conversion sequence.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000356 SK_ConversionSequence,
357 /// \brief Perform list-initialization
Douglas Gregor51c56d62009-12-14 20:49:26 +0000358 SK_ListInitialization,
359 /// \brief Perform initialization via a constructor.
Douglas Gregor71d17402009-12-15 00:01:57 +0000360 SK_ConstructorInitialization,
361 /// \brief Zero-initialize the object
362 SK_ZeroInitialization
Douglas Gregor20093b42009-12-09 23:02:17 +0000363 };
364
365 /// \brief A single step in the initialization sequence.
366 class Step {
367 public:
368 /// \brief The kind of conversion or initialization step we are taking.
369 StepKind Kind;
370
371 // \brief The type that results from this initialization.
372 QualType Type;
373
374 union {
375 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
376 /// SK_UserConversion, the function that the expression should be
377 /// resolved to or the conversion function to call, respectively.
378 FunctionDecl *Function;
379
380 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
381 /// sequence
382 ImplicitConversionSequence *ICS;
383 };
384
385 void Destroy();
386 };
387
388private:
389 /// \brief The kind of initialization sequence computed.
390 enum SequenceKind SequenceKind;
391
392 /// \brief Steps taken by this initialization.
393 llvm::SmallVector<Step, 4> Steps;
394
395public:
396 /// \brief Describes why initialization failed.
397 enum FailureKind {
398 /// \brief Too many initializers provided for a reference.
399 FK_TooManyInitsForReference,
400 /// \brief Array must be initialized with an initializer list.
401 FK_ArrayNeedsInitList,
402 /// \brief Array must be initialized with an initializer list or a
403 /// string literal.
404 FK_ArrayNeedsInitListOrStringLiteral,
405 /// \brief Cannot resolve the address of an overloaded function.
406 FK_AddressOfOverloadFailed,
407 /// \brief Overloading due to reference initialization failed.
408 FK_ReferenceInitOverloadFailed,
409 /// \brief Non-const lvalue reference binding to a temporary.
410 FK_NonConstLValueReferenceBindingToTemporary,
411 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
412 /// type.
413 FK_NonConstLValueReferenceBindingToUnrelated,
414 /// \brief Rvalue reference binding to an lvalue.
415 FK_RValueReferenceBindingToLValue,
416 /// \brief Reference binding drops qualifiers.
417 FK_ReferenceInitDropsQualifiers,
418 /// \brief Reference binding failed.
419 FK_ReferenceInitFailed,
420 /// \brief Implicit conversion failed.
Douglas Gregord87b61f2009-12-10 17:56:55 +0000421 FK_ConversionFailed,
422 /// \brief Too many initializers for scalar
423 FK_TooManyInitsForScalar,
424 /// \brief Reference initialization from an initializer list
425 FK_ReferenceBindingToInitList,
426 /// \brief Initialization of some unused destination type with an
427 /// initializer list.
Douglas Gregor4a520a22009-12-14 17:27:33 +0000428 FK_InitListBadDestinationType,
429 /// \brief Overloading for a user-defined conversion failed.
Douglas Gregor51c56d62009-12-14 20:49:26 +0000430 FK_UserConversionOverloadFailed,
431 /// \brief Overloaded for initialization by constructor failed.
Douglas Gregor99a2e602009-12-16 01:38:02 +0000432 FK_ConstructorOverloadFailed,
433 /// \brief Default-initialization of a 'const' object.
434 FK_DefaultInitOfConst
Douglas Gregor20093b42009-12-09 23:02:17 +0000435 };
436
437private:
438 /// \brief The reason why initialization failued.
439 FailureKind Failure;
440
441 /// \brief The failed result of overload resolution.
442 OverloadingResult FailedOverloadResult;
443
444 /// \brief The candidate set created when initialization failed.
445 OverloadCandidateSet FailedCandidateSet;
446
447public:
448 /// \brief Try to perform initialization of the given entity, creating a
449 /// record of the steps required to perform the initialization.
450 ///
451 /// The generated initialization sequence will either contain enough
452 /// information to diagnose
453 ///
454 /// \param S the semantic analysis object.
455 ///
456 /// \param Entity the entity being initialized.
457 ///
458 /// \param Kind the kind of initialization being performed.
459 ///
460 /// \param Args the argument(s) provided for initialization.
461 ///
462 /// \param NumArgs the number of arguments provided for initialization.
463 InitializationSequence(Sema &S,
464 const InitializedEntity &Entity,
465 const InitializationKind &Kind,
466 Expr **Args,
467 unsigned NumArgs);
468
469 ~InitializationSequence();
470
471 /// \brief Perform the actual initialization of the given entity based on
472 /// the computed initialization sequence.
473 ///
474 /// \param S the semantic analysis object.
475 ///
476 /// \param Entity the entity being initialized.
477 ///
478 /// \param Kind the kind of initialization being performed.
479 ///
480 /// \param Args the argument(s) provided for initialization, ownership of
481 /// which is transfered into the routine.
482 ///
Douglas Gregord87b61f2009-12-10 17:56:55 +0000483 /// \param ResultType if non-NULL, will be set to the type of the
484 /// initialized object, which is the type of the declaration in most
485 /// cases. However, when the initialized object is a variable of
486 /// incomplete array type and the initializer is an initializer
487 /// list, this type will be set to the completed array type.
488 ///
Douglas Gregor20093b42009-12-09 23:02:17 +0000489 /// \returns an expression that performs the actual object initialization, if
490 /// the initialization is well-formed. Otherwise, emits diagnostics
491 /// and returns an invalid expression.
492 Action::OwningExprResult Perform(Sema &S,
493 const InitializedEntity &Entity,
494 const InitializationKind &Kind,
Douglas Gregord87b61f2009-12-10 17:56:55 +0000495 Action::MultiExprArg Args,
496 QualType *ResultType = 0);
Douglas Gregor20093b42009-12-09 23:02:17 +0000497
498 /// \brief Diagnose an potentially-invalid initialization sequence.
499 ///
500 /// \returns true if the initialization sequence was ill-formed,
501 /// false otherwise.
502 bool Diagnose(Sema &S,
503 const InitializedEntity &Entity,
504 const InitializationKind &Kind,
505 Expr **Args, unsigned NumArgs);
506
507 /// \brief Determine the kind of initialization sequence computed.
508 enum SequenceKind getKind() const { return SequenceKind; }
509
510 /// \brief Set the kind of sequence computed.
511 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
512
513 /// \brief Determine whether the initialization sequence is valid.
514 operator bool() const { return SequenceKind != FailedSequence; }
515
516 typedef llvm::SmallVector<Step, 4>::const_iterator step_iterator;
517 step_iterator step_begin() const { return Steps.begin(); }
518 step_iterator step_end() const { return Steps.end(); }
519
520 /// \brief Add a new step in the initialization that resolves the address
521 /// of an overloaded function to a specific function declaration.
522 ///
523 /// \param Function the function to which the overloaded function reference
524 /// resolves.
525 void AddAddressOverloadResolutionStep(FunctionDecl *Function);
526
527 /// \brief Add a new step in the initialization that performs a derived-to-
528 /// base cast.
529 ///
530 /// \param BaseType the base type to which we will be casting.
531 ///
532 /// \param IsLValue true if the result of this cast will be treated as
533 /// an lvalue.
534 void AddDerivedToBaseCastStep(QualType BaseType, bool IsLValue);
535
536 /// \brief Add a new step binding a reference to an object.
537 ///
538 /// \param BindingTemporary true if we are binding a reference to a temporary
539 /// object (thereby extending its lifetime); false if we are binding to an
540 /// lvalue or an lvalue treated as an rvalue.
541 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
542
543 /// \brief Add a new step invoking a conversion function, which is either
544 /// a constructor or a conversion function.
Eli Friedman03981012009-12-11 02:42:07 +0000545 void AddUserConversionStep(FunctionDecl *Function, QualType T);
Douglas Gregor20093b42009-12-09 23:02:17 +0000546
547 /// \brief Add a new step that performs a qualification conversion to the
548 /// given type.
549 void AddQualificationConversionStep(QualType Ty, bool IsLValue);
550
551 /// \brief Add a new step that applies an implicit conversion sequence.
552 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
553 QualType T);
Douglas Gregord87b61f2009-12-10 17:56:55 +0000554
555 /// \brief Add a list-initialiation step
556 void AddListInitializationStep(QualType T);
557
Douglas Gregor71d17402009-12-15 00:01:57 +0000558 /// \brief Add a constructor-initialization step.
Douglas Gregor51c56d62009-12-14 20:49:26 +0000559 void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
560 QualType T);
Douglas Gregor71d17402009-12-15 00:01:57 +0000561
562 /// \brief Add a zero-initialization step.
563 void AddZeroInitializationStep(QualType T);
Douglas Gregor51c56d62009-12-14 20:49:26 +0000564
Douglas Gregor20093b42009-12-09 23:02:17 +0000565 /// \brief Note that this initialization sequence failed.
566 void SetFailed(FailureKind Failure) {
567 SequenceKind = FailedSequence;
568 this->Failure = Failure;
569 }
570
571 /// \brief Note that this initialization sequence failed due to failed
572 /// overload resolution.
573 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
574
575 /// \brief Retrieve a reference to the candidate set when overload
576 /// resolution fails.
577 OverloadCandidateSet &getFailedCandidateSet() {
578 return FailedCandidateSet;
579 }
580
581 /// \brief Determine why initialization failed.
582 FailureKind getFailureKind() const {
583 assert(getKind() == FailedSequence && "Not an initialization failure!");
584 return Failure;
585 }
586};
587
588} // end namespace clang
589
590#endif // LLVM_CLANG_SEMA_INIT_H