blob: 85aa421db675641e3833b0c07fec7a1ca46d4dd8 [file] [log] [blame]
Douglas Gregor20093b42009-12-09 23:02:17 +00001//===--- SemaInit.h - 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//
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 {
272 return SourceRange(Locations[0], Locations[1]);
273 }
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.
296 enum SequenceKind {
297 /// \brief A failed initialization sequence. The failure kind tells what
298 /// happened.
299 FailedSequence = 0,
300
301 /// \brief A dependent initialization, which could not be
302 /// type-checked due to the presence of dependent types or
303 /// dependently-type expressions.
304 DependentSequence,
305
306 /// \brief A reference binding.
307 ReferenceBinding
308 };
309
310 /// \brief Describes the kind of a particular step in an initialization
311 /// sequence.
312 enum StepKind {
313 /// \brief Resolve the address of an overloaded function to a specific
314 /// function declaration.
315 SK_ResolveAddressOfOverloadedFunction,
316 /// \brief Perform a derived-to-base cast, producing an rvalue.
317 SK_CastDerivedToBaseRValue,
318 /// \brief Perform a derived-to-base cast, producing an lvalue.
319 SK_CastDerivedToBaseLValue,
320 /// \brief Reference binding to an lvalue.
321 SK_BindReference,
322 /// \brief Reference binding to a temporary.
323 SK_BindReferenceToTemporary,
324 /// \brief Perform a user-defined conversion, either via a conversion
325 /// function or via a constructor.
326 SK_UserConversion,
327 /// \brief Perform a qualification conversion, producing an rvalue.
328 SK_QualificationConversionRValue,
329 /// \brief Perform a qualification conversion, producing an lvalue.
330 SK_QualificationConversionLValue,
331 /// \brief Perform an implicit conversion sequence.
332 SK_ConversionSequence
333 };
334
335 /// \brief A single step in the initialization sequence.
336 class Step {
337 public:
338 /// \brief The kind of conversion or initialization step we are taking.
339 StepKind Kind;
340
341 // \brief The type that results from this initialization.
342 QualType Type;
343
344 union {
345 /// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
346 /// SK_UserConversion, the function that the expression should be
347 /// resolved to or the conversion function to call, respectively.
348 FunctionDecl *Function;
349
350 /// \brief When Kind = SK_ConversionSequence, the implicit conversion
351 /// sequence
352 ImplicitConversionSequence *ICS;
353 };
354
355 void Destroy();
356 };
357
358private:
359 /// \brief The kind of initialization sequence computed.
360 enum SequenceKind SequenceKind;
361
362 /// \brief Steps taken by this initialization.
363 llvm::SmallVector<Step, 4> Steps;
364
365public:
366 /// \brief Describes why initialization failed.
367 enum FailureKind {
368 /// \brief Too many initializers provided for a reference.
369 FK_TooManyInitsForReference,
370 /// \brief Array must be initialized with an initializer list.
371 FK_ArrayNeedsInitList,
372 /// \brief Array must be initialized with an initializer list or a
373 /// string literal.
374 FK_ArrayNeedsInitListOrStringLiteral,
375 /// \brief Cannot resolve the address of an overloaded function.
376 FK_AddressOfOverloadFailed,
377 /// \brief Overloading due to reference initialization failed.
378 FK_ReferenceInitOverloadFailed,
379 /// \brief Non-const lvalue reference binding to a temporary.
380 FK_NonConstLValueReferenceBindingToTemporary,
381 /// \brief Non-const lvalue reference binding to an lvalue of unrelated
382 /// type.
383 FK_NonConstLValueReferenceBindingToUnrelated,
384 /// \brief Rvalue reference binding to an lvalue.
385 FK_RValueReferenceBindingToLValue,
386 /// \brief Reference binding drops qualifiers.
387 FK_ReferenceInitDropsQualifiers,
388 /// \brief Reference binding failed.
389 FK_ReferenceInitFailed,
390 /// \brief Implicit conversion failed.
391 FK_ConversionFailed
392 };
393
394private:
395 /// \brief The reason why initialization failued.
396 FailureKind Failure;
397
398 /// \brief The failed result of overload resolution.
399 OverloadingResult FailedOverloadResult;
400
401 /// \brief The candidate set created when initialization failed.
402 OverloadCandidateSet FailedCandidateSet;
403
404public:
405 /// \brief Try to perform initialization of the given entity, creating a
406 /// record of the steps required to perform the initialization.
407 ///
408 /// The generated initialization sequence will either contain enough
409 /// information to diagnose
410 ///
411 /// \param S the semantic analysis object.
412 ///
413 /// \param Entity the entity being initialized.
414 ///
415 /// \param Kind the kind of initialization being performed.
416 ///
417 /// \param Args the argument(s) provided for initialization.
418 ///
419 /// \param NumArgs the number of arguments provided for initialization.
420 InitializationSequence(Sema &S,
421 const InitializedEntity &Entity,
422 const InitializationKind &Kind,
423 Expr **Args,
424 unsigned NumArgs);
425
426 ~InitializationSequence();
427
428 /// \brief Perform the actual initialization of the given entity based on
429 /// the computed initialization sequence.
430 ///
431 /// \param S the semantic analysis object.
432 ///
433 /// \param Entity the entity being initialized.
434 ///
435 /// \param Kind the kind of initialization being performed.
436 ///
437 /// \param Args the argument(s) provided for initialization, ownership of
438 /// which is transfered into the routine.
439 ///
440 /// \returns an expression that performs the actual object initialization, if
441 /// the initialization is well-formed. Otherwise, emits diagnostics
442 /// and returns an invalid expression.
443 Action::OwningExprResult Perform(Sema &S,
444 const InitializedEntity &Entity,
445 const InitializationKind &Kind,
446 Action::MultiExprArg Args);
447
448 /// \brief Diagnose an potentially-invalid initialization sequence.
449 ///
450 /// \returns true if the initialization sequence was ill-formed,
451 /// false otherwise.
452 bool Diagnose(Sema &S,
453 const InitializedEntity &Entity,
454 const InitializationKind &Kind,
455 Expr **Args, unsigned NumArgs);
456
457 /// \brief Determine the kind of initialization sequence computed.
458 enum SequenceKind getKind() const { return SequenceKind; }
459
460 /// \brief Set the kind of sequence computed.
461 void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
462
463 /// \brief Determine whether the initialization sequence is valid.
464 operator bool() const { return SequenceKind != FailedSequence; }
465
466 typedef llvm::SmallVector<Step, 4>::const_iterator step_iterator;
467 step_iterator step_begin() const { return Steps.begin(); }
468 step_iterator step_end() const { return Steps.end(); }
469
470 /// \brief Add a new step in the initialization that resolves the address
471 /// of an overloaded function to a specific function declaration.
472 ///
473 /// \param Function the function to which the overloaded function reference
474 /// resolves.
475 void AddAddressOverloadResolutionStep(FunctionDecl *Function);
476
477 /// \brief Add a new step in the initialization that performs a derived-to-
478 /// base cast.
479 ///
480 /// \param BaseType the base type to which we will be casting.
481 ///
482 /// \param IsLValue true if the result of this cast will be treated as
483 /// an lvalue.
484 void AddDerivedToBaseCastStep(QualType BaseType, bool IsLValue);
485
486 /// \brief Add a new step binding a reference to an object.
487 ///
488 /// \param BindingTemporary true if we are binding a reference to a temporary
489 /// object (thereby extending its lifetime); false if we are binding to an
490 /// lvalue or an lvalue treated as an rvalue.
491 void AddReferenceBindingStep(QualType T, bool BindingTemporary);
492
493 /// \brief Add a new step invoking a conversion function, which is either
494 /// a constructor or a conversion function.
495 void AddUserConversionStep(FunctionDecl *Function);
496
497 /// \brief Add a new step that performs a qualification conversion to the
498 /// given type.
499 void AddQualificationConversionStep(QualType Ty, bool IsLValue);
500
501 /// \brief Add a new step that applies an implicit conversion sequence.
502 void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
503 QualType T);
504
505 /// \brief Note that this initialization sequence failed.
506 void SetFailed(FailureKind Failure) {
507 SequenceKind = FailedSequence;
508 this->Failure = Failure;
509 }
510
511 /// \brief Note that this initialization sequence failed due to failed
512 /// overload resolution.
513 void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
514
515 /// \brief Retrieve a reference to the candidate set when overload
516 /// resolution fails.
517 OverloadCandidateSet &getFailedCandidateSet() {
518 return FailedCandidateSet;
519 }
520
521 /// \brief Determine why initialization failed.
522 FailureKind getFailureKind() const {
523 assert(getKind() == FailedSequence && "Not an initialization failure!");
524 return Failure;
525 }
526};
527
528} // end namespace clang
529
530#endif // LLVM_CLANG_SEMA_INIT_H