SemaExprCXX.cpp revision 1bfe1c47238444b2de13034b6254126386afb3f9
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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 implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "SemaInherit.h"
15#include "Sema.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/Parse/DeclSpec.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Basic/TargetInfo.h"
21#include "llvm/ADT/STLExtras.h"
22using namespace clang;
23
24/// ActOnCXXConversionFunctionExpr - Parse a C++ conversion function
25/// name (e.g., operator void const *) as an expression. This is
26/// very similar to ActOnIdentifierExpr, except that instead of
27/// providing an identifier the parser provides the type of the
28/// conversion function.
29Sema::OwningExprResult
30Sema::ActOnCXXConversionFunctionExpr(Scope *S, SourceLocation OperatorLoc,
31                                     TypeTy *Ty, bool HasTrailingLParen,
32                                     const CXXScopeSpec &SS,
33                                     bool isAddressOfOperand) {
34  QualType ConvType = QualType::getFromOpaquePtr(Ty);
35  CanQualType ConvTypeCanon = Context.getCanonicalType(ConvType);
36  DeclarationName ConvName
37    = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
38  return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
39                                  &SS, isAddressOfOperand);
40}
41
42/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
43/// name (e.g., @c operator+ ) as an expression. This is very
44/// similar to ActOnIdentifierExpr, except that instead of providing
45/// an identifier the parser provides the kind of overloaded
46/// operator that was parsed.
47Sema::OwningExprResult
48Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
49                                     OverloadedOperatorKind Op,
50                                     bool HasTrailingLParen,
51                                     const CXXScopeSpec &SS,
52                                     bool isAddressOfOperand) {
53  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
54  return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS,
55                                  isAddressOfOperand);
56}
57
58/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
59Action::OwningExprResult
60Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
61                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
62  NamespaceDecl *StdNs = GetStdNamespace();
63  if (!StdNs)
64    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
65
66  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
67  Decl *TypeInfoDecl = LookupQualifiedName(StdNs, TypeInfoII, LookupTagName);
68  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
69  if (!TypeInfoRecordDecl)
70    return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
71
72  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
73
74  if (!isType) {
75    // C++0x [expr.typeid]p3:
76    //   When typeid is applied to an expression other than an lvalue of a
77    //   polymorphic class type [...] [the] expression is an unevaluated
78    //   operand.
79
80    // FIXME: if the type of the expression is a class type, the class
81    // shall be completely defined.
82    bool isUnevaluatedOperand = true;
83    Expr *E = static_cast<Expr *>(TyOrExpr);
84    if (E && !E->isTypeDependent() && E->isLvalue(Context) == Expr::LV_Valid) {
85      QualType T = E->getType();
86      if (const RecordType *RecordT = T->getAs<RecordType>()) {
87        CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
88        if (RecordD->isPolymorphic())
89          isUnevaluatedOperand = false;
90      }
91    }
92
93    // If this is an unevaluated operand, clear out the set of declaration
94    // references we have been computing.
95    if (isUnevaluatedOperand)
96      PotentiallyReferencedDeclStack.back().clear();
97  }
98
99  return Owned(new (Context) CXXTypeidExpr(isType, TyOrExpr,
100                                           TypeInfoType.withConst(),
101                                           SourceRange(OpLoc, RParenLoc)));
102}
103
104/// ActOnCXXBoolLiteral - Parse {true,false} literals.
105Action::OwningExprResult
106Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
107  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
108         "Unknown C++ Boolean value!");
109  return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
110                                                Context.BoolTy, OpLoc));
111}
112
113/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
114Action::OwningExprResult
115Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
116  return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
117}
118
119/// ActOnCXXThrow - Parse throw expressions.
120Action::OwningExprResult
121Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprArg E) {
122  Expr *Ex = E.takeAs<Expr>();
123  if (Ex && !Ex->isTypeDependent() && CheckCXXThrowOperand(OpLoc, Ex))
124    return ExprError();
125  return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc));
126}
127
128/// CheckCXXThrowOperand - Validate the operand of a throw.
129bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *&E) {
130  // C++ [except.throw]p3:
131  //   [...] adjusting the type from "array of T" or "function returning T"
132  //   to "pointer to T" or "pointer to function returning T", [...]
133  DefaultFunctionArrayConversion(E);
134
135  //   If the type of the exception would be an incomplete type or a pointer
136  //   to an incomplete type other than (cv) void the program is ill-formed.
137  QualType Ty = E->getType();
138  int isPointer = 0;
139  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
140    Ty = Ptr->getPointeeType();
141    isPointer = 1;
142  }
143  if (!isPointer || !Ty->isVoidType()) {
144    if (RequireCompleteType(ThrowLoc, Ty,
145                            isPointer ? diag::err_throw_incomplete_ptr
146                                      : diag::err_throw_incomplete,
147                            E->getSourceRange(), SourceRange(), QualType()))
148      return true;
149  }
150
151  // FIXME: Construct a temporary here.
152  return false;
153}
154
155Action::OwningExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
156  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
157  /// is a non-lvalue expression whose value is the address of the object for
158  /// which the function is called.
159
160  if (!isa<FunctionDecl>(CurContext))
161    return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
162
163  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
164    if (MD->isInstance())
165      return Owned(new (Context) CXXThisExpr(ThisLoc,
166                                             MD->getThisType(Context)));
167
168  return ExprError(Diag(ThisLoc, diag::err_invalid_this_use));
169}
170
171/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
172/// Can be interpreted either as function-style casting ("int(x)")
173/// or class type construction ("ClassType(x,y,z)")
174/// or creation of a value-initialized type ("int()").
175Action::OwningExprResult
176Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
177                                SourceLocation LParenLoc,
178                                MultiExprArg exprs,
179                                SourceLocation *CommaLocs,
180                                SourceLocation RParenLoc) {
181  assert(TypeRep && "Missing type!");
182  QualType Ty = QualType::getFromOpaquePtr(TypeRep);
183  unsigned NumExprs = exprs.size();
184  Expr **Exprs = (Expr**)exprs.get();
185  SourceLocation TyBeginLoc = TypeRange.getBegin();
186  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
187
188  if (Ty->isDependentType() ||
189      CallExpr::hasAnyTypeDependentArguments(Exprs, NumExprs)) {
190    exprs.release();
191
192    return Owned(CXXUnresolvedConstructExpr::Create(Context,
193                                                    TypeRange.getBegin(), Ty,
194                                                    LParenLoc,
195                                                    Exprs, NumExprs,
196                                                    RParenLoc));
197  }
198
199
200  // C++ [expr.type.conv]p1:
201  // If the expression list is a single expression, the type conversion
202  // expression is equivalent (in definedness, and if defined in meaning) to the
203  // corresponding cast expression.
204  //
205  if (NumExprs == 1) {
206    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
207    if (CheckCastTypes(TypeRange, Ty, Exprs[0], Kind, /*functional-style*/true))
208      return ExprError();
209    exprs.release();
210    return Owned(new (Context) CXXFunctionalCastExpr(Ty.getNonReferenceType(),
211                                                     Ty, TyBeginLoc, Kind,
212                                                     Exprs[0], RParenLoc));
213  }
214
215  if (const RecordType *RT = Ty->getAs<RecordType>()) {
216    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
217
218    // FIXME: We should always create a CXXTemporaryObjectExpr here unless
219    // both the ctor and dtor are trivial.
220    if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
221      CXXConstructorDecl *Constructor
222        = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
223                                             TypeRange.getBegin(),
224                                             SourceRange(TypeRange.getBegin(),
225                                                         RParenLoc),
226                                             DeclarationName(),
227                                             IK_Direct);
228
229      if (!Constructor)
230        return ExprError();
231
232      exprs.release();
233      Expr *E = new (Context) CXXTemporaryObjectExpr(Context, Constructor,
234                                                     Ty, TyBeginLoc, Exprs,
235                                                     NumExprs, RParenLoc);
236      return MaybeBindToTemporary(E);
237    }
238
239    // Fall through to value-initialize an object of class type that
240    // doesn't have a user-declared default constructor.
241  }
242
243  // C++ [expr.type.conv]p1:
244  // If the expression list specifies more than a single value, the type shall
245  // be a class with a suitably declared constructor.
246  //
247  if (NumExprs > 1)
248    return ExprError(Diag(CommaLocs[0],
249                          diag::err_builtin_func_cast_more_than_one_arg)
250      << FullRange);
251
252  assert(NumExprs == 0 && "Expected 0 expressions");
253
254  // C++ [expr.type.conv]p2:
255  // The expression T(), where T is a simple-type-specifier for a non-array
256  // complete object type or the (possibly cv-qualified) void type, creates an
257  // rvalue of the specified type, which is value-initialized.
258  //
259  if (Ty->isArrayType())
260    return ExprError(Diag(TyBeginLoc,
261                          diag::err_value_init_for_array_type) << FullRange);
262  if (!Ty->isDependentType() && !Ty->isVoidType() &&
263      RequireCompleteType(TyBeginLoc, Ty,
264                          diag::err_invalid_incomplete_type_use, FullRange))
265    return ExprError();
266
267  if (RequireNonAbstractType(TyBeginLoc, Ty,
268                             diag::err_allocation_of_abstract_type))
269    return ExprError();
270
271  exprs.release();
272  return Owned(new (Context) CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc));
273}
274
275
276/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
277/// @code new (memory) int[size][4] @endcode
278/// or
279/// @code ::new Foo(23, "hello") @endcode
280/// For the interpretation of this heap of arguments, consult the base version.
281Action::OwningExprResult
282Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
283                  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
284                  SourceLocation PlacementRParen, bool ParenTypeId,
285                  Declarator &D, SourceLocation ConstructorLParen,
286                  MultiExprArg ConstructorArgs,
287                  SourceLocation ConstructorRParen)
288{
289  Expr *ArraySize = 0;
290  unsigned Skip = 0;
291  // If the specified type is an array, unwrap it and save the expression.
292  if (D.getNumTypeObjects() > 0 &&
293      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
294    DeclaratorChunk &Chunk = D.getTypeObject(0);
295    if (Chunk.Arr.hasStatic)
296      return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
297        << D.getSourceRange());
298    if (!Chunk.Arr.NumElts)
299      return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
300        << D.getSourceRange());
301    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
302    Skip = 1;
303  }
304
305  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
306  if (D.isInvalidType())
307    return ExprError();
308
309  // Every dimension shall be of constant size.
310  unsigned i = 1;
311  QualType ElementType = AllocType;
312  while (const ArrayType *Array = Context.getAsArrayType(ElementType)) {
313    if (!Array->isConstantArrayType()) {
314      Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
315        << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
316      return ExprError();
317    }
318    ElementType = Array->getElementType();
319    ++i;
320  }
321
322  return BuildCXXNew(StartLoc, UseGlobal,
323                     PlacementLParen,
324                     move(PlacementArgs),
325                     PlacementRParen,
326                     ParenTypeId,
327                     AllocType,
328                     D.getSourceRange().getBegin(),
329                     D.getSourceRange(),
330                     Owned(ArraySize),
331                     ConstructorLParen,
332                     move(ConstructorArgs),
333                     ConstructorRParen);
334}
335
336Sema::OwningExprResult
337Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
338                  SourceLocation PlacementLParen,
339                  MultiExprArg PlacementArgs,
340                  SourceLocation PlacementRParen,
341                  bool ParenTypeId,
342                  QualType AllocType,
343                  SourceLocation TypeLoc,
344                  SourceRange TypeRange,
345                  ExprArg ArraySizeE,
346                  SourceLocation ConstructorLParen,
347                  MultiExprArg ConstructorArgs,
348                  SourceLocation ConstructorRParen) {
349  if (CheckAllocatedType(AllocType, TypeLoc, TypeRange))
350    return ExprError();
351
352  QualType ResultType = Context.getPointerType(AllocType);
353
354  // That every array dimension except the first is constant was already
355  // checked by the type check above.
356
357  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
358  //   or enumeration type with a non-negative value."
359  Expr *ArraySize = (Expr *)ArraySizeE.get();
360  if (ArraySize && !ArraySize->isTypeDependent()) {
361    QualType SizeType = ArraySize->getType();
362    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
363      return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
364                            diag::err_array_size_not_integral)
365        << SizeType << ArraySize->getSourceRange());
366    // Let's see if this is a constant < 0. If so, we reject it out of hand.
367    // We don't care about special rules, so we tell the machinery it's not
368    // evaluated - it gives us a result in more cases.
369    if (!ArraySize->isValueDependent()) {
370      llvm::APSInt Value;
371      if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
372        if (Value < llvm::APSInt(
373                        llvm::APInt::getNullValue(Value.getBitWidth()), false))
374          return ExprError(Diag(ArraySize->getSourceRange().getBegin(),
375                           diag::err_typecheck_negative_array_size)
376            << ArraySize->getSourceRange());
377      }
378    }
379  }
380
381  FunctionDecl *OperatorNew = 0;
382  FunctionDecl *OperatorDelete = 0;
383  Expr **PlaceArgs = (Expr**)PlacementArgs.get();
384  unsigned NumPlaceArgs = PlacementArgs.size();
385  if (!AllocType->isDependentType() &&
386      !Expr::hasAnyTypeDependentArguments(PlaceArgs, NumPlaceArgs) &&
387      FindAllocationFunctions(StartLoc,
388                              SourceRange(PlacementLParen, PlacementRParen),
389                              UseGlobal, AllocType, ArraySize, PlaceArgs,
390                              NumPlaceArgs, OperatorNew, OperatorDelete))
391    return ExprError();
392
393  bool Init = ConstructorLParen.isValid();
394  // --- Choosing a constructor ---
395  // C++ 5.3.4p15
396  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
397  //   the object is not initialized. If the object, or any part of it, is
398  //   const-qualified, it's an error.
399  // 2) If T is a POD and there's an empty initializer, the object is value-
400  //   initialized.
401  // 3) If T is a POD and there's one initializer argument, the object is copy-
402  //   constructed.
403  // 4) If T is a POD and there's more initializer arguments, it's an error.
404  // 5) If T is not a POD, the initializer arguments are used as constructor
405  //   arguments.
406  //
407  // Or by the C++0x formulation:
408  // 1) If there's no initializer, the object is default-initialized according
409  //    to C++0x rules.
410  // 2) Otherwise, the object is direct-initialized.
411  CXXConstructorDecl *Constructor = 0;
412  Expr **ConsArgs = (Expr**)ConstructorArgs.get();
413  const RecordType *RT;
414  unsigned NumConsArgs = ConstructorArgs.size();
415  if (AllocType->isDependentType()) {
416    // Skip all the checks.
417  } else if ((RT = AllocType->getAs<RecordType>()) &&
418             !AllocType->isAggregateType()) {
419    Constructor = PerformInitializationByConstructor(
420                      AllocType, ConsArgs, NumConsArgs,
421                      TypeLoc,
422                      SourceRange(TypeLoc, ConstructorRParen),
423                      RT->getDecl()->getDeclName(),
424                      NumConsArgs != 0 ? IK_Direct : IK_Default);
425    if (!Constructor)
426      return ExprError();
427  } else {
428    if (!Init) {
429      // FIXME: Check that no subpart is const.
430      if (AllocType.isConstQualified())
431        return ExprError(Diag(StartLoc, diag::err_new_uninitialized_const)
432                           << TypeRange);
433    } else if (NumConsArgs == 0) {
434      // Object is value-initialized. Do nothing.
435    } else if (NumConsArgs == 1) {
436      // Object is direct-initialized.
437      // FIXME: What DeclarationName do we pass in here?
438      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
439                                DeclarationName() /*AllocType.getAsString()*/,
440                                /*DirectInit=*/true))
441        return ExprError();
442    } else {
443      return ExprError(Diag(StartLoc,
444                            diag::err_builtin_direct_init_more_than_one_arg)
445        << SourceRange(ConstructorLParen, ConstructorRParen));
446    }
447  }
448
449  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
450
451  PlacementArgs.release();
452  ConstructorArgs.release();
453  ArraySizeE.release();
454  return Owned(new (Context) CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs,
455                        NumPlaceArgs, ParenTypeId, ArraySize, Constructor, Init,
456                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
457                        StartLoc, Init ? ConstructorRParen : SourceLocation()));
458}
459
460/// CheckAllocatedType - Checks that a type is suitable as the allocated type
461/// in a new-expression.
462/// dimension off and stores the size expression in ArraySize.
463bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
464                              SourceRange R)
465{
466  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
467  //   abstract class type or array thereof.
468  if (AllocType->isFunctionType())
469    return Diag(Loc, diag::err_bad_new_type)
470      << AllocType << 0 << R;
471  else if (AllocType->isReferenceType())
472    return Diag(Loc, diag::err_bad_new_type)
473      << AllocType << 1 << R;
474  else if (!AllocType->isDependentType() &&
475           RequireCompleteType(Loc, AllocType,
476                               diag::err_new_incomplete_type,
477                               R))
478    return true;
479  else if (RequireNonAbstractType(Loc, AllocType,
480                                  diag::err_allocation_of_abstract_type))
481    return true;
482
483  return false;
484}
485
486/// FindAllocationFunctions - Finds the overloads of operator new and delete
487/// that are appropriate for the allocation.
488bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
489                                   bool UseGlobal, QualType AllocType,
490                                   bool IsArray, Expr **PlaceArgs,
491                                   unsigned NumPlaceArgs,
492                                   FunctionDecl *&OperatorNew,
493                                   FunctionDecl *&OperatorDelete)
494{
495  // --- Choosing an allocation function ---
496  // C++ 5.3.4p8 - 14 & 18
497  // 1) If UseGlobal is true, only look in the global scope. Else, also look
498  //   in the scope of the allocated class.
499  // 2) If an array size is given, look for operator new[], else look for
500  //   operator new.
501  // 3) The first argument is always size_t. Append the arguments from the
502  //   placement form.
503  // FIXME: Also find the appropriate delete operator.
504
505  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
506  // We don't care about the actual value of this argument.
507  // FIXME: Should the Sema create the expression and embed it in the syntax
508  // tree? Or should the consumer just recalculate the value?
509  AllocArgs[0] = new (Context) IntegerLiteral(llvm::APInt::getNullValue(
510                                        Context.Target.getPointerWidth(0)),
511                                    Context.getSizeType(),
512                                    SourceLocation());
513  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
514
515  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
516                                        IsArray ? OO_Array_New : OO_New);
517  if (AllocType->isRecordType() && !UseGlobal) {
518    CXXRecordDecl *Record
519      = cast<CXXRecordDecl>(AllocType->getAs<RecordType>()->getDecl());
520    // FIXME: We fail to find inherited overloads.
521    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
522                          AllocArgs.size(), Record, /*AllowMissing=*/true,
523                          OperatorNew))
524      return true;
525  }
526  if (!OperatorNew) {
527    // Didn't find a member overload. Look for a global one.
528    DeclareGlobalNewDelete();
529    DeclContext *TUDecl = Context.getTranslationUnitDecl();
530    if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
531                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
532                          OperatorNew))
533      return true;
534  }
535
536  // FindAllocationOverload can change the passed in arguments, so we need to
537  // copy them back.
538  if (NumPlaceArgs > 0)
539    std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
540
541  // FIXME: This is leaked on error. But so much is currently in Sema that it's
542  // easier to clean it in one go.
543  AllocArgs[0]->Destroy(Context);
544  return false;
545}
546
547/// FindAllocationOverload - Find an fitting overload for the allocation
548/// function in the specified scope.
549bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
550                                  DeclarationName Name, Expr** Args,
551                                  unsigned NumArgs, DeclContext *Ctx,
552                                  bool AllowMissing, FunctionDecl *&Operator)
553{
554  DeclContext::lookup_iterator Alloc, AllocEnd;
555  llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
556  if (Alloc == AllocEnd) {
557    if (AllowMissing)
558      return false;
559    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
560      << Name << Range;
561  }
562
563  OverloadCandidateSet Candidates;
564  for (; Alloc != AllocEnd; ++Alloc) {
565    // Even member operator new/delete are implicitly treated as
566    // static, so don't use AddMemberCandidate.
567    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
568      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
569                           /*SuppressUserConversions=*/false);
570  }
571
572  // Do the resolution.
573  OverloadCandidateSet::iterator Best;
574  switch(BestViableFunction(Candidates, StartLoc, Best)) {
575  case OR_Success: {
576    // Got one!
577    FunctionDecl *FnDecl = Best->Function;
578    // The first argument is size_t, and the first parameter must be size_t,
579    // too. This is checked on declaration and can be assumed. (It can't be
580    // asserted on, though, since invalid decls are left in there.)
581    for (unsigned i = 1; i < NumArgs; ++i) {
582      // FIXME: Passing word to diagnostic.
583      if (PerformCopyInitialization(Args[i],
584                                    FnDecl->getParamDecl(i)->getType(),
585                                    "passing"))
586        return true;
587    }
588    Operator = FnDecl;
589    return false;
590  }
591
592  case OR_No_Viable_Function:
593    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
594      << Name << Range;
595    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
596    return true;
597
598  case OR_Ambiguous:
599    Diag(StartLoc, diag::err_ovl_ambiguous_call)
600      << Name << Range;
601    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
602    return true;
603
604  case OR_Deleted:
605    Diag(StartLoc, diag::err_ovl_deleted_call)
606      << Best->Function->isDeleted()
607      << Name << Range;
608    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
609    return true;
610  }
611  assert(false && "Unreachable, bad result from BestViableFunction");
612  return true;
613}
614
615
616/// DeclareGlobalNewDelete - Declare the global forms of operator new and
617/// delete. These are:
618/// @code
619///   void* operator new(std::size_t) throw(std::bad_alloc);
620///   void* operator new[](std::size_t) throw(std::bad_alloc);
621///   void operator delete(void *) throw();
622///   void operator delete[](void *) throw();
623/// @endcode
624/// Note that the placement and nothrow forms of new are *not* implicitly
625/// declared. Their use requires including \<new\>.
626void Sema::DeclareGlobalNewDelete()
627{
628  if (GlobalNewDeleteDeclared)
629    return;
630  GlobalNewDeleteDeclared = true;
631
632  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
633  QualType SizeT = Context.getSizeType();
634
635  // FIXME: Exception specifications are not added.
636  DeclareGlobalAllocationFunction(
637      Context.DeclarationNames.getCXXOperatorName(OO_New),
638      VoidPtr, SizeT);
639  DeclareGlobalAllocationFunction(
640      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
641      VoidPtr, SizeT);
642  DeclareGlobalAllocationFunction(
643      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
644      Context.VoidTy, VoidPtr);
645  DeclareGlobalAllocationFunction(
646      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
647      Context.VoidTy, VoidPtr);
648}
649
650/// DeclareGlobalAllocationFunction - Declares a single implicit global
651/// allocation function if it doesn't already exist.
652void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
653                                           QualType Return, QualType Argument)
654{
655  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
656
657  // Check if this function is already declared.
658  {
659    DeclContext::lookup_iterator Alloc, AllocEnd;
660    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
661         Alloc != AllocEnd; ++Alloc) {
662      // FIXME: Do we need to check for default arguments here?
663      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
664      if (Func->getNumParams() == 1 &&
665          Context.getCanonicalType(Func->getParamDecl(0)->getType())==Argument)
666        return;
667    }
668  }
669
670  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
671  FunctionDecl *Alloc =
672    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
673                         FnType, FunctionDecl::None, false, true,
674                         SourceLocation());
675  Alloc->setImplicit();
676  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
677                                           0, Argument, VarDecl::None, 0);
678  Alloc->setParams(Context, &Param, 1);
679
680  // FIXME: Also add this declaration to the IdentifierResolver, but
681  // make sure it is at the end of the chain to coincide with the
682  // global scope.
683  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
684}
685
686/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
687/// @code ::delete ptr; @endcode
688/// or
689/// @code delete [] ptr; @endcode
690Action::OwningExprResult
691Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
692                     bool ArrayForm, ExprArg Operand)
693{
694  // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
695  //   having a single conversion function to a pointer type. The result has
696  //   type void."
697  // DR599 amends "pointer type" to "pointer to object type" in both cases.
698
699  Expr *Ex = (Expr *)Operand.get();
700  if (!Ex->isTypeDependent()) {
701    QualType Type = Ex->getType();
702
703    if (Type->isRecordType()) {
704      // FIXME: Find that one conversion function and amend the type.
705    }
706
707    if (!Type->isPointerType())
708      return ExprError(Diag(StartLoc, diag::err_delete_operand)
709        << Type << Ex->getSourceRange());
710
711    QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
712    if (Pointee->isFunctionType() || Pointee->isVoidType())
713      return ExprError(Diag(StartLoc, diag::err_delete_operand)
714        << Type << Ex->getSourceRange());
715    else if (!Pointee->isDependentType() &&
716             RequireCompleteType(StartLoc, Pointee,
717                                 diag::warn_delete_incomplete,
718                                 Ex->getSourceRange()))
719      return ExprError();
720
721    // FIXME: Look up the correct operator delete overload and pass a pointer
722    // along.
723    // FIXME: Check access and ambiguity of operator delete and destructor.
724  }
725
726  Operand.release();
727  return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
728                                           0, Ex, StartLoc));
729}
730
731
732/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
733/// C++ if/switch/while/for statement.
734/// e.g: "if (int x = f()) {...}"
735Action::OwningExprResult
736Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
737                                       Declarator &D,
738                                       SourceLocation EqualLoc,
739                                       ExprArg AssignExprVal) {
740  assert(AssignExprVal.get() && "Null assignment expression");
741
742  // C++ 6.4p2:
743  // The declarator shall not specify a function or an array.
744  // The type-specifier-seq shall not contain typedef and shall not declare a
745  // new class or enumeration.
746
747  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
748         "Parser allowed 'typedef' as storage class of condition decl.");
749
750  TagDecl *OwnedTag = 0;
751  QualType Ty = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag);
752
753  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
754    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
755    // would be created and CXXConditionDeclExpr wants a VarDecl.
756    return ExprError(Diag(StartLoc, diag::err_invalid_use_of_function_type)
757      << SourceRange(StartLoc, EqualLoc));
758  } else if (Ty->isArrayType()) { // ...or an array.
759    Diag(StartLoc, diag::err_invalid_use_of_array_type)
760      << SourceRange(StartLoc, EqualLoc);
761  } else if (OwnedTag && OwnedTag->isDefinition()) {
762    // The type-specifier-seq shall not declare a new class or enumeration.
763    Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
764  }
765
766  DeclPtrTy Dcl = ActOnDeclarator(S, D);
767  if (!Dcl)
768    return ExprError();
769  AddInitializerToDecl(Dcl, move(AssignExprVal), /*DirectInit=*/false);
770
771  // Mark this variable as one that is declared within a conditional.
772  // We know that the decl had to be a VarDecl because that is the only type of
773  // decl that can be assigned and the grammar requires an '='.
774  VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
775  VD->setDeclaredInCondition(true);
776  return Owned(new (Context) CXXConditionDeclExpr(StartLoc, EqualLoc, VD));
777}
778
779/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
780bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
781  // C++ 6.4p4:
782  // The value of a condition that is an initialized declaration in a statement
783  // other than a switch statement is the value of the declared variable
784  // implicitly converted to type bool. If that conversion is ill-formed, the
785  // program is ill-formed.
786  // The value of a condition that is an expression is the value of the
787  // expression, implicitly converted to bool.
788  //
789  return PerformContextuallyConvertToBool(CondExpr);
790}
791
792/// Helper function to determine whether this is the (deprecated) C++
793/// conversion from a string literal to a pointer to non-const char or
794/// non-const wchar_t (for narrow and wide string literals,
795/// respectively).
796bool
797Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
798  // Look inside the implicit cast, if it exists.
799  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
800    From = Cast->getSubExpr();
801
802  // A string literal (2.13.4) that is not a wide string literal can
803  // be converted to an rvalue of type "pointer to char"; a wide
804  // string literal can be converted to an rvalue of type "pointer
805  // to wchar_t" (C++ 4.2p2).
806  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
807    if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
808      if (const BuiltinType *ToPointeeType
809          = ToPtrType->getPointeeType()->getAsBuiltinType()) {
810        // This conversion is considered only when there is an
811        // explicit appropriate pointer target type (C++ 4.2p2).
812        if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
813            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
814             (!StrLit->isWide() &&
815              (ToPointeeType->getKind() == BuiltinType::Char_U ||
816               ToPointeeType->getKind() == BuiltinType::Char_S))))
817          return true;
818      }
819
820  return false;
821}
822
823/// PerformImplicitConversion - Perform an implicit conversion of the
824/// expression From to the type ToType. Returns true if there was an
825/// error, false otherwise. The expression From is replaced with the
826/// converted expression. Flavor is the kind of conversion we're
827/// performing, used in the error message. If @p AllowExplicit,
828/// explicit user-defined conversions are permitted. @p Elidable should be true
829/// when called for copies which may be elided (C++ 12.8p15). C++0x overload
830/// resolution works differently in that case.
831bool
832Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
833                                const char *Flavor, bool AllowExplicit,
834                                bool Elidable)
835{
836  ImplicitConversionSequence ICS;
837  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
838  if (Elidable && getLangOptions().CPlusPlus0x) {
839    ICS = TryImplicitConversion(From, ToType, /*SuppressUserConversions*/false,
840                                AllowExplicit, /*ForceRValue*/true);
841  }
842  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) {
843    ICS = TryImplicitConversion(From, ToType, false, AllowExplicit);
844  }
845  return PerformImplicitConversion(From, ToType, ICS, Flavor);
846}
847
848/// PerformImplicitConversion - Perform an implicit conversion of the
849/// expression From to the type ToType using the pre-computed implicit
850/// conversion sequence ICS. Returns true if there was an error, false
851/// otherwise. The expression From is replaced with the converted
852/// expression. Flavor is the kind of conversion we're performing,
853/// used in the error message.
854bool
855Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
856                                const ImplicitConversionSequence &ICS,
857                                const char* Flavor) {
858  switch (ICS.ConversionKind) {
859  case ImplicitConversionSequence::StandardConversion:
860    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
861      return true;
862    break;
863
864  case ImplicitConversionSequence::UserDefinedConversion:
865    // FIXME: This is, of course, wrong. We'll need to actually call the
866    // constructor or conversion operator, and then cope with the standard
867    // conversions.
868    ImpCastExprToType(From, ToType.getNonReferenceType(),
869                      CastExpr::CK_Unknown,
870                      ToType->isLValueReferenceType());
871    return false;
872
873  case ImplicitConversionSequence::EllipsisConversion:
874    assert(false && "Cannot perform an ellipsis conversion");
875    return false;
876
877  case ImplicitConversionSequence::BadConversion:
878    return true;
879  }
880
881  // Everything went well.
882  return false;
883}
884
885/// PerformImplicitConversion - Perform an implicit conversion of the
886/// expression From to the type ToType by following the standard
887/// conversion sequence SCS. Returns true if there was an error, false
888/// otherwise. The expression From is replaced with the converted
889/// expression. Flavor is the context in which we're performing this
890/// conversion, for use in error messages.
891bool
892Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
893                                const StandardConversionSequence& SCS,
894                                const char *Flavor) {
895  // Overall FIXME: we are recomputing too many types here and doing far too
896  // much extra work. What this means is that we need to keep track of more
897  // information that is computed when we try the implicit conversion initially,
898  // so that we don't need to recompute anything here.
899  QualType FromType = From->getType();
900
901  if (SCS.CopyConstructor) {
902    // FIXME: When can ToType be a reference type?
903    assert(!ToType->isReferenceType());
904
905    // FIXME: Keep track of whether the copy constructor is elidable or not.
906    bool Elidable = (isa<CallExpr>(From) ||
907                     isa<CXXTemporaryObjectExpr>(From));
908    From = BuildCXXConstructExpr(ToType, SCS.CopyConstructor,
909                                 Elidable, &From, 1);
910    return false;
911  }
912
913  // Perform the first implicit conversion.
914  switch (SCS.First) {
915  case ICK_Identity:
916  case ICK_Lvalue_To_Rvalue:
917    // Nothing to do.
918    break;
919
920  case ICK_Array_To_Pointer:
921    FromType = Context.getArrayDecayedType(FromType);
922    ImpCastExprToType(From, FromType, CastExpr::CK_ArrayToPointerDecay);
923    break;
924
925  case ICK_Function_To_Pointer:
926    if (Context.getCanonicalType(FromType) == Context.OverloadTy) {
927      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
928      if (!Fn)
929        return true;
930
931      if (DiagnoseUseOfDecl(Fn, From->getSourceRange().getBegin()))
932        return true;
933
934      FixOverloadedFunctionReference(From, Fn);
935      FromType = From->getType();
936    }
937    FromType = Context.getPointerType(FromType);
938    ImpCastExprToType(From, FromType);
939    break;
940
941  default:
942    assert(false && "Improper first standard conversion");
943    break;
944  }
945
946  // Perform the second implicit conversion
947  switch (SCS.Second) {
948  case ICK_Identity:
949    // Nothing to do.
950    break;
951
952  case ICK_Integral_Promotion:
953  case ICK_Floating_Promotion:
954  case ICK_Complex_Promotion:
955  case ICK_Integral_Conversion:
956  case ICK_Floating_Conversion:
957  case ICK_Complex_Conversion:
958  case ICK_Floating_Integral:
959  case ICK_Complex_Real:
960  case ICK_Compatible_Conversion:
961      // FIXME: Go deeper to get the unqualified type!
962    FromType = ToType.getUnqualifiedType();
963    ImpCastExprToType(From, FromType);
964    break;
965
966  case ICK_Pointer_Conversion:
967    if (SCS.IncompatibleObjC) {
968      // Diagnose incompatible Objective-C conversions
969      Diag(From->getSourceRange().getBegin(),
970           diag::ext_typecheck_convert_incompatible_pointer)
971        << From->getType() << ToType << Flavor
972        << From->getSourceRange();
973    }
974
975    if (CheckPointerConversion(From, ToType))
976      return true;
977    ImpCastExprToType(From, ToType);
978    break;
979
980  case ICK_Pointer_Member:
981    if (CheckMemberPointerConversion(From, ToType))
982      return true;
983    ImpCastExprToType(From, ToType);
984    break;
985
986  case ICK_Boolean_Conversion:
987    FromType = Context.BoolTy;
988    ImpCastExprToType(From, FromType);
989    break;
990
991  default:
992    assert(false && "Improper second standard conversion");
993    break;
994  }
995
996  switch (SCS.Third) {
997  case ICK_Identity:
998    // Nothing to do.
999    break;
1000
1001  case ICK_Qualification:
1002    // FIXME: Not sure about lvalue vs rvalue here in the presence of rvalue
1003    // references.
1004    ImpCastExprToType(From, ToType.getNonReferenceType(),
1005                      CastExpr::CK_Unknown,
1006                      ToType->isLValueReferenceType());
1007    break;
1008
1009  default:
1010    assert(false && "Improper second standard conversion");
1011    break;
1012  }
1013
1014  return false;
1015}
1016
1017Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
1018                                                 SourceLocation KWLoc,
1019                                                 SourceLocation LParen,
1020                                                 TypeTy *Ty,
1021                                                 SourceLocation RParen) {
1022  QualType T = QualType::getFromOpaquePtr(Ty);
1023
1024  // According to http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
1025  // all traits except __is_class, __is_enum and __is_union require a the type
1026  // to be complete.
1027  if (OTT != UTT_IsClass && OTT != UTT_IsEnum && OTT != UTT_IsUnion) {
1028    if (RequireCompleteType(KWLoc, T,
1029                            diag::err_incomplete_type_used_in_type_trait_expr,
1030                            SourceRange(), SourceRange(), T))
1031      return ExprError();
1032  }
1033
1034  // There is no point in eagerly computing the value. The traits are designed
1035  // to be used from type trait templates, so Ty will be a template parameter
1036  // 99% of the time.
1037  return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, OTT, T,
1038                                                RParen, Context.BoolTy));
1039}
1040
1041QualType Sema::CheckPointerToMemberOperands(
1042  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isIndirect)
1043{
1044  const char *OpSpelling = isIndirect ? "->*" : ".*";
1045  // C++ 5.5p2
1046  //   The binary operator .* [p3: ->*] binds its second operand, which shall
1047  //   be of type "pointer to member of T" (where T is a completely-defined
1048  //   class type) [...]
1049  QualType RType = rex->getType();
1050  const MemberPointerType *MemPtr = RType->getAs<MemberPointerType>();
1051  if (!MemPtr) {
1052    Diag(Loc, diag::err_bad_memptr_rhs)
1053      << OpSpelling << RType << rex->getSourceRange();
1054    return QualType();
1055  }
1056
1057  QualType Class(MemPtr->getClass(), 0);
1058
1059  // C++ 5.5p2
1060  //   [...] to its first operand, which shall be of class T or of a class of
1061  //   which T is an unambiguous and accessible base class. [p3: a pointer to
1062  //   such a class]
1063  QualType LType = lex->getType();
1064  if (isIndirect) {
1065    if (const PointerType *Ptr = LType->getAs<PointerType>())
1066      LType = Ptr->getPointeeType().getNonReferenceType();
1067    else {
1068      Diag(Loc, diag::err_bad_memptr_lhs)
1069        << OpSpelling << 1 << LType << lex->getSourceRange();
1070      return QualType();
1071    }
1072  }
1073
1074  if (Context.getCanonicalType(Class).getUnqualifiedType() !=
1075      Context.getCanonicalType(LType).getUnqualifiedType()) {
1076    BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1077                    /*DetectVirtual=*/false);
1078    // FIXME: Would it be useful to print full ambiguity paths, or is that
1079    // overkill?
1080    if (!IsDerivedFrom(LType, Class, Paths) ||
1081        Paths.isAmbiguous(Context.getCanonicalType(Class))) {
1082      Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
1083        << (int)isIndirect << lex->getType() << lex->getSourceRange();
1084      return QualType();
1085    }
1086  }
1087
1088  // C++ 5.5p2
1089  //   The result is an object or a function of the type specified by the
1090  //   second operand.
1091  // The cv qualifiers are the union of those in the pointer and the left side,
1092  // in accordance with 5.5p5 and 5.2.5.
1093  // FIXME: This returns a dereferenced member function pointer as a normal
1094  // function type. However, the only operation valid on such functions is
1095  // calling them. There's also a GCC extension to get a function pointer to the
1096  // thing, which is another complication, because this type - unlike the type
1097  // that is the result of this expression - takes the class as the first
1098  // argument.
1099  // We probably need a "MemberFunctionClosureType" or something like that.
1100  QualType Result = MemPtr->getPointeeType();
1101  if (LType.isConstQualified())
1102    Result.addConst();
1103  if (LType.isVolatileQualified())
1104    Result.addVolatile();
1105  return Result;
1106}
1107
1108/// \brief Get the target type of a standard or user-defined conversion.
1109static QualType TargetType(const ImplicitConversionSequence &ICS) {
1110  assert((ICS.ConversionKind ==
1111              ImplicitConversionSequence::StandardConversion ||
1112          ICS.ConversionKind ==
1113              ImplicitConversionSequence::UserDefinedConversion) &&
1114         "function only valid for standard or user-defined conversions");
1115  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion)
1116    return QualType::getFromOpaquePtr(ICS.Standard.ToTypePtr);
1117  return QualType::getFromOpaquePtr(ICS.UserDefined.After.ToTypePtr);
1118}
1119
1120/// \brief Try to convert a type to another according to C++0x 5.16p3.
1121///
1122/// This is part of the parameter validation for the ? operator. If either
1123/// value operand is a class type, the two operands are attempted to be
1124/// converted to each other. This function does the conversion in one direction.
1125/// It emits a diagnostic and returns true only if it finds an ambiguous
1126/// conversion.
1127static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
1128                                SourceLocation QuestionLoc,
1129                                ImplicitConversionSequence &ICS)
1130{
1131  // C++0x 5.16p3
1132  //   The process for determining whether an operand expression E1 of type T1
1133  //   can be converted to match an operand expression E2 of type T2 is defined
1134  //   as follows:
1135  //   -- If E2 is an lvalue:
1136  if (To->isLvalue(Self.Context) == Expr::LV_Valid) {
1137    //   E1 can be converted to match E2 if E1 can be implicitly converted to
1138    //   type "lvalue reference to T2", subject to the constraint that in the
1139    //   conversion the reference must bind directly to E1.
1140    if (!Self.CheckReferenceInit(From,
1141                            Self.Context.getLValueReferenceType(To->getType()),
1142                            &ICS))
1143    {
1144      assert((ICS.ConversionKind ==
1145                  ImplicitConversionSequence::StandardConversion ||
1146              ICS.ConversionKind ==
1147                  ImplicitConversionSequence::UserDefinedConversion) &&
1148             "expected a definite conversion");
1149      bool DirectBinding =
1150        ICS.ConversionKind == ImplicitConversionSequence::StandardConversion ?
1151        ICS.Standard.DirectBinding : ICS.UserDefined.After.DirectBinding;
1152      if (DirectBinding)
1153        return false;
1154    }
1155  }
1156  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1157  //   -- If E2 is an rvalue, or if the conversion above cannot be done:
1158  //      -- if E1 and E2 have class type, and the underlying class types are
1159  //         the same or one is a base class of the other:
1160  QualType FTy = From->getType();
1161  QualType TTy = To->getType();
1162  const RecordType *FRec = FTy->getAs<RecordType>();
1163  const RecordType *TRec = TTy->getAs<RecordType>();
1164  bool FDerivedFromT = FRec && TRec && Self.IsDerivedFrom(FTy, TTy);
1165  if (FRec && TRec && (FRec == TRec ||
1166        FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
1167    //         E1 can be converted to match E2 if the class of T2 is the
1168    //         same type as, or a base class of, the class of T1, and
1169    //         [cv2 > cv1].
1170    if ((FRec == TRec || FDerivedFromT) && TTy.isAtLeastAsQualifiedAs(FTy)) {
1171      // Could still fail if there's no copy constructor.
1172      // FIXME: Is this a hard error then, or just a conversion failure? The
1173      // standard doesn't say.
1174      ICS = Self.TryCopyInitialization(From, TTy);
1175    }
1176  } else {
1177    //     -- Otherwise: E1 can be converted to match E2 if E1 can be
1178    //        implicitly converted to the type that expression E2 would have
1179    //        if E2 were converted to an rvalue.
1180    // First find the decayed type.
1181    if (TTy->isFunctionType())
1182      TTy = Self.Context.getPointerType(TTy);
1183    else if(TTy->isArrayType())
1184      TTy = Self.Context.getArrayDecayedType(TTy);
1185
1186    // Now try the implicit conversion.
1187    // FIXME: This doesn't detect ambiguities.
1188    ICS = Self.TryImplicitConversion(From, TTy);
1189  }
1190  return false;
1191}
1192
1193/// \brief Try to find a common type for two according to C++0x 5.16p5.
1194///
1195/// This is part of the parameter validation for the ? operator. If either
1196/// value operand is a class type, overload resolution is used to find a
1197/// conversion to a common type.
1198static bool FindConditionalOverload(Sema &Self, Expr *&LHS, Expr *&RHS,
1199                                    SourceLocation Loc) {
1200  Expr *Args[2] = { LHS, RHS };
1201  OverloadCandidateSet CandidateSet;
1202  Self.AddBuiltinOperatorCandidates(OO_Conditional, Args, 2, CandidateSet);
1203
1204  OverloadCandidateSet::iterator Best;
1205  switch (Self.BestViableFunction(CandidateSet, Loc, Best)) {
1206    case Sema::OR_Success:
1207      // We found a match. Perform the conversions on the arguments and move on.
1208      if (Self.PerformImplicitConversion(LHS, Best->BuiltinTypes.ParamTypes[0],
1209                                         Best->Conversions[0], "converting") ||
1210          Self.PerformImplicitConversion(RHS, Best->BuiltinTypes.ParamTypes[1],
1211                                         Best->Conversions[1], "converting"))
1212        break;
1213      return false;
1214
1215    case Sema::OR_No_Viable_Function:
1216      Self.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
1217        << LHS->getType() << RHS->getType()
1218        << LHS->getSourceRange() << RHS->getSourceRange();
1219      return true;
1220
1221    case Sema::OR_Ambiguous:
1222      Self.Diag(Loc, diag::err_conditional_ambiguous_ovl)
1223        << LHS->getType() << RHS->getType()
1224        << LHS->getSourceRange() << RHS->getSourceRange();
1225      // FIXME: Print the possible common types by printing the return types of
1226      // the viable candidates.
1227      break;
1228
1229    case Sema::OR_Deleted:
1230      assert(false && "Conditional operator has only built-in overloads");
1231      break;
1232  }
1233  return true;
1234}
1235
1236/// \brief Perform an "extended" implicit conversion as returned by
1237/// TryClassUnification.
1238///
1239/// TryClassUnification generates ICSs that include reference bindings.
1240/// PerformImplicitConversion is not suitable for this; it chokes if the
1241/// second part of a standard conversion is ICK_DerivedToBase. This function
1242/// handles the reference binding specially.
1243static bool ConvertForConditional(Sema &Self, Expr *&E,
1244                                  const ImplicitConversionSequence &ICS)
1245{
1246  if (ICS.ConversionKind == ImplicitConversionSequence::StandardConversion &&
1247      ICS.Standard.ReferenceBinding) {
1248    assert(ICS.Standard.DirectBinding &&
1249           "TryClassUnification should never generate indirect ref bindings");
1250    // FIXME: CheckReferenceInit should be able to reuse the ICS instead of
1251    // redoing all the work.
1252    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1253                                        TargetType(ICS)));
1254  }
1255  if (ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion &&
1256      ICS.UserDefined.After.ReferenceBinding) {
1257    assert(ICS.UserDefined.After.DirectBinding &&
1258           "TryClassUnification should never generate indirect ref bindings");
1259    return Self.CheckReferenceInit(E, Self.Context.getLValueReferenceType(
1260                                        TargetType(ICS)));
1261  }
1262  if (Self.PerformImplicitConversion(E, TargetType(ICS), ICS, "converting"))
1263    return true;
1264  return false;
1265}
1266
1267/// \brief Check the operands of ?: under C++ semantics.
1268///
1269/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
1270/// extension. In this case, LHS == Cond. (But they're not aliases.)
1271QualType Sema::CXXCheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
1272                                           SourceLocation QuestionLoc) {
1273  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
1274  // interface pointers.
1275
1276  // C++0x 5.16p1
1277  //   The first expression is contextually converted to bool.
1278  if (!Cond->isTypeDependent()) {
1279    if (CheckCXXBooleanCondition(Cond))
1280      return QualType();
1281  }
1282
1283  // Either of the arguments dependent?
1284  if (LHS->isTypeDependent() || RHS->isTypeDependent())
1285    return Context.DependentTy;
1286
1287  // C++0x 5.16p2
1288  //   If either the second or the third operand has type (cv) void, ...
1289  QualType LTy = LHS->getType();
1290  QualType RTy = RHS->getType();
1291  bool LVoid = LTy->isVoidType();
1292  bool RVoid = RTy->isVoidType();
1293  if (LVoid || RVoid) {
1294    //   ... then the [l2r] conversions are performed on the second and third
1295    //   operands ...
1296    DefaultFunctionArrayConversion(LHS);
1297    DefaultFunctionArrayConversion(RHS);
1298    LTy = LHS->getType();
1299    RTy = RHS->getType();
1300
1301    //   ... and one of the following shall hold:
1302    //   -- The second or the third operand (but not both) is a throw-
1303    //      expression; the result is of the type of the other and is an rvalue.
1304    bool LThrow = isa<CXXThrowExpr>(LHS);
1305    bool RThrow = isa<CXXThrowExpr>(RHS);
1306    if (LThrow && !RThrow)
1307      return RTy;
1308    if (RThrow && !LThrow)
1309      return LTy;
1310
1311    //   -- Both the second and third operands have type void; the result is of
1312    //      type void and is an rvalue.
1313    if (LVoid && RVoid)
1314      return Context.VoidTy;
1315
1316    // Neither holds, error.
1317    Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
1318      << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
1319      << LHS->getSourceRange() << RHS->getSourceRange();
1320    return QualType();
1321  }
1322
1323  // Neither is void.
1324
1325  // C++0x 5.16p3
1326  //   Otherwise, if the second and third operand have different types, and
1327  //   either has (cv) class type, and attempt is made to convert each of those
1328  //   operands to the other.
1329  if (Context.getCanonicalType(LTy) != Context.getCanonicalType(RTy) &&
1330      (LTy->isRecordType() || RTy->isRecordType())) {
1331    ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
1332    // These return true if a single direction is already ambiguous.
1333    if (TryClassUnification(*this, LHS, RHS, QuestionLoc, ICSLeftToRight))
1334      return QualType();
1335    if (TryClassUnification(*this, RHS, LHS, QuestionLoc, ICSRightToLeft))
1336      return QualType();
1337
1338    bool HaveL2R = ICSLeftToRight.ConversionKind !=
1339      ImplicitConversionSequence::BadConversion;
1340    bool HaveR2L = ICSRightToLeft.ConversionKind !=
1341      ImplicitConversionSequence::BadConversion;
1342    //   If both can be converted, [...] the program is ill-formed.
1343    if (HaveL2R && HaveR2L) {
1344      Diag(QuestionLoc, diag::err_conditional_ambiguous)
1345        << LTy << RTy << LHS->getSourceRange() << RHS->getSourceRange();
1346      return QualType();
1347    }
1348
1349    //   If exactly one conversion is possible, that conversion is applied to
1350    //   the chosen operand and the converted operands are used in place of the
1351    //   original operands for the remainder of this section.
1352    if (HaveL2R) {
1353      if (ConvertForConditional(*this, LHS, ICSLeftToRight))
1354        return QualType();
1355      LTy = LHS->getType();
1356    } else if (HaveR2L) {
1357      if (ConvertForConditional(*this, RHS, ICSRightToLeft))
1358        return QualType();
1359      RTy = RHS->getType();
1360    }
1361  }
1362
1363  // C++0x 5.16p4
1364  //   If the second and third operands are lvalues and have the same type,
1365  //   the result is of that type [...]
1366  bool Same = Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy);
1367  if (Same && LHS->isLvalue(Context) == Expr::LV_Valid &&
1368      RHS->isLvalue(Context) == Expr::LV_Valid)
1369    return LTy;
1370
1371  // C++0x 5.16p5
1372  //   Otherwise, the result is an rvalue. If the second and third operands
1373  //   do not have the same type, and either has (cv) class type, ...
1374  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
1375    //   ... overload resolution is used to determine the conversions (if any)
1376    //   to be applied to the operands. If the overload resolution fails, the
1377    //   program is ill-formed.
1378    if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
1379      return QualType();
1380  }
1381
1382  // C++0x 5.16p6
1383  //   LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
1384  //   conversions are performed on the second and third operands.
1385  DefaultFunctionArrayConversion(LHS);
1386  DefaultFunctionArrayConversion(RHS);
1387  LTy = LHS->getType();
1388  RTy = RHS->getType();
1389
1390  //   After those conversions, one of the following shall hold:
1391  //   -- The second and third operands have the same type; the result
1392  //      is of that type.
1393  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy))
1394    return LTy;
1395
1396  //   -- The second and third operands have arithmetic or enumeration type;
1397  //      the usual arithmetic conversions are performed to bring them to a
1398  //      common type, and the result is of that type.
1399  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
1400    UsualArithmeticConversions(LHS, RHS);
1401    return LHS->getType();
1402  }
1403
1404  //   -- The second and third operands have pointer type, or one has pointer
1405  //      type and the other is a null pointer constant; pointer conversions
1406  //      and qualification conversions are performed to bring them to their
1407  //      composite pointer type. The result is of the composite pointer type.
1408  QualType Composite = FindCompositePointerType(LHS, RHS);
1409  if (!Composite.isNull())
1410    return Composite;
1411
1412  // Fourth bullet is same for pointers-to-member. However, the possible
1413  // conversions are far more limited: we have null-to-pointer, upcast of
1414  // containing class, and second-level cv-ness.
1415  // cv-ness is not a union, but must match one of the two operands. (Which,
1416  // frankly, is stupid.)
1417  const MemberPointerType *LMemPtr = LTy->getAs<MemberPointerType>();
1418  const MemberPointerType *RMemPtr = RTy->getAs<MemberPointerType>();
1419  if (LMemPtr && RHS->isNullPointerConstant(Context)) {
1420    ImpCastExprToType(RHS, LTy);
1421    return LTy;
1422  }
1423  if (RMemPtr && LHS->isNullPointerConstant(Context)) {
1424    ImpCastExprToType(LHS, RTy);
1425    return RTy;
1426  }
1427  if (LMemPtr && RMemPtr) {
1428    QualType LPointee = LMemPtr->getPointeeType();
1429    QualType RPointee = RMemPtr->getPointeeType();
1430    // First, we check that the unqualified pointee type is the same. If it's
1431    // not, there's no conversion that will unify the two pointers.
1432    if (Context.getCanonicalType(LPointee).getUnqualifiedType() ==
1433        Context.getCanonicalType(RPointee).getUnqualifiedType()) {
1434      // Second, we take the greater of the two cv qualifications. If neither
1435      // is greater than the other, the conversion is not possible.
1436      unsigned Q = LPointee.getCVRQualifiers() | RPointee.getCVRQualifiers();
1437      if (Q == LPointee.getCVRQualifiers() || Q == RPointee.getCVRQualifiers()){
1438        // Third, we check if either of the container classes is derived from
1439        // the other.
1440        QualType LContainer(LMemPtr->getClass(), 0);
1441        QualType RContainer(RMemPtr->getClass(), 0);
1442        QualType MoreDerived;
1443        if (Context.getCanonicalType(LContainer) ==
1444            Context.getCanonicalType(RContainer))
1445          MoreDerived = LContainer;
1446        else if (IsDerivedFrom(LContainer, RContainer))
1447          MoreDerived = LContainer;
1448        else if (IsDerivedFrom(RContainer, LContainer))
1449          MoreDerived = RContainer;
1450
1451        if (!MoreDerived.isNull()) {
1452          // The type 'Q Pointee (MoreDerived::*)' is the common type.
1453          // We don't use ImpCastExprToType here because this could still fail
1454          // for ambiguous or inaccessible conversions.
1455          QualType Common = Context.getMemberPointerType(
1456            LPointee.getQualifiedType(Q), MoreDerived.getTypePtr());
1457          if (PerformImplicitConversion(LHS, Common, "converting"))
1458            return QualType();
1459          if (PerformImplicitConversion(RHS, Common, "converting"))
1460            return QualType();
1461          return Common;
1462        }
1463      }
1464    }
1465  }
1466
1467  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
1468    << LHS->getType() << RHS->getType()
1469    << LHS->getSourceRange() << RHS->getSourceRange();
1470  return QualType();
1471}
1472
1473/// \brief Find a merged pointer type and convert the two expressions to it.
1474///
1475/// This finds the composite pointer type for @p E1 and @p E2 according to
1476/// C++0x 5.9p2. It converts both expressions to this type and returns it.
1477/// It does not emit diagnostics.
1478QualType Sema::FindCompositePointerType(Expr *&E1, Expr *&E2) {
1479  assert(getLangOptions().CPlusPlus && "This function assumes C++");
1480  QualType T1 = E1->getType(), T2 = E2->getType();
1481  if(!T1->isAnyPointerType() && !T2->isAnyPointerType())
1482    return QualType();
1483
1484  // C++0x 5.9p2
1485  //   Pointer conversions and qualification conversions are performed on
1486  //   pointer operands to bring them to their composite pointer type. If
1487  //   one operand is a null pointer constant, the composite pointer type is
1488  //   the type of the other operand.
1489  if (E1->isNullPointerConstant(Context)) {
1490    ImpCastExprToType(E1, T2);
1491    return T2;
1492  }
1493  if (E2->isNullPointerConstant(Context)) {
1494    ImpCastExprToType(E2, T1);
1495    return T1;
1496  }
1497  // Now both have to be pointers.
1498  if(!T1->isPointerType() || !T2->isPointerType())
1499    return QualType();
1500
1501  //   Otherwise, of one of the operands has type "pointer to cv1 void," then
1502  //   the other has type "pointer to cv2 T" and the composite pointer type is
1503  //   "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
1504  //   Otherwise, the composite pointer type is a pointer type similar to the
1505  //   type of one of the operands, with a cv-qualification signature that is
1506  //   the union of the cv-qualification signatures of the operand types.
1507  // In practice, the first part here is redundant; it's subsumed by the second.
1508  // What we do here is, we build the two possible composite types, and try the
1509  // conversions in both directions. If only one works, or if the two composite
1510  // types are the same, we have succeeded.
1511  llvm::SmallVector<unsigned, 4> QualifierUnion;
1512  QualType Composite1 = T1, Composite2 = T2;
1513  const PointerType *Ptr1, *Ptr2;
1514  while ((Ptr1 = Composite1->getAs<PointerType>()) &&
1515         (Ptr2 = Composite2->getAs<PointerType>())) {
1516    Composite1 = Ptr1->getPointeeType();
1517    Composite2 = Ptr2->getPointeeType();
1518    QualifierUnion.push_back(
1519      Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
1520  }
1521  // Rewrap the composites as pointers with the union CVRs.
1522  for (llvm::SmallVector<unsigned, 4>::iterator I = QualifierUnion.begin(),
1523       E = QualifierUnion.end(); I != E; ++I) {
1524    Composite1 = Context.getPointerType(Composite1.getQualifiedType(*I));
1525    Composite2 = Context.getPointerType(Composite2.getQualifiedType(*I));
1526  }
1527
1528  ImplicitConversionSequence E1ToC1 = TryImplicitConversion(E1, Composite1);
1529  ImplicitConversionSequence E2ToC1 = TryImplicitConversion(E2, Composite1);
1530  ImplicitConversionSequence E1ToC2, E2ToC2;
1531  E1ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1532  E2ToC2.ConversionKind = ImplicitConversionSequence::BadConversion;
1533  if (Context.getCanonicalType(Composite1) !=
1534      Context.getCanonicalType(Composite2)) {
1535    E1ToC2 = TryImplicitConversion(E1, Composite2);
1536    E2ToC2 = TryImplicitConversion(E2, Composite2);
1537  }
1538
1539  bool ToC1Viable = E1ToC1.ConversionKind !=
1540                      ImplicitConversionSequence::BadConversion
1541                 && E2ToC1.ConversionKind !=
1542                      ImplicitConversionSequence::BadConversion;
1543  bool ToC2Viable = E1ToC2.ConversionKind !=
1544                      ImplicitConversionSequence::BadConversion
1545                 && E2ToC2.ConversionKind !=
1546                      ImplicitConversionSequence::BadConversion;
1547  if (ToC1Viable && !ToC2Viable) {
1548    if (!PerformImplicitConversion(E1, Composite1, E1ToC1, "converting") &&
1549        !PerformImplicitConversion(E2, Composite1, E2ToC1, "converting"))
1550      return Composite1;
1551  }
1552  if (ToC2Viable && !ToC1Viable) {
1553    if (!PerformImplicitConversion(E1, Composite2, E1ToC2, "converting") &&
1554        !PerformImplicitConversion(E2, Composite2, E2ToC2, "converting"))
1555      return Composite2;
1556  }
1557  return QualType();
1558}
1559
1560Sema::OwningExprResult Sema::MaybeBindToTemporary(Expr *E) {
1561  if (!Context.getLangOptions().CPlusPlus)
1562    return Owned(E);
1563
1564  const RecordType *RT = E->getType()->getAs<RecordType>();
1565  if (!RT)
1566    return Owned(E);
1567
1568  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1569  if (RD->hasTrivialDestructor())
1570    return Owned(E);
1571
1572  CXXTemporary *Temp = CXXTemporary::Create(Context,
1573                                            RD->getDestructor(Context));
1574  ExprTemporaries.push_back(Temp);
1575  if (CXXDestructorDecl *Destructor =
1576        const_cast<CXXDestructorDecl*>(RD->getDestructor(Context)))
1577    MarkDeclarationReferenced(E->getExprLoc(), Destructor);
1578  // FIXME: Add the temporary to the temporaries vector.
1579  return Owned(CXXBindTemporaryExpr::Create(Context, Temp, E));
1580}
1581
1582Expr *Sema::MaybeCreateCXXExprWithTemporaries(Expr *SubExpr,
1583                                              bool ShouldDestroyTemps) {
1584  assert(SubExpr && "sub expression can't be null!");
1585
1586  if (ExprTemporaries.empty())
1587    return SubExpr;
1588
1589  Expr *E = CXXExprWithTemporaries::Create(Context, SubExpr,
1590                                           &ExprTemporaries[0],
1591                                           ExprTemporaries.size(),
1592                                           ShouldDestroyTemps);
1593  ExprTemporaries.clear();
1594
1595  return E;
1596}
1597
1598Sema::OwningExprResult Sema::ActOnFinishFullExpr(ExprArg Arg) {
1599  Expr *FullExpr = Arg.takeAs<Expr>();
1600  if (FullExpr)
1601    FullExpr = MaybeCreateCXXExprWithTemporaries(FullExpr,
1602                                                 /*ShouldDestroyTemps=*/true);
1603
1604  return Owned(FullExpr);
1605}
1606