SemaExprCXX.cpp revision af8ad2b4dcc1d03fec720ab2c20d9eaf4754e496
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 "Sema.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/Parse/DeclSpec.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Basic/Diagnostic.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  QualType ConvType = QualType::getFromOpaquePtr(Ty);
34  QualType ConvTypeCanon = Context.getCanonicalType(ConvType);
35  DeclarationName ConvName
36    = Context.DeclarationNames.getCXXConversionFunctionName(ConvTypeCanon);
37  return ActOnDeclarationNameExpr(S, OperatorLoc, ConvName, HasTrailingLParen,
38                                  &SS);
39}
40
41/// ActOnCXXOperatorFunctionIdExpr - Parse a C++ overloaded operator
42/// name (e.g., @c operator+ ) as an expression. This is very
43/// similar to ActOnIdentifierExpr, except that instead of providing
44/// an identifier the parser provides the kind of overloaded
45/// operator that was parsed.
46Sema::OwningExprResult
47Sema::ActOnCXXOperatorFunctionIdExpr(Scope *S, SourceLocation OperatorLoc,
48                                     OverloadedOperatorKind Op,
49                                     bool HasTrailingLParen,
50                                     const CXXScopeSpec &SS) {
51  DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op);
52  return ActOnDeclarationNameExpr(S, OperatorLoc, Name, HasTrailingLParen, &SS);
53}
54
55/// ActOnCXXTypeidOfType - Parse typeid( type-id ).
56Action::ExprResult
57Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
58                     bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
59  const NamespaceDecl *StdNs = GetStdNamespace();
60  if (!StdNs)
61    return Diag(OpLoc, diag::err_need_header_before_typeid);
62
63  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
64  Decl *TypeInfoDecl = LookupDecl(TypeInfoII, Decl::IDNS_Tag,
65                                  0, StdNs, /*createBuiltins=*/false);
66  RecordDecl *TypeInfoRecordDecl = dyn_cast_or_null<RecordDecl>(TypeInfoDecl);
67  if (!TypeInfoRecordDecl)
68    return Diag(OpLoc, diag::err_need_header_before_typeid);
69
70  QualType TypeInfoType = Context.getTypeDeclType(TypeInfoRecordDecl);
71
72  return new CXXTypeidExpr(isType, TyOrExpr, TypeInfoType.withConst(),
73                           SourceRange(OpLoc, RParenLoc));
74}
75
76/// ActOnCXXBoolLiteral - Parse {true,false} literals.
77Action::ExprResult
78Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
79  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
80         "Unknown C++ Boolean value!");
81  return new CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
82}
83
84/// ActOnCXXThrow - Parse throw expressions.
85Action::ExprResult
86Sema::ActOnCXXThrow(SourceLocation OpLoc, ExprTy *E) {
87  return new CXXThrowExpr((Expr*)E, Context.VoidTy, OpLoc);
88}
89
90Action::ExprResult Sema::ActOnCXXThis(SourceLocation ThisLoc) {
91  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
92  /// is a non-lvalue expression whose value is the address of the object for
93  /// which the function is called.
94
95  if (!isa<FunctionDecl>(CurContext)) {
96    Diag(ThisLoc, diag::err_invalid_this_use);
97    return ExprResult(true);
98  }
99
100  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext))
101    if (MD->isInstance())
102      return new CXXThisExpr(ThisLoc, MD->getThisType(Context));
103
104  return Diag(ThisLoc, diag::err_invalid_this_use);
105}
106
107/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
108/// Can be interpreted either as function-style casting ("int(x)")
109/// or class type construction ("ClassType(x,y,z)")
110/// or creation of a value-initialized type ("int()").
111Action::ExprResult
112Sema::ActOnCXXTypeConstructExpr(SourceRange TypeRange, TypeTy *TypeRep,
113                                SourceLocation LParenLoc,
114                                ExprTy **ExprTys, unsigned NumExprs,
115                                SourceLocation *CommaLocs,
116                                SourceLocation RParenLoc) {
117  assert(TypeRep && "Missing type!");
118  QualType Ty = QualType::getFromOpaquePtr(TypeRep);
119  Expr **Exprs = (Expr**)ExprTys;
120  SourceLocation TyBeginLoc = TypeRange.getBegin();
121  SourceRange FullRange = SourceRange(TyBeginLoc, RParenLoc);
122
123  // C++ [expr.type.conv]p1:
124  // If the expression list is a single expression, the type conversion
125  // expression is equivalent (in definedness, and if defined in meaning) to the
126  // corresponding cast expression.
127  //
128  if (NumExprs == 1) {
129    if (CheckCastTypes(TypeRange, Ty, Exprs[0]))
130      return true;
131    return new CXXFunctionalCastExpr(Ty.getNonReferenceType(), Ty, TyBeginLoc,
132                                     Exprs[0], RParenLoc);
133  }
134
135  if (const RecordType *RT = Ty->getAsRecordType()) {
136    CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
137
138    if (NumExprs > 1 || Record->hasUserDeclaredConstructor()) {
139      CXXConstructorDecl *Constructor
140        = PerformInitializationByConstructor(Ty, Exprs, NumExprs,
141                                             TypeRange.getBegin(),
142                                             SourceRange(TypeRange.getBegin(),
143                                                         RParenLoc),
144                                             DeclarationName(),
145                                             IK_Direct);
146
147      if (!Constructor)
148        return true;
149
150      return new CXXTemporaryObjectExpr(Constructor, Ty, TyBeginLoc,
151                                        Exprs, NumExprs, RParenLoc);
152    }
153
154    // Fall through to value-initialize an object of class type that
155    // doesn't have a user-declared default constructor.
156  }
157
158  // C++ [expr.type.conv]p1:
159  // If the expression list specifies more than a single value, the type shall
160  // be a class with a suitably declared constructor.
161  //
162  if (NumExprs > 1)
163    return Diag(CommaLocs[0], diag::err_builtin_func_cast_more_than_one_arg)
164      << FullRange;
165
166  assert(NumExprs == 0 && "Expected 0 expressions");
167
168  // C++ [expr.type.conv]p2:
169  // The expression T(), where T is a simple-type-specifier for a non-array
170  // complete object type or the (possibly cv-qualified) void type, creates an
171  // rvalue of the specified type, which is value-initialized.
172  //
173  if (Ty->isArrayType())
174    return Diag(TyBeginLoc, diag::err_value_init_for_array_type) << FullRange;
175  if (!Ty->isDependentType() && !Ty->isVoidType() &&
176      DiagnoseIncompleteType(TyBeginLoc, Ty,
177                             diag::err_invalid_incomplete_type_use, FullRange))
178    return true;
179
180  return new CXXZeroInitValueExpr(Ty, TyBeginLoc, RParenLoc);
181}
182
183
184/// ActOnCXXNew - Parsed a C++ 'new' expression (C++ 5.3.4), as in e.g.:
185/// @code new (memory) int[size][4] @endcode
186/// or
187/// @code ::new Foo(23, "hello") @endcode
188/// For the interpretation of this heap of arguments, consult the base version.
189Action::ExprResult
190Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
191                  SourceLocation PlacementLParen,
192                  ExprTy **PlacementArgs, unsigned NumPlaceArgs,
193                  SourceLocation PlacementRParen, bool ParenTypeId,
194                  Declarator &D, SourceLocation ConstructorLParen,
195                  ExprTy **ConstructorArgs, unsigned NumConsArgs,
196                  SourceLocation ConstructorRParen)
197{
198  // FIXME: Throughout this function, we have rather bad location information.
199  // Implementing Declarator::getSourceRange() would go a long way toward
200  // fixing that.
201
202  Expr *ArraySize = 0;
203  unsigned Skip = 0;
204  // If the specified type is an array, unwrap it and save the expression.
205  if (D.getNumTypeObjects() > 0 &&
206      D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
207    DeclaratorChunk &Chunk = D.getTypeObject(0);
208    if (Chunk.Arr.hasStatic)
209      return Diag(Chunk.Loc, diag::err_static_illegal_in_new);
210    if (!Chunk.Arr.NumElts)
211      return Diag(Chunk.Loc, diag::err_array_new_needs_size);
212    ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
213    Skip = 1;
214  }
215
216  QualType AllocType = GetTypeForDeclarator(D, /*Scope=*/0, Skip);
217  if (D.getInvalidType())
218    return true;
219
220  if (CheckAllocatedType(AllocType, D))
221    return true;
222
223  QualType ResultType = Context.getPointerType(AllocType);
224
225  // That every array dimension except the first is constant was already
226  // checked by the type check above.
227
228  // C++ 5.3.4p6: "The expression in a direct-new-declarator shall have integral
229  //   or enumeration type with a non-negative value."
230  if (ArraySize) {
231    QualType SizeType = ArraySize->getType();
232    if (!SizeType->isIntegralType() && !SizeType->isEnumeralType())
233      return Diag(ArraySize->getSourceRange().getBegin(),
234                  diag::err_array_size_not_integral)
235        << SizeType << ArraySize->getSourceRange();
236    // Let's see if this is a constant < 0. If so, we reject it out of hand.
237    // We don't care about special rules, so we tell the machinery it's not
238    // evaluated - it gives us a result in more cases.
239    llvm::APSInt Value;
240    if (ArraySize->isIntegerConstantExpr(Value, Context, 0, false)) {
241      if (Value < llvm::APSInt(
242                      llvm::APInt::getNullValue(Value.getBitWidth()), false))
243        return Diag(ArraySize->getSourceRange().getBegin(),
244                    diag::err_typecheck_negative_array_size)
245          << ArraySize->getSourceRange();
246    }
247  }
248
249  FunctionDecl *OperatorNew = 0;
250  FunctionDecl *OperatorDelete = 0;
251  Expr **PlaceArgs = (Expr**)PlacementArgs;
252  if (FindAllocationFunctions(StartLoc, UseGlobal, AllocType, ArraySize,
253                              PlaceArgs, NumPlaceArgs, OperatorNew,
254                              OperatorDelete))
255    return true;
256
257  bool Init = ConstructorLParen.isValid();
258  // --- Choosing a constructor ---
259  // C++ 5.3.4p15
260  // 1) If T is a POD and there's no initializer (ConstructorLParen is invalid)
261  //   the object is not initialized. If the object, or any part of it, is
262  //   const-qualified, it's an error.
263  // 2) If T is a POD and there's an empty initializer, the object is value-
264  //   initialized.
265  // 3) If T is a POD and there's one initializer argument, the object is copy-
266  //   constructed.
267  // 4) If T is a POD and there's more initializer arguments, it's an error.
268  // 5) If T is not a POD, the initializer arguments are used as constructor
269  //   arguments.
270  //
271  // Or by the C++0x formulation:
272  // 1) If there's no initializer, the object is default-initialized according
273  //    to C++0x rules.
274  // 2) Otherwise, the object is direct-initialized.
275  CXXConstructorDecl *Constructor = 0;
276  Expr **ConsArgs = (Expr**)ConstructorArgs;
277  if (const RecordType *RT = AllocType->getAsRecordType()) {
278    // FIXME: This is incorrect for when there is an empty initializer and
279    // no user-defined constructor. Must zero-initialize, not default-construct.
280    Constructor = PerformInitializationByConstructor(
281                      AllocType, ConsArgs, NumConsArgs,
282                      D.getDeclSpec().getSourceRange().getBegin(),
283                      SourceRange(D.getDeclSpec().getSourceRange().getBegin(),
284                                  ConstructorRParen),
285                      RT->getDecl()->getDeclName(),
286                      NumConsArgs != 0 ? IK_Direct : IK_Default);
287    if (!Constructor)
288      return true;
289  } else {
290    if (!Init) {
291      // FIXME: Check that no subpart is const.
292      if (AllocType.isConstQualified()) {
293        Diag(StartLoc, diag::err_new_uninitialized_const)
294          << D.getSourceRange();
295        return true;
296      }
297    } else if (NumConsArgs == 0) {
298      // Object is value-initialized. Do nothing.
299    } else if (NumConsArgs == 1) {
300      // Object is direct-initialized.
301      // FIXME: WHAT DeclarationName do we pass in here?
302      if (CheckInitializerTypes(ConsArgs[0], AllocType, StartLoc,
303                                DeclarationName() /*AllocType.getAsString()*/,
304                                /*DirectInit=*/true))
305        return true;
306    } else {
307      Diag(StartLoc, diag::err_builtin_direct_init_more_than_one_arg)
308        << SourceRange(ConstructorLParen, ConstructorRParen);
309    }
310  }
311
312  // FIXME: Also check that the destructor is accessible. (C++ 5.3.4p16)
313
314  return new CXXNewExpr(UseGlobal, OperatorNew, PlaceArgs, NumPlaceArgs,
315                        ParenTypeId, ArraySize, Constructor, Init,
316                        ConsArgs, NumConsArgs, OperatorDelete, ResultType,
317                        StartLoc, Init ? ConstructorRParen : SourceLocation());
318}
319
320/// CheckAllocatedType - Checks that a type is suitable as the allocated type
321/// in a new-expression.
322/// dimension off and stores the size expression in ArraySize.
323bool Sema::CheckAllocatedType(QualType AllocType, const Declarator &D)
324{
325  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
326  //   abstract class type or array thereof.
327  // FIXME: We don't have abstract types yet.
328  // FIXME: Under C++ semantics, an incomplete object type is still an object
329  // type. This code assumes the C semantics, where it's not.
330  if (!AllocType->isObjectType()) {
331    unsigned type; // For the select in the message.
332    if (AllocType->isFunctionType()) {
333      type = 0;
334    } else if(AllocType->isIncompleteType()) {
335      type = 1;
336    } else {
337      assert(AllocType->isReferenceType() && "What else could it be?");
338      type = 2;
339    }
340    SourceRange TyR = D.getDeclSpec().getSourceRange();
341    // FIXME: This is very much a guess and won't work for, e.g., pointers.
342    if (D.getNumTypeObjects() > 0)
343      TyR.setEnd(D.getTypeObject(0).Loc);
344    Diag(TyR.getBegin(), diag::err_bad_new_type)
345      << AllocType.getAsString() << type << TyR;
346    return true;
347  }
348
349  // Every dimension shall be of constant size.
350  unsigned i = 1;
351  while (const ArrayType *Array = Context.getAsArrayType(AllocType)) {
352    if (!Array->isConstantArrayType()) {
353      Diag(D.getTypeObject(i).Loc, diag::err_new_array_nonconst)
354        << static_cast<Expr*>(D.getTypeObject(i).Arr.NumElts)->getSourceRange();
355      return true;
356    }
357    AllocType = Array->getElementType();
358    ++i;
359  }
360
361  return false;
362}
363
364/// FindAllocationFunctions - Finds the overloads of operator new and delete
365/// that are appropriate for the allocation.
366bool Sema::FindAllocationFunctions(SourceLocation StartLoc, bool UseGlobal,
367                                   QualType AllocType, bool IsArray,
368                                   Expr **PlaceArgs, unsigned NumPlaceArgs,
369                                   FunctionDecl *&OperatorNew,
370                                   FunctionDecl *&OperatorDelete)
371{
372  // --- Choosing an allocation function ---
373  // C++ 5.3.4p8 - 14 & 18
374  // 1) If UseGlobal is true, only look in the global scope. Else, also look
375  //   in the scope of the allocated class.
376  // 2) If an array size is given, look for operator new[], else look for
377  //   operator new.
378  // 3) The first argument is always size_t. Append the arguments from the
379  //   placement form.
380  // FIXME: Also find the appropriate delete operator.
381
382  llvm::SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
383  // We don't care about the actual value of this argument.
384  // FIXME: Should the Sema create the expression and embed it in the syntax
385  // tree? Or should the consumer just recalculate the value?
386  AllocArgs[0] = new IntegerLiteral(llvm::APInt::getNullValue(
387                                        Context.Target.getPointerWidth(0)),
388                                    Context.getSizeType(),
389                                    SourceLocation());
390  std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
391
392  DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
393                                        IsArray ? OO_Array_New : OO_New);
394  if (AllocType->isRecordType() && !UseGlobal) {
395    CXXRecordDecl *Record = cast<CXXRecordType>(AllocType->getAsRecordType())
396                                ->getDecl();
397    // FIXME: We fail to find inherited overloads.
398    if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
399                          AllocArgs.size(), Record, /*AllowMissing=*/true,
400                          OperatorNew))
401      return true;
402  }
403  if (!OperatorNew) {
404    // Didn't find a member overload. Look for a global one.
405    DeclareGlobalNewDelete();
406    DeclContext *TUDecl = Context.getTranslationUnitDecl();
407    if (FindAllocationOverload(StartLoc, NewName, &AllocArgs[0],
408                          AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
409                          OperatorNew))
410      return true;
411  }
412
413  // FIXME: This is leaked on error. But so much is currently in Sema that it's
414  // easier to clean it in one go.
415  AllocArgs[0]->Destroy(Context);
416  return false;
417}
418
419/// FindAllocationOverload - Find an fitting overload for the allocation
420/// function in the specified scope.
421bool Sema::FindAllocationOverload(SourceLocation StartLoc, DeclarationName Name,
422                                  Expr** Args, unsigned NumArgs,
423                                  DeclContext *Ctx, bool AllowMissing,
424                                  FunctionDecl *&Operator)
425{
426  DeclContext::lookup_iterator Alloc, AllocEnd;
427  llvm::tie(Alloc, AllocEnd) = Ctx->lookup(Name);
428  if (Alloc == AllocEnd) {
429    if (AllowMissing)
430      return false;
431    // FIXME: Bad location information.
432    return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
433      << Name << 0;
434  }
435
436  OverloadCandidateSet Candidates;
437  for (; Alloc != AllocEnd; ++Alloc) {
438    // Even member operator new/delete are implicitly treated as
439    // static, so don't use AddMemberCandidate.
440    if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*Alloc))
441      AddOverloadCandidate(Fn, Args, NumArgs, Candidates,
442                           /*SuppressUserConversions=*/false);
443  }
444
445  // Do the resolution.
446  OverloadCandidateSet::iterator Best;
447  switch(BestViableFunction(Candidates, Best)) {
448  case OR_Success: {
449    // Got one!
450    FunctionDecl *FnDecl = Best->Function;
451    // The first argument is size_t, and the first parameter must be size_t,
452    // too. This is checked on declaration and can be assumed. (It can't be
453    // asserted on, though, since invalid decls are left in there.)
454    for (unsigned i = 1; i < NumArgs; ++i) {
455      // FIXME: Passing word to diagnostic.
456      if (PerformCopyInitialization(Args[i-1],
457                                    FnDecl->getParamDecl(i)->getType(),
458                                    "passing"))
459        return true;
460    }
461    Operator = FnDecl;
462    return false;
463  }
464
465  case OR_No_Viable_Function:
466    if (AllowMissing)
467      return false;
468    // FIXME: Bad location information.
469    Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
470      << Name << (unsigned)Candidates.size();
471    PrintOverloadCandidates(Candidates, /*OnlyViable=*/false);
472    return true;
473
474  case OR_Ambiguous:
475    // FIXME: Bad location information.
476    Diag(StartLoc, diag::err_ovl_ambiguous_call)
477      << Name;
478    PrintOverloadCandidates(Candidates, /*OnlyViable=*/true);
479    return true;
480  }
481  assert(false && "Unreachable, bad result from BestViableFunction");
482  return true;
483}
484
485
486/// DeclareGlobalNewDelete - Declare the global forms of operator new and
487/// delete. These are:
488/// @code
489///   void* operator new(std::size_t) throw(std::bad_alloc);
490///   void* operator new[](std::size_t) throw(std::bad_alloc);
491///   void operator delete(void *) throw();
492///   void operator delete[](void *) throw();
493/// @endcode
494/// Note that the placement and nothrow forms of new are *not* implicitly
495/// declared. Their use requires including \<new\>.
496void Sema::DeclareGlobalNewDelete()
497{
498  if (GlobalNewDeleteDeclared)
499    return;
500  GlobalNewDeleteDeclared = true;
501
502  QualType VoidPtr = Context.getPointerType(Context.VoidTy);
503  QualType SizeT = Context.getSizeType();
504
505  // FIXME: Exception specifications are not added.
506  DeclareGlobalAllocationFunction(
507      Context.DeclarationNames.getCXXOperatorName(OO_New),
508      VoidPtr, SizeT);
509  DeclareGlobalAllocationFunction(
510      Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
511      VoidPtr, SizeT);
512  DeclareGlobalAllocationFunction(
513      Context.DeclarationNames.getCXXOperatorName(OO_Delete),
514      Context.VoidTy, VoidPtr);
515  DeclareGlobalAllocationFunction(
516      Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
517      Context.VoidTy, VoidPtr);
518}
519
520/// DeclareGlobalAllocationFunction - Declares a single implicit global
521/// allocation function if it doesn't already exist.
522void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
523                                           QualType Return, QualType Argument)
524{
525  DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
526
527  // Check if this function is already declared.
528  {
529    DeclContext::lookup_iterator Alloc, AllocEnd;
530    for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
531         Alloc != AllocEnd; ++Alloc) {
532      // FIXME: Do we need to check for default arguments here?
533      FunctionDecl *Func = cast<FunctionDecl>(*Alloc);
534      if (Func->getNumParams() == 1 &&
535          Context.getCanonicalType(Func->getParamDecl(0)->getType()) == Argument)
536        return;
537    }
538  }
539
540  QualType FnType = Context.getFunctionType(Return, &Argument, 1, false, 0);
541  FunctionDecl *Alloc =
542    FunctionDecl::Create(Context, GlobalCtx, SourceLocation(), Name,
543                         FnType, FunctionDecl::None, false,
544                         SourceLocation());
545  Alloc->setImplicit();
546  ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
547                                           0, Argument, VarDecl::None, 0);
548  Alloc->setParams(Context, &Param, 1);
549
550  // FIXME: Also add this declaration to the IdentifierResolver, but
551  // make sure it is at the end of the chain to coincide with the
552  // global scope.
553  ((DeclContext *)TUScope->getEntity())->addDecl(Alloc);
554}
555
556/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
557/// @code ::delete ptr; @endcode
558/// or
559/// @code delete [] ptr; @endcode
560Action::ExprResult
561Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
562                     bool ArrayForm, ExprTy *Operand)
563{
564  // C++ 5.3.5p1: "The operand shall have a pointer type, or a class type
565  //   having a single conversion function to a pointer type. The result has
566  //   type void."
567  // DR599 amends "pointer type" to "pointer to object type" in both cases.
568
569  Expr *Ex = (Expr *)Operand;
570  QualType Type = Ex->getType();
571
572  if (Type->isRecordType()) {
573    // FIXME: Find that one conversion function and amend the type.
574  }
575
576  if (!Type->isPointerType()) {
577    Diag(StartLoc, diag::err_delete_operand) << Type << Ex->getSourceRange();
578    return true;
579  }
580
581  QualType Pointee = Type->getAsPointerType()->getPointeeType();
582  if (!Pointee->isVoidType() &&
583      DiagnoseIncompleteType(StartLoc, Pointee, diag::warn_delete_incomplete,
584                             Ex->getSourceRange()))
585    return true;
586  else if (!Pointee->isObjectType()) {
587    Diag(StartLoc, diag::err_delete_operand)
588      << Type << Ex->getSourceRange();
589    return true;
590  }
591
592  // FIXME: Look up the correct operator delete overload and pass a pointer
593  // along.
594  // FIXME: Check access and ambiguity of operator delete and destructor.
595
596  return new CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm, 0, Ex,
597                           StartLoc);
598}
599
600
601/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
602/// C++ if/switch/while/for statement.
603/// e.g: "if (int x = f()) {...}"
604Action::ExprResult
605Sema::ActOnCXXConditionDeclarationExpr(Scope *S, SourceLocation StartLoc,
606                                       Declarator &D,
607                                       SourceLocation EqualLoc,
608                                       ExprTy *AssignExprVal) {
609  assert(AssignExprVal && "Null assignment expression");
610
611  // C++ 6.4p2:
612  // The declarator shall not specify a function or an array.
613  // The type-specifier-seq shall not contain typedef and shall not declare a
614  // new class or enumeration.
615
616  assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
617         "Parser allowed 'typedef' as storage class of condition decl.");
618
619  QualType Ty = GetTypeForDeclarator(D, S);
620
621  if (Ty->isFunctionType()) { // The declarator shall not specify a function...
622    // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
623    // would be created and CXXConditionDeclExpr wants a VarDecl.
624    return Diag(StartLoc, diag::err_invalid_use_of_function_type)
625      << SourceRange(StartLoc, EqualLoc);
626  } else if (Ty->isArrayType()) { // ...or an array.
627    Diag(StartLoc, diag::err_invalid_use_of_array_type)
628      << SourceRange(StartLoc, EqualLoc);
629  } else if (const RecordType *RT = Ty->getAsRecordType()) {
630    RecordDecl *RD = RT->getDecl();
631    // The type-specifier-seq shall not declare a new class...
632    if (RD->isDefinition() && (RD->getIdentifier() == 0 || S->isDeclScope(RD)))
633      Diag(RD->getLocation(), diag::err_type_defined_in_condition);
634  } else if (const EnumType *ET = Ty->getAsEnumType()) {
635    EnumDecl *ED = ET->getDecl();
636    // ...or enumeration.
637    if (ED->isDefinition() && (ED->getIdentifier() == 0 || S->isDeclScope(ED)))
638      Diag(ED->getLocation(), diag::err_type_defined_in_condition);
639  }
640
641  DeclTy *Dcl = ActOnDeclarator(S, D, 0);
642  if (!Dcl)
643    return true;
644  AddInitializerToDecl(Dcl, ExprArg(*this, AssignExprVal));
645
646  // Mark this variable as one that is declared within a conditional.
647  if (VarDecl *VD = dyn_cast<VarDecl>((Decl *)Dcl))
648    VD->setDeclaredInCondition(true);
649
650  return new CXXConditionDeclExpr(StartLoc, EqualLoc,
651                                       cast<VarDecl>(static_cast<Decl *>(Dcl)));
652}
653
654/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
655bool Sema::CheckCXXBooleanCondition(Expr *&CondExpr) {
656  // C++ 6.4p4:
657  // The value of a condition that is an initialized declaration in a statement
658  // other than a switch statement is the value of the declared variable
659  // implicitly converted to type bool. If that conversion is ill-formed, the
660  // program is ill-formed.
661  // The value of a condition that is an expression is the value of the
662  // expression, implicitly converted to bool.
663  //
664  return PerformContextuallyConvertToBool(CondExpr);
665}
666
667/// Helper function to determine whether this is the (deprecated) C++
668/// conversion from a string literal to a pointer to non-const char or
669/// non-const wchar_t (for narrow and wide string literals,
670/// respectively).
671bool
672Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
673  // Look inside the implicit cast, if it exists.
674  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
675    From = Cast->getSubExpr();
676
677  // A string literal (2.13.4) that is not a wide string literal can
678  // be converted to an rvalue of type "pointer to char"; a wide
679  // string literal can be converted to an rvalue of type "pointer
680  // to wchar_t" (C++ 4.2p2).
681  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From))
682    if (const PointerType *ToPtrType = ToType->getAsPointerType())
683      if (const BuiltinType *ToPointeeType
684          = ToPtrType->getPointeeType()->getAsBuiltinType()) {
685        // This conversion is considered only when there is an
686        // explicit appropriate pointer target type (C++ 4.2p2).
687        if (ToPtrType->getPointeeType().getCVRQualifiers() == 0 &&
688            ((StrLit->isWide() && ToPointeeType->isWideCharType()) ||
689             (!StrLit->isWide() &&
690              (ToPointeeType->getKind() == BuiltinType::Char_U ||
691               ToPointeeType->getKind() == BuiltinType::Char_S))))
692          return true;
693      }
694
695  return false;
696}
697
698/// PerformImplicitConversion - Perform an implicit conversion of the
699/// expression From to the type ToType. Returns true if there was an
700/// error, false otherwise. The expression From is replaced with the
701/// converted expression. Flavor is the kind of conversion we're
702/// performing, used in the error message. If @p AllowExplicit,
703/// explicit user-defined conversions are permitted.
704bool
705Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
706                                const char *Flavor, bool AllowExplicit)
707{
708  ImplicitConversionSequence ICS = TryImplicitConversion(From, ToType, false,
709                                                         AllowExplicit);
710  return PerformImplicitConversion(From, ToType, ICS, Flavor);
711}
712
713/// PerformImplicitConversion - Perform an implicit conversion of the
714/// expression From to the type ToType using the pre-computed implicit
715/// conversion sequence ICS. Returns true if there was an error, false
716/// otherwise. The expression From is replaced with the converted
717/// expression. Flavor is the kind of conversion we're performing,
718/// used in the error message.
719bool
720Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
721                                const ImplicitConversionSequence &ICS,
722                                const char* Flavor) {
723  switch (ICS.ConversionKind) {
724  case ImplicitConversionSequence::StandardConversion:
725    if (PerformImplicitConversion(From, ToType, ICS.Standard, Flavor))
726      return true;
727    break;
728
729  case ImplicitConversionSequence::UserDefinedConversion:
730    // FIXME: This is, of course, wrong. We'll need to actually call
731    // the constructor or conversion operator, and then cope with the
732    // standard conversions.
733    ImpCastExprToType(From, ToType.getNonReferenceType(),
734                      ToType->isReferenceType());
735    return false;
736
737  case ImplicitConversionSequence::EllipsisConversion:
738    assert(false && "Cannot perform an ellipsis conversion");
739    return false;
740
741  case ImplicitConversionSequence::BadConversion:
742    return true;
743  }
744
745  // Everything went well.
746  return false;
747}
748
749/// PerformImplicitConversion - Perform an implicit conversion of the
750/// expression From to the type ToType by following the standard
751/// conversion sequence SCS. Returns true if there was an error, false
752/// otherwise. The expression From is replaced with the converted
753/// expression. Flavor is the context in which we're performing this
754/// conversion, for use in error messages.
755bool
756Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
757                                const StandardConversionSequence& SCS,
758                                const char *Flavor) {
759  // Overall FIXME: we are recomputing too many types here and doing
760  // far too much extra work. What this means is that we need to keep
761  // track of more information that is computed when we try the
762  // implicit conversion initially, so that we don't need to recompute
763  // anything here.
764  QualType FromType = From->getType();
765
766  if (SCS.CopyConstructor) {
767    // FIXME: Create a temporary object by calling the copy
768    // constructor.
769    ImpCastExprToType(From, ToType.getNonReferenceType(),
770                      ToType->isReferenceType());
771    return false;
772  }
773
774  // Perform the first implicit conversion.
775  switch (SCS.First) {
776  case ICK_Identity:
777  case ICK_Lvalue_To_Rvalue:
778    // Nothing to do.
779    break;
780
781  case ICK_Array_To_Pointer:
782    if (FromType->isOverloadType()) {
783      FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, true);
784      if (!Fn)
785        return true;
786
787      FixOverloadedFunctionReference(From, Fn);
788      FromType = From->getType();
789    } else {
790      FromType = Context.getArrayDecayedType(FromType);
791    }
792    ImpCastExprToType(From, FromType);
793    break;
794
795  case ICK_Function_To_Pointer:
796    FromType = Context.getPointerType(FromType);
797    ImpCastExprToType(From, FromType);
798    break;
799
800  default:
801    assert(false && "Improper first standard conversion");
802    break;
803  }
804
805  // Perform the second implicit conversion
806  switch (SCS.Second) {
807  case ICK_Identity:
808    // Nothing to do.
809    break;
810
811  case ICK_Integral_Promotion:
812  case ICK_Floating_Promotion:
813  case ICK_Integral_Conversion:
814  case ICK_Floating_Conversion:
815  case ICK_Floating_Integral:
816    FromType = ToType.getUnqualifiedType();
817    ImpCastExprToType(From, FromType);
818    break;
819
820  case ICK_Pointer_Conversion:
821    if (SCS.IncompatibleObjC) {
822      // Diagnose incompatible Objective-C conversions
823      Diag(From->getSourceRange().getBegin(),
824           diag::ext_typecheck_convert_incompatible_pointer)
825        << From->getType() << ToType << Flavor
826        << From->getSourceRange();
827    }
828
829    if (CheckPointerConversion(From, ToType))
830      return true;
831    ImpCastExprToType(From, ToType);
832    break;
833
834  case ICK_Pointer_Member:
835    // FIXME: Implement pointer-to-member conversions.
836    assert(false && "Pointer-to-member conversions are unsupported");
837    break;
838
839  case ICK_Boolean_Conversion:
840    FromType = Context.BoolTy;
841    ImpCastExprToType(From, FromType);
842    break;
843
844  default:
845    assert(false && "Improper second standard conversion");
846    break;
847  }
848
849  switch (SCS.Third) {
850  case ICK_Identity:
851    // Nothing to do.
852    break;
853
854  case ICK_Qualification:
855    ImpCastExprToType(From, ToType.getNonReferenceType(),
856                      ToType->isReferenceType());
857    break;
858
859  default:
860    assert(false && "Improper second standard conversion");
861    break;
862  }
863
864  return false;
865}
866
867Sema::OwningExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait OTT,
868                                                 SourceLocation KWLoc,
869                                                 SourceLocation LParen,
870                                                 TypeTy *Ty,
871                                                 SourceLocation RParen) {
872  // FIXME: Some of the type traits have requirements. Interestingly, only the
873  // __is_base_of requirement is explicitly stated to be diagnosed. Indeed,
874  // G++ accepts __is_pod(Incomplete) without complaints, and claims that the
875  // type is indeed a POD.
876
877  // There is no point in eagerly computing the value. The traits are designed
878  // to be used from type trait templates, so Ty will be a template parameter
879  // 99% of the time.
880  return Owned(new UnaryTypeTraitExpr(KWLoc, OTT,
881                                      QualType::getFromOpaquePtr(Ty),
882                                      RParen, Context.BoolTy));
883}
884