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