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